-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbot.js
2183 lines (2017 loc) · 84.4 KB
/
bot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var Discord = require("discord.js");
var auth = require("./auth.json");
var fetch = require("node-fetch");
var request = require("request");
var exec = require("child_process").exec;
var fs = require("fs");
var logger = require("js-logging");
var config = {};
var err;
try {
config = require("./config.json");
} catch (e) {
err = e;
}
var defaultConfig = require("./default-config.json");
function recursiveDefault(obj, def) {
var keys = Object.keys(def);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (obj[key] == null) {
obj[key] = def[key];
} else if (obj[key] instanceof Array || def[key] instanceof Array) {
if (obj[key] instanceof Array && def[key] instanceof Array) {
obj[key] = obj[key].concat(def[key]);
}
} else if (obj[key] instanceof Object && def[key] instanceof Object) {
recursiveDefault(obj[key], def[key]);
}
}
}
recursiveDefault(config, defaultConfig);
// Load bans if dynamic banning is enabled (Otherwise we should trust config)
var banErr;
if (config.enableDynamicBans) {
try {
var bans = require("./bans.json");
config.bannedUsers = config.bannedUsers.concat(bans);
} catch (e) {
banErr = e;
}
}
// Check if we should set node to permit insecure TLS
if (config.allowInsecure) {
require("process").env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
}
if (config.padLog) {
var longestLengthIn = function (array) {
var max = -1;
for (var i = 0; i < array.length; ++i) {
if (array[i].length > max) {
max = array[i].length;
}
}
return max;
};
// Attempt to pad the log format so that all log entries are the same length
// Assumptions and restrictions documented below
var logging = config.logging;
var string = logging.format;
config.logging.preprocess = function (data) {
// Uppercase the level if we're configured to
if (config.logging.uppercaseLevel)
data.title = data.title.toUpperCase();
// Pad the level so its centered, surrounded by enough spaces to fit the longest level
var longestTitle = longestLengthIn(Object.keys(logging.filters));
if (data.title.length < longestTitle) {
var diff = longestTitle - data.title.length;
var leftPad = Math.floor(diff / 2);
var rightPad = diff - leftPad;
// Account for a misalignment in testing
// TODO find out why this is needed
leftPad -= 1;
rightPad -= 1;
data.title =
Array(leftPad + 2).join(" ") +
data.title +
Array(rightPad + 2).join(" ");
}
// Pad the line number so it has spaces to its right until its maximum length
var lineLength = 4; // The number of digits the line field is allocated. Currently maxes at 9999 lines
if (data.line.length <= lineLength) {
data.line += Array(lineLength - data.line.length + 2).join(" ");
}
};
}
var log = logger.colorConsole(config.logging); // Use default colors. Change if necessary
// Log config override issues if they were found
if (err) log.warning("Could not load config.json: " + err);
if (banErr) log.warning("Could not load bans.json: " + banErr);
var bot = new Discord.Client({
token: auth.token,
autorun: true,
});
var isPlaying = {};
var reconnectAllowedAt = {};
var reconnectTimeout = 30; // Seconds
var lastSearchedSongs = {};
// Memoization layer around album art, to avoid excessive fetches.
async function getAlbumArt(currentSong) {
if (this.cache == null) {
log.debug("Initializing album art cache...");
this.cache = {};
}
log.debug(`Searching album art cache for '${currentSong}'`);
if (this.cache[currentSong] != null) {
log.debug(
`Found cached art with length ${this.cache[currentSong].length}.`
);
return this.cache[currentSong];
}
log.debug("Cache miss. Fetching art for addition to cache.");
const artURL = config.API.aria.prefix + config.API.aria.albumart;
log.debug(`fetch('${artURL}')`);
const response = await fetch(artURL);
const text = await response.text();
log.debug(`Received response with length ${text.length}.`);
try {
const art = Buffer.from(JSON.parse(text).Picture, "base64");
// If configured to limit the size of the cache, and we're at the limit, drop an artwork to make room.
if (config.maxCachedAlbumArts > 0) {
log.info(
"Album art cache has a maximum configured size. Checking for cleanup need."
);
while (
Object.keys(this.cache).length >= config.maxCachedAlbumArts
) {
log.debug(
`Cache currently has ${
Object.keys(this.cache).length
} artworks, which is at least at the limit of ${
config.maxCachedAlbumArts
}.`
);
const key = Object.keys(this.cache)[0];
log.debug(`Removing artwork cached for '${key}'...`);
delete this.cache[key];
}
log.info("Cache is below the size limit.");
log.debug(
`Current size is ${
Object.keys(this.cache).length
}, configured limit is ${config.maxCachedAlbumArts}.`
);
}
// Now that we know there's at least one clear slot, we can store the new art in there.
this.cache[currentSong] = art;
log.debug("Added art to cache");
return art;
} catch (err) {
log.debug("Encountered error with parse of album art:");
log.debug(err);
return null;
}
}
// This is the single audio stream which will be used for all CadenceBot listeners.
// This saves bandwidth and encoding overhead as compared to having one stream for each server.
// As an added bonus, it also keeps all CadenceBot listeners in perfect sync!
// (Seeing as Cadence streams tend to desync over time, this is useful).
const stream = bot.voice.createBroadcast();
// This variable will track our current stream status, for reporting reasons
let streamStatus = "Startup";
// This will be the path we connect to.
// By default, we shall use fallback paths set in config
// But, if configured to try to auto-fetch it, we'll grab the new path and put it here.
let streamPath =
config.API.stream.protocol +
"://" +
config.API.stream.fallbackPrefix +
config.API.stream.fallbackStream;
// This function initializes the stream.
// It is provided to allow the stream to reinitialize itself when it encounters an issue...
// Which appears to happen rather often with the broadcast.
function beginGlobalPlayback() {
streamStatus = "Connecting...";
try {
log.info(`Connecting to music stream at ${streamPath}...`);
stream.play(streamPath, {
bitrate: config.stream.bitrate,
volume: config.stream.volume,
passes: config.stream.retryCount,
});
streamStatus = "Connected.";
} catch (e) {
// Rate-limit restarts due to exceptions: We would rather drop a bit of music
// than fill the log with exceptions.
log.error("Exception during global broadcast stream init: " + e);
streamStatus = "Connection failed.";
setTimeout(beginGlobalPlayback, 100);
}
}
// If the stream path should be set automatically, try to override our streamPath from the upstream.
if (config.API.stream.automatic) {
log.info("Attempting automatic set of steam path.");
const url = config.API.aria.prefix + config.API.aria.listenurl;
log.debug(`Making request to ${url}`);
request.get({ url, form: {} }, (err, response, body) => {
if (!err && body != null) {
log.info("Received response:");
log.info(body);
try {
const path = JSON.parse(body).ListenURL;
streamPath = config.API.stream.protocol + "://" + path;
log.info(`Setting path to ${streamPath} and reconnecting.`);
// Trigger a new playback
beginGlobalPlayback();
} catch (error) {
log.error("Error encountered during parse of listen URL:");
log.error(error);
}
} else {
log.error("Received null body or non-null error!");
log.error(`body: ${body}`);
log.error(`error: ${err}`);
log.error(`Response status code: ${response.statusCode}`);
}
});
}
// Start up the stream before we initialize event handlers.
// This means that playback can begin as soon as the bot can handle a command.
beginGlobalPlayback();
// Add event handlers for the stream.
// When the stream ends, reconnect and resume it.
// (We don't ever want CadenceBot to lose audio)
stream.on("end", function () {
log.info("Global broadcast stream ended, restarting in 15ms.");
streamStatus = "Ended.";
// Rate-limit end restarts less aggressively: If this is not done,
// we tend to spam the log and our connection to the stream.
setTimeout(beginGlobalPlayback, 15);
});
// Log errors.
stream.on("error", function (err) {
log.error("Global broadcast stream error: " + err);
// End should be triggered as well if this interrupts playback...
// If this doesn't happen, add a call to beginGlobalPlayback here.
// Status can help notice this (If the stream is dead and the status is this one)
streamStatus = "Failed.";
});
// Log warnings.
// Keep warnings up for five minutes
stream.on("warn", function (warn) {
log.warning("Global broadcast stream warning: " + warn);
streamStatus = "Connected, in warning state.";
setTimeout(() => {
streamStatus = "Connected.";
}, 300000);
});
// Defined later: Filters that one-step-request attempts to use to choose a song to request
// Filters are queried one at a time, in order of appearance (by iterating over the keys)
// They are stored as an associative array "name": filter, where the name will be used for logging
// Each filter is a function, accepting an array of songs (the lastSearchedSongs entry for the current channel during one-step-request), plus the request string,
// and returning an integer (the number to pass to a mock request - one plus the index of the target song)
// If the filter cannot choose a single song to request, it may return the subset of results which pass the filter
// The implementation should replace the array being searched with this subset
// These filters should, however, come as late as reasonable, so as to not filter out results another filter would select unless these are incorrect
// If the filter cannot choose a single song to request, but would not like to narrow the search space, it should return a falsy value (0).
// If the implementation passes all filters without selecting a result,
// It will present the remaining options to the user as if it was `search`, and have them choose a request normally (manual selection filter)
var oneStepRequestFilters;
function songFormat(song) {
return (
'"' +
(song.title || song.Title) +
'" by ' +
(song.artist || song.Artist)
);
}
function searchResultsFormat(songs) {
var response = "";
for (var i = 0; i < songs.length; ++i) {
response += " " + (i + 1) + ") " + songFormat(songs[i]) + "\n";
}
return response;
}
function nowPlayingFormat(text) {
var json = JSON.parse(text);
return songFormat(json);
}
function splitOnLastLine(text, length, separator = "\n") {
text = text.substring(0, length);
index = text.lastIndexOf(separator);
if (index == -1) return text;
return text.substring(0, index);
}
function sendLongReply(message, text, length = 2000) {
// Proactive bugfix: Make sure that length isn't above 2000 (which is where Discord caps messages)
if (length > 2000) length = 2000;
// Special handling for messages that don't actually need long behavior
if (text.length <= length - message.author.id.toString().length - 5) {
message.reply(text);
return;
}
// Special handling for the first part of the message.
var response = splitOnLastLine(
text,
length - message.author.id.toString().length - 5
);
message.reply(response);
text = text.substring(response.length + 1);
// If the text starts with a whitespace character, discord will strip it. This prevents that.
if (/\s/.test(text.charAt(0))) {
text = "_" + text.charAt(0) + "_" + text.substring(1);
}
while (text.length > length) {
response = splitOnLastLine(text, length);
message.channel.send(response);
text = text.substring(response.length + 1);
// If the text starts with a whitespace character, discord will strip it. This prevents that.
if (/\s/.test(text.charAt(0))) {
text = "_" + text.charAt(0) + "_" + text.substring(1);
}
}
if (text.length > 0) message.channel.send(text);
}
function sendLongMessage(channel, text, length = 2000) {
// Proactive bugfix: Make sure that length isn't above 2000 (which is where Discord caps messages)
if (length > 2000) length = 2000;
// Special handling for messages that don't actually need long behavior
if (text.length <= length) {
channel.send(text);
return;
}
while (text.length > length) {
var response = splitOnLastLine(text, length);
channel.send(response);
text = text.substring(response.length + 1);
// If the text starts with a whitespace character, discord will strip it. This prevents that.
if (/\s/.test(text.charAt(0))) {
text = "_" + text.charAt(0) + "_" + text.substring(1);
}
}
if (text.length > 0) channel.send(text);
}
function selectOne(array) {
// First, 'cook' array into a flat list of strings
// (allowing for the {option: '', weight: <n>} syntax)
const options = array.flatMap(option => {
// A plain string is returned intact
if (typeof option === "string") return option;
// Assume if we don't have a string we have an object with the above syntax.
return new Array(option.weight).fill(option.option);
});
// Now choose out of the remaining options.
return options[Math.round(Math.random() * (options.length - 1))];
}
// Does the leg work of choosing a voice channel for play to default to
// Accepts an array of Discord.js GuildChannels
function playChannelSelector(guildChannels) {
if (!(guildChannels instanceof Array) || guildChannels.length == 0) {
log.error(
"Channel selector was either not given an array or was given an empty array."
);
log.info("Was given:\n\n" + JSON.stringify(guildChannels) + "\n\n");
return null;
}
log.debug(
"Searching through channels object:\n\n" +
JSON.stringify(guildChannels) +
"\n\n"
);
voiceChannels = guildChannels.filter(channel => channel.type == "voice");
log.debug(
"Narrowed channels to voice channels:\n\n" +
JSON.stringify(voiceChannels + "\n\n")
);
var startsWith = false;
var includes = false;
for (var channel of voiceChannels) {
log.debug("Trying channel " + channel.name);
for (var i = 0; i < config.playAutoselectChannels.length; ++i) {
var name = config.playAutoselectChannels[i];
log.debug("Comparing against configured test name " + name);
if (caselessCompare(channel.name, name)) {
log.debug("Full match. Returning");
return channel;
}
if (startsWith === false) {
if (
caselessCompare(
channel.name.substring(0, name.length),
name
)
) {
log.debug("Prefix match. Storing for later use.");
startsWith = channel;
}
if (includes === false) {
if (
channel.name
.toLocaleUpperCase()
.includes(name.toLocaleUpperCase())
) {
log.debug("Inclusion match. Storing for later use.");
includes = channel;
}
}
}
}
}
if (startsWith !== false) {
log.debug("Found a prefix match. Returning channel " + startsWith.name);
return startsWith;
}
if (includes !== false) {
log.debug(
"Found an inclusion match. Returning channel " + includes.name
);
return includes;
}
log.debug(
"No matches found. Returning default match (first channel): " +
voiceChannels[0].name
);
return voiceChannels[0];
}
// Parses a time string (1d2h3m4s) into a number of milliseconds (93784000) according to the mapping defined by dict
// Anything with no suffix is considered as a number of milliseconds.
// The numbers must be integers - No floats are permitted.
function parseTimeString(
str,
dict = {
d: 24 * 3600 * 1000,
h: 3600 * 1000,
m: 60 * 1000,
s: 1000,
}
) {
var time = 0;
str = str.trim();
while (str.length > 0) {
var index = str.search(/\D/);
if (index < 1) {
var count = parseInt(str);
if (isNaN(count)) throw { errorMsg: "Not a number", problem: str };
time += count;
break;
}
var count = parseInt(str);
if (isNaN(count)) throw { errorMsg: "Not a number", problem: str };
var rest = str.substr(index);
var end = rest.search(/\d/);
var suffix;
if (end > 0) {
suffix = rest.substr(0, end).trim();
} else {
suffix = rest;
rest = "";
}
if (dict.hasOwnProperty(suffix)) {
count *= dict[suffix];
time += count;
} else {
throw { errorMsg: "Unrecognized unit", problem: suffix };
}
str = rest.substr(end).trim();
}
return time;
}
// Does the inverse of the above - Convert a number of seconds into a human-readable time string (milliseconds don't matter)
function generateTimeString(seconds, secondsPrecision = 2) {
let result = "";
// Handle very odd errors somewhat sanely.
if (seconds < 0) {
return "a few minutes";
}
// Handle days (24*60*60=86400 seconds)
if (seconds > 86400) {
const days = Math.floor(seconds / 86400);
seconds %= 86400;
if (days == 1) {
result += "one day, ";
} else {
result += days.toFixed(0) + " days, ";
}
}
// Now hours (60*60=3600 seconds)
if (seconds > 3600) {
const hours = Math.floor(seconds / 3600);
seconds %= 3600;
if (hours == 1) {
result += "one hour, ";
} else {
result += hours.toFixed(0) + " hours, ";
}
}
// Now minutes
if (seconds > 60) {
const minutes = Math.floor(seconds / 60);
seconds %= 60;
if (minutes == 1) {
result += "one minute, ";
} else {
result += minutes.toFixed(0) + " minutes, ";
}
}
// Now seconds
if (seconds == 1) {
result += "one second";
} else if (seconds > 0) {
result += seconds.toFixed(secondsPrecision) + " seconds";
} else {
// Remove the ' ,' from the end
result = result.substring(0, result.length - 2);
}
// Just in case we managed to encounter an interesting timing edge case...
if (result == "") {
// Let the user think things are mostly sane.
result = "one second";
}
return result;
}
// Returns the UTC offset of the local timezone of the given date
// (ie UTC+5:00)
function getUTCOffset(date = new Date()) {
var hours = Math.floor(date.getTimezoneOffset() / 60);
var out;
// Note: getTimezoneOffset returns the time that needs to be added to reach UTC
// IE it's the inverse of the offset we're trying to divide out.
// That's why the signs here are apparently flipped.
if (hours > 0) {
out = "UTC-";
} else if (hours < 0) {
out = "UTC+";
} else {
return "UTC";
}
out += hours.toString() + ":";
var minutes = (date.getTimezoneOffset() % 60).toString();
if (minutes.length == 1) minutes = "0" + minutes;
out += minutes;
return out;
}
// This function handles alias expansion for core commands.
// It should be passed the content string of the message, and it will
// return the 'canonical' (de-aliased) form of any command alias within.
function coreAliasTranslation(content) {
log.debug("Canonicalizing message: " + content);
// Iterate over all aliases we recognize.
for (const alias of config.commandAliases) {
// Skip this alias if it is disabled.
if (alias.disabled) continue;
// If this alias is a prefix-match...
if (alias.prefix) {
// And our message starts with the alias text...
if (content.startsWith(alias.alias)) {
// Then parse out the rest of the message after the alias and canonicalize the prefix
log.debug(
"Matched prefix alias: " + JSON.stringify(alias, null, 4)
);
const result =
config.commands[alias.target] +
content.substring(alias.alias.length);
log.debug("Canonicalized to " + result);
return result;
}
// If the alias is not a prefix match, and the message exactly matches the alias text...
} else if (content === alias.alias) {
// Then return the canonicalized command.
log.debug(
"Matched exact-match alias: " + JSON.stringify(alias, null, 4)
);
return config.commands[alias.target];
}
}
// If no alias matched our message, return the content untouched.
log.debug("Message is already canonical.");
return content;
}
// Saves bannedUsers to disk
function saveBans(bannedUsers, file = "./bans.json") {
if (config.enableDynamicBans) {
var str = JSON.stringify(bannedUsers, null, 4);
fs.writeFile(file, str, e => {
if (e) log.warning("Could not save bannedUsers to disk: " + e);
else log.info("Saved new ban list to " + file);
log.debug("Banlist:\n" + str);
});
}
}
function command(message) {
// Check banned users.
var removeBans = [];
if (config.bannedUsers) {
for (var tag of config.bannedUsers) {
var ID = tag;
if (tag instanceof Object) {
ID = tag.id;
var now = new Date().getTime();
var start = tag.start
? Date.parse(tag.start)
: Number.NEGATIVE_INFINITY;
var end = tag.end
? Date.parse(tag.end)
: Number.POSITIVE_INFINITY;
if (isNaN(start)) start = Number.NEGATIVE_INFINITY;
if (isNaN(end)) end = Number.POSITIVE_INFINITY;
// Apply banning if user is within the time window [start, end]
if (now < start) {
// Ban has not yet started. Skip this ban setting and check later.
continue;
} else if (now > end) {
// Ban has ended. Note that we should remove it from configuration and continue.
removeBans.push(config.bannedUsers.indexOf(tag));
continue;
}
}
if (message.author.id == ID) {
return;
}
}
}
// Ensure removes are sorted
removeBans.sort(function (a, b) {
return a - b;
});
// Now iterate through them and remove them (indexes will be stable now that we're removing them in reverse order)
for (var ban of removeBans) {
config.bannedUsers.splice(ban, 1);
}
// If at least one ban got removed, save our ban list without the removed bans
if (removeBans.length != 0) {
saveBans(config.bannedUsers);
}
removeBans = null;
// Make sure we have a canonical form of any aliased core commands
const messageContent = coreAliasTranslation(message.content);
if (messageContent === config.commands.play) {
log.notice("Received play command.");
if (isPlaying[message.guild.id]) {
log.info("Already playing in server " + message.guild.name);
message.reply("Don't you have enough Cadence already?");
} else {
var voiceChannel = message.member.voice.channel;
if (!voiceChannel) {
log.warning(
"User " +
message.member.user.tag +
" is not in a voice channel in server " +
message.guild.name +
"."
);
log.warning("Performing connection to autoselected channel.");
voiceChannel = playChannelSelector(
message.guild.channels.cache.array()
);
if (voiceChannel) {
log.notice("Selected channel " + voiceChannel.name + ".");
}
}
if (voiceChannel) {
log.info(
"Attempting to join voice channel " +
voiceChannel.name +
" in server " +
message.guild.name
);
var rAA = new Date();
rAA.setSeconds(rAA.getSeconds() + reconnectTimeout);
reconnectAllowedAt[voiceChannel.id] = rAA;
isPlaying[message.guild.id] = true;
voiceChannel
.join()
.then(connection => {
log.notice(
"Joined. Beginning playback (channel bitrate=" +
voiceChannel.bitrate +
")."
);
const dispatch = connection.play(stream);
dispatch.on("end", end => {
log.warning(
"Stream ended. Playback was in server " +
message.guild.name +
", channel " +
voiceChannel.name
);
if (!isPlaying[message.guild.id]) return;
log.warning("Error was: " + end);
isPlaying[message.guild.id] = false;
if (
new Date() < reconnectAllowedAt[voiceChannel.id]
) {
log.notice(
"Before reconnect timer for channel " +
message.guild.name +
":" +
voiceChannel.name +
". Disconnecting"
);
message.reply(
"Since I've already tried to reconnect in the last " +
reconnectTimeout +
" seconds, I won't try again.\n\nRun \"" +
config.commands.play +
'" if you want me to try again.'
);
voiceChannel.leave();
return;
}
log.debug(
"Was allowed to reconnect to channel with id " +
voiceChannel.id +
" before " +
reconnectAllowedAt[voiceChannel.id]
);
message.reply(
"Hm, I seem to have lost Cadence.\n\nLet me see if I can get it back for you."
);
// Issue a spurious nowplaying to get it in the log.
// Should remove this before sending to prod, probably
var msg = {};
msg.content = config.commands.nowplaying;
msg.reply = function (s) {
log.debug("Sent message: " + s);
};
msg.channel = {
send: d => {
log.debug(
`Sent additional data with length ${d.length}.`
);
},
};
log.notice(
"Sending false nowplaying command in server " +
message.guild.name +
"...\n"
);
command(msg);
// Now, we want to reissue ourselves a play command
// equivalent to the original one, to begin playback on
// the same channel.
// At a glance, that means reissuing the original message.
// However, if the user has since disconnected...
// ... We'll generate a spurious error.
// The play code wants to connect to the user's channel:
// It doesn't know what channel to connect to if the user
// isn't connected.
// We, however, do.
// So, if there isn't a VC, we need to mock it.
// At the same time, the user could be in the wrong VC.
// That would make us connect to the incorrect channel.
// Basically, we just generally want to mock the VC.
// That's why the naïve implementation (command(message))
// isn't the one we use here.
msg = {};
msg.content = messageContent;
msg.reply = function (r) {
message.reply(r);
};
msg.member = {};
msg.member.voice = { channel: voiceChannel };
msg.guild = message.guild;
log.notice(
"Sending mocked play command in server " +
message.guild.name +
"...\n"
);
command(msg);
});
})
.catch(err => log.critical(err));
} else {
log.error(
"User " +
message.member.user.tag +
" is not in a voice channel in server " +
message.guild.name +
"."
);
message.reply(
"You need to be in a voice channel for me to play Cadence in it, この馬鹿!"
);
}
}
} else if (messageContent === config.commands.stop) {
log.notice("Received stop command.");
if (isPlaying[message.guild.id]) {
var voiceChannel = message.member.voice.channel;
log.info(
"Attempting to disconnect from channel in " +
message.guild.name +
"."
);
if (voiceChannel) {
isPlaying[message.guild.id] = false;
voiceChannel.leave();
log.notice(
"Disconnected from channel " + voiceChannel.name + "."
);
} else {
log.notice("User not in a voice channel.");
message.reply(
"I dunno, I'd prefer if someone in the channel told me to stop."
);
}
} else {
log.error("Not currently playing.");
message.reply("OK, OK, I get it, you don't like me, sheesh!");
}
} else if (messageContent === config.commands.help) {
log.notice("Received help command.");
var help = "";
help =
"I have " +
Object.keys(config.commands).length +
" commands. They are:\n";
for (var key in config.commands) {
if (config.commands.hasOwnProperty(key)) {
var paramList = "";
if (config.commandDescriptions[key].parameters) {
paramList = config.commandDescriptions[key].parameters
.map(x => "<" + x + ">")
.join(" ");
}
help +=
' "' +
config.commands[key] +
paramList +
'" - ' +
config.commandDescriptions[key].description +
"\n";
}
}
message.reply(help);
log.notice("Issued help message.");
} else if (messageContent === config.commands.nowplaying) {
log.notice("Received nowplaying command.");
const url = config.API.aria.prefix + config.API.aria.nowplaying;
log.info("Issuing fetch request to " + url);
fetch(url).then(async response => {
log.info("Received response.");
const text = await response.text();
log.info("Response text:\n\n" + text + "\n\n");
log.info("Parsing response...");
song = nowPlayingFormat(text);
bot.user.setPresence({ game: { name: song } });
log.notice("Parse complete: Now playing " + song);
message.reply("Now playing: " + song);
// If we have saved album art, attach it
const albumArt = await getAlbumArt(song);
if (albumArt) {
log.info("Found existing album art.");
log.debug(`Stored album art is ${albumArt.length} bytes long`);
const attachment = new Discord.MessageAttachment(
albumArt,
"AlbumArt.png"
);
message.channel.send(attachment);
} else {
log.info("No available album art.");
}
});
} else if (messageContent.startsWith(config.commands.search)) {
log.notice(
"Received search command in text channel " +
message.channel.name +
", server " +
message.guild.name +
"."
);
log.debug('Received message was "' + message.content + '"');
log.notice(
'Canonicalized form of received message was "' +
messageContent +
'"'
);
const url = config.API.aria.prefix + config.API.aria.search;
var data = {
Search: messageContent.substring(config.commands.search.length),
};
log.info("Making a request to " + url);
log.debug("data.Search=" + data.Search);
var post = {
url,
body: data,
json: true,
followAllRedirects: true,
followOriginalHttpMethod: true,
gzip: true,
};
request.post(post, function (err, response, body) {
log.info("Received response.");
if (!err && (!response || response.statusCode == 200)) {
log.info(
"No error, and either no status code or status code 200."
);
log.debug("Received body:\n\n" + JSON.stringify(body) + "\n\n");
if (body == null || body.length == 0) {
log.info("No results.");
message.reply(
'Cadence has no results for "' + data.Search + '".'
);
} else {
log.info(body.length + " result(s).");
lastSearchedSongs[message.channel.id] = body;
var response = "Cadence returned:\n";
response += searchResultsFormat(body);
log.debug("Issuing response:\n\n" + response + "\n\n");
sendLongReply(message, response);
}
} else {
log.error(