-
Notifications
You must be signed in to change notification settings - Fork 2
/
stableDiscordBot.js
1784 lines (1604 loc) · 81.7 KB
/
stableDiscordBot.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
//
// stableDiscordBot.js
//
// Created by Zach Fox on 2020-03-16
//
// Distributed under the MIT License.
// See the accompanying LICENSE.txt file for details.
//
const Discord = require('discord.js');
const discordBackup = require('discord-backup');
const bot = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
const auth = require('./auth.json');
const youtubeAuthToken = auth.youtubeToken;
const ytdl = require('ytdl-core');
const { google } = require('googleapis');
const { googleAuth } = require('google-auth-library');
const fs = require('fs');
const path = require('path');
const https = require('https');
const imageMagick = require('imagemagick');
const ColorScheme = require('color-scheme');
const rgbHex = require('rgb-hex');
const moment = require('moment');
const SQLite = require("better-sqlite3");
const quotesSQL = new SQLite('./quotes/quotes.sqlite');
const wikiSQL = new SQLite('./wiki/wiki.sqlite');
function deleteTempFiles() {
let directory = __dirname + '/temp';
let files = fs.readdirSync(directory);
for (const file of files) {
if (file === "README.md" || file.indexOf(".mp3") > -1) {
continue;
}
fs.unlinkSync(path.join(directory, file));
}
}
function prepareSQLite() {
// Check if the table "quotes" exists.
const quotesTable = quotesSQL.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'quotes';").get();
if (!quotesTable['count(*)']) {
// If the table isn't there, create it and setup the database correctly.
quotesSQL.prepare("CREATE TABLE quotes (id INTEGER PRIMARY KEY, created DATETIME DEFAULT CURRENT_TIMESTAMP, userWhoAdded TEXT, guild TEXT, channel TEXT, quote TEXT);").run();
// Ensure that the "id" row is always unique and indexed.
quotesSQL.prepare("CREATE UNIQUE INDEX idx_quotes_id ON quotes (id);").run();
quotesSQL.pragma("synchronous = 1");
quotesSQL.pragma("journal_mode = wal");
}
// We have some prepared statements to get, set, and delete the quote data.
bot.getQuote = quotesSQL.prepare("SELECT * FROM quotes WHERE guild = ? AND channel = ? AND id = ?;");
bot.getRandomQuote = quotesSQL.prepare("SELECT * FROM quotes WHERE guild = ? AND channel = ? ORDER BY random() LIMIT 1;");
bot.setQuote = quotesSQL.prepare("INSERT OR REPLACE INTO quotes (userWhoAdded, guild, channel, quote) VALUES (@userWhoAdded, @guild, @channel, @quote);");
bot.deleteQuote = quotesSQL.prepare("DELETE FROM quotes WHERE guild = ? AND channel = ? AND id = ?;");
// Check if the table "wiki" exists.
const wikiTable = wikiSQL.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'wiki';").get();
if (!wikiTable['count(*)']) {
// If the table isn't there, create it and setup the database correctly.
wikiSQL.prepare("CREATE TABLE wiki (id INTEGER PRIMARY KEY, created DATETIME DEFAULT CURRENT_TIMESTAMP, userWhoAdded TEXT, guild TEXT, topic TEXT, contents TEXT);").run();
// Ensure that the "id" row is always unique and indexed.
wikiSQL.prepare("CREATE UNIQUE INDEX idx_wiki_id ON wiki (id);").run();
wikiSQL.pragma("synchronous = 1");
wikiSQL.pragma("journal_mode = wal");
}
// We have some prepared statements to get, set, and delete the quote data.
bot.getWikiTopicContents = wikiSQL.prepare("SELECT * FROM wiki WHERE guild = ? AND topic = ? ORDER BY CURRENT_TIMESTAMP LIMIT 1;");
bot.setWikiTopicContents = wikiSQL.prepare("INSERT INTO wiki (guild, topic, contents) VALUES (@guild, @topic, @contents);");
bot.deleteWikiTopicContents = wikiSQL.prepare("DELETE FROM wiki WHERE guild = ? AND topic = ?;");
}
bot.on('ready', () => {
console.log("Clearing temporary file directory...");
deleteTempFiles();
console.log("Cleared temporary file directory.");
console.log("Preparing SQLite tables and statements...");
prepareSQLite();
console.log("Prepared!");
console.log(`Bot online. I'm Clamster! The clam with the pain.\nActually though I'm \`${bot.user.tag}\`.\n`);
});
function showCommandUsage(msg, command, optionalArg) {
if (!commandDictionary[command]) {
let errorMsg = `Couldn't show command usage for command \`${commandInvocationCharacter + command}\`!`;
msg.channel.send(errorMsg);
console.error(errorMsg);
return;
}
let argCombos = commandDictionary[command].argCombos;
let msgToSend = "```\n";
msgToSend += `${commandInvocationCharacter + command}: ${commandDictionary[command].description}`;
if (argCombos) {
msgToSend += `\n\n`;
for (let i = 0; i < argCombos.length; i++) {
if (!optionalArg || (optionalArg && argCombos[i].argCombo.indexOf(optionalArg) > -1)) {
msgToSend += `${commandInvocationCharacter + command} <${argCombos[i].argCombo}>:\n`;
msgToSend += `${argCombos[i].description}\n`;
if (argCombos[i].handler) {
msgToSend += argCombos[i].handler(msg);
msgToSend += `\n`;
}
msgToSend += `\n`;
}
}
}
msgToSend += "\n```";
msg.channel.send(msgToSend);
}
function onSoundsPlaylistAddedTo(msg) {
let guild = msg.guild;
let botCurrentVoiceChannelInGuild = getBotCurrentVoiceChannelInGuild(msg);
if (playlistInfo[guild].currentPlaylistIndex === -1) {
playlistInfo[guild].currentPlaylistIndex = playlistInfo[guild].playlist.length - 1;
changeSoundBasedOnCurrentPlaylistIndex(msg);
} else if (playlistInfo[guild].currentPlaylistIndex > -1 && !botCurrentVoiceChannelInGuild) {
handleStatusMessage(msg, onSoundsPlaylistAddedTo.name, "I'm not connected to a voice channel, so I'm just going to start playing the Sound you just added to the list.", true);
playlistInfo[guild].currentPlaylistIndex = playlistInfo[guild].playlist.length - 1;
changeSoundBasedOnCurrentPlaylistIndex(msg);
}
}
function handleYouTubeSearchThenAdd(msg, args) {
if (!youtubeAuthToken) {
handleErrorMessage(msg, handleYouTubeSearchThenAdd.name, "You haven't set up a YouTube API key, so this command won't work!");
return;
}
let searchQuery = args.join(' ');
let youtubeService = google.youtube('v3');
let parameters = {
'maxResults': '1',
'part': 'snippet',
'q': searchQuery,
'type': 'video',
'regionCode': 'US',
'auth': youtubeAuthToken
};
youtubeService.search.list(parameters, (err, response) => {
if (err) {
handleErrorMessage(msg, "YouTube API Search", `The YouTube API returned an error: ${err}`);
return;
}
if (response.data.items.length === 0) {
handleStatusMessage(msg, "YouTube API Search", `Your search query "${searchQuery}" returned 0 results on YouTube.`)
return;
}
let videoId = response.data.items[0].id.videoId;
let fullUrl = "https://www.youtube.com/watch?v=" + videoId;
let videoTitle = response.data.items[0].snippet.title;
playlistInfo[msg.guild].playlist.push({
"title": videoTitle,
"URL": fullUrl,
"addedBy": msg.author.username
});
handleStatusMessage(msg, handleYouTubeCommand.name, `Adding "${videoTitle}" from ${fullUrl} to the Sounds Playlist.`);
onSoundsPlaylistAddedTo(msg);
});
}
function getYouTubeVideoTitleFromURL(msg, youTubeURL, callback) {
if (!youtubeAuthToken) {
handleErrorMessage(msg, getYouTubeVideoTitleFromURL.name, "You haven't set up a YouTube API key, so I can't get a title from a YouTube video URL!");
return;
}
let videoId = youTubeURL.substr(-11);
let youtubeService = google.youtube('v3');
let parameters = {
'maxResults': '1',
'part': 'snippet',
'q': videoId,
'type': 'video',
'regionCode': 'US',
'auth': youtubeAuthToken
};
youtubeService.search.list(parameters, (err, response) => {
if (err) {
handleErrorMessage(msg, "YouTube API Search", `The YouTube API returned an error: ${err}`);
return;
}
if (response.data.items[0]) {
let videoTitle = response.data.items[0].snippet.title;
callback(msg, videoTitle);
}
});
}
function maybeSetupGuildPlaylist(msg) {
let guild = msg.guild;
if (!playlistInfo[guild]) {
playlistInfo[guild] = {
"playlist": [],
"currentPlaylistIndex": -1,
"repeatMode": "none"
};
}
}
var playlistInfo = {};
function handleYouTubeCommand(msg, args) {
let guild = msg.guild;
let msgSenderVoiceChannel = msg.member.voice.channel;
if (!msgSenderVoiceChannel) {
errorMessage = "Join a voice channel first.";
handleErrorMessage(msg, handleYouTubeCommand.name, errorMessage);
return;
}
maybeSetupGuildPlaylist(msg);
if (args[0] && args[0].indexOf("youtube.com") > -1) {
let youTubeURL = args[0];
handleStatusMessage(msg, handleYouTubeCommand.name, `Adding \`${youTubeURL}\` to the Sounds Playlist.`);
let newPlaylistLength = playlistInfo[guild].playlist.push({
"URL": youTubeURL,
"addedBy": msg.author.username
});
onSoundsPlaylistAddedTo(msg);
getYouTubeVideoTitleFromURL(msg, youTubeURL, (cbMsg, videoTitle) => {
handleStatusMessage(cbMsg, "getYouTubeVideoTitleFromURL Callback", `Updating title associated with \`${youTubeURL}\` to "${videoTitle}".`, true);
playlistInfo[guild].playlist[newPlaylistLength - 1].title = videoTitle;
});
} else if (args[0]) {
handleYouTubeSearchThenAdd(msg, args);
} else {
showCommandUsage(msg, "y");
}
}
const soundSpeakersFolder = "./sounds/";
var soundboardData = {};
function refreshSoundboardData() {
soundboardData = {};
let soundSpeakersSubfolders = fs.readdirSync(soundSpeakersFolder);
for (let i = 0; i < soundSpeakersSubfolders.length; i++) {
let currentSpeaker = soundSpeakersSubfolders[i];
if (currentSpeaker === "README.md" || currentSpeaker.indexOf("sounds.sqlite") > -1) {
continue;
}
let soundIDs = fs.readdirSync(soundSpeakersFolder + currentSpeaker);
for (let j = 0; j < soundIDs.length; j++) {
let soundID = soundIDs[j].slice(0, -4);
if (!soundboardData[soundID]) {
soundboardData[soundID] = [];
}
soundboardData[soundID].push(currentSpeaker);
}
}
}
function formatAvailableSoundIDs(msg) {
refreshSoundboardData();
let availableSoundIDsList = Object.keys(soundboardData).join(", ");
if (availableSoundIDsList.length > 1500) {
availableSoundIDsList = "There's too many Sound IDs to display! Here's some:\n" + availableSoundIDsList.substring(0, 1500) + "...";
}
return availableSoundIDsList;
}
function handleSbvCommand(msg, args) {
let msgSenderVoiceChannel = msg.member.voice.channel;
if (!msgSenderVoiceChannel) {
errorMessage = "Join a voice channel first.";
handleErrorMessage(msg, handleSbvCommand.name, errorMessage);
return;
}
refreshSoundboardData();
maybeSetupGuildPlaylist(msg);
let soundID = args[0];
let person = args[1];
if (soundID && !soundboardData[soundID]) {
handleErrorMessage(msg, handleSbvCommand.name, "Invalid Sound ID.");
} else if (soundID && soundboardData[soundID] && person && soundboardData[soundID].contains(person)) {
handleSuccessMessage(msg, handleSbvCommand.name, `Adding "${soundID}" by ${person} to Sounds Playlist...`);
playlistInfo[msg.guild].playlist.push({
"URL": `${soundSpeakersFolder}${person}/${soundID}.mp3`,
"title": soundID
});
onSoundsPlaylistAddedTo(msg);
} else if (soundID && soundboardData[soundID] && person && !soundboardData[soundID].contains(person)) {
handleErrorMessage(msg, handleSbvCommand.name, "That person didn't say that sound!");
} else if (soundID && soundboardData[soundID] && !person) {
person = soundboardData[soundID][Math.floor(Math.random() * soundboardData[soundID].length)];
handleSuccessMessage(msg, handleSbvCommand.name, `Adding "${soundID}" by ${person} to Sounds Playlist...`);
playlistInfo[msg.guild].playlist.push({
"URL": `${soundSpeakersFolder}${person}/${soundID}.mp3`,
"title": soundID
});
onSoundsPlaylistAddedTo(msg);
} else if (!soundID && !person) {
showCommandUsage(msg, "handleSbvCommand");
} else {
handleErrorMessage(msg, handleSbvCommand.name, "Unhandled case.");
}
}
function getBotCurrentVoiceChannelInGuild(msg) {
let guild = bot.guilds.resolve(msg.guild);
if (!guild.available) {
handleErrorMessage(msg, getBotCurrentVoiceChannelInGuild.name, "Guild unavailable.", true);
return false;
}
return guild.voice && guild.voice.channel;
}
function handleStreamFinished(msg, playLeaveSoundBeforeLeaving) {
if (!playlistInfo[msg.guild] || playlistInfo[msg.guild].repeatMode !== "one") {
handlePlaylistNext(msg, playLeaveSoundBeforeLeaving);
} else if (playlistInfo[msg.guild] && playlistInfo[msg.guild].currentPlaylistIndex && playlistInfo[msg.guild].repeatMode === "one") {
playlistInfo[msg.guild].currentPlaylistIndex--;
handlePlaylistNext(msg);
} else {
handleErrorMessage(msg, handleStreamFinished.name, "The stream finished, and there was an unhandled error case.");
}
}
var streamDispatchers = {};
function playSoundFromURL(msg, URL) {
handleStatusMessage(msg, playSoundFromURL.name, `Attempting to play sound with URL \`${URL}\`...`, true);
let msgSenderVoiceChannel = msg.member.voice.channel;
let voiceConnection = voiceConnections[msgSenderVoiceChannel.id];
if (!msgSenderVoiceChannel) {
handleErrorMessage(msg, playSoundFromURL.name, "It's rude for you to try to change playback while you're not in a voice channel. >:(");
} else if (!voiceConnection) {
handleErrorMessage(msg, playSoundFromURL.name, "The bot somehow doesn't have a voice connection in this server.");
} else if (URL.indexOf("youtube.com") > -1) {
handleStatusMessage(msg, playSoundFromURL.name, `Asking \`ytdl\` nicely to play audio from \`${URL}\`...`, true);
streamDispatchers[msgSenderVoiceChannel] = voiceConnection.play(ytdl(URL, {
'quality': 'highestaudio',
'volume': playlistInfo[msg.guild].volume || 1.0,
'highWaterMark': 1 << 25 // Fixes an issue where `StreamDispatcher` emits "finish" event too early.
}), {
"bitrate": "auto"
});
streamDispatchers[msgSenderVoiceChannel].on('close', () => {
handleVolumeCommand(msg, [1.0]);
streamDispatchers[msgSenderVoiceChannel].removeAllListeners('close');
handleStatusMessage(msg, "StreamDispatcher on 'close'", "The `StreamDispatcher` emitted a `close` event.", true);
});
streamDispatchers[msgSenderVoiceChannel].on('finish', (reason) => {
handleVolumeCommand(msg, [1.0]);
streamDispatchers[msgSenderVoiceChannel].removeAllListeners('finish');
if (reason) {
handleStatusMessage(msg, "StreamDispatcher on 'finish'", `The \`StreamDispatcher\` emitted a \`finish\` event with reason "${reason || "<No Reason>"}".`, true);
}
handleStreamFinished(msg, true);
});
streamDispatchers[msgSenderVoiceChannel].on('error', (err) => {
handleVolumeCommand(msg, [1.0]);
streamDispatchers[msgSenderVoiceChannel].removeAllListeners('error');
handleErrorMessage(msg, "StreamDispatcher on 'error'", `The \`StreamDispatcher\` emitted an \`error\` event. Error: ${err}`, true);
});
} else if (fs.existsSync(URL)) {
handleStatusMessage(msg, playSoundFromURL.name, `Playing \`${URL}\` from filesystem...`, true);
streamDispatchers[msgSenderVoiceChannel] = voiceConnection.play(URL, {
"bitrate": "auto"
});
streamDispatchers[msgSenderVoiceChannel].on('close', () => {
handleVolumeCommand(msg, [1.0]);
streamDispatchers[msgSenderVoiceChannel].removeAllListeners('close');
handleStatusMessage(msg, "StreamDispatcher on 'close'", "The `StreamDispatcher` emitted a `close` event.", true);
});
streamDispatchers[msgSenderVoiceChannel].on('finish', (reason) => {
handleVolumeCommand(msg, [1.0]);
streamDispatchers[msgSenderVoiceChannel].removeAllListeners('finish');
if (reason) {
handleStatusMessage(msg, "StreamDispatcher on 'finish'", `The \`StreamDispatcher\` emitted a \`finish\` event with reason "${reason || "<No Reason>"}".`, true);
}
for (let i = playlistInfo[msg.guild].playlist.length - 1; i >= 0; i--) {
if (playlistInfo[msg.guild].playlist[i].URL === URL) {
playlistInfo[msg.guild].playlist.splice(i, 1);
playlistInfo[msg.guild].currentPlaylistIndex--;
break;
}
}
handleStreamFinished(msg, false);
});
streamDispatchers[msgSenderVoiceChannel].on('error', (err) => {
handleVolumeCommand(msg, [1.0]);
streamDispatchers[msgSenderVoiceChannel].removeAllListeners('error');
handleErrorMessage(msg, "StreamDispatcher on 'error'", `The \`StreamDispatcher\` emitted an \`error\` event. Error: ${err}`, true);
});
} else {
errorMessage = `I don't know how to play the URL \`${URL}\`.`;
handleErrorMessage(msg, playSoundFromURL.name, errorMessage);
}
}
var voiceConnections = {};
function joinVoiceThenPlaySoundFromURL(msg, URL) {
let successMessage, errorMessage;
let guild = msg.guild;
let botCurrentVoiceChannelInGuild = getBotCurrentVoiceChannelInGuild(msg);
let msgSenderVoiceChannel = msg.member.voice.channel;
if (!msgSenderVoiceChannel) {
errorMessage = "Join a voice channel first.";
handleErrorMessage(msg, joinVoiceThenPlaySoundFromURL.name, errorMessage);
} else if (!botCurrentVoiceChannelInGuild || (botCurrentVoiceChannelInGuild !== msgSenderVoiceChannel)) {
msgSenderVoiceChannel.join()
.then((connection) => {
handleSuccessMessage(msg, joinVoiceThenPlaySoundFromURL.name, "I joined your voice channel successfully!", true);
voiceConnections[msgSenderVoiceChannel.id] = connection;
playSoundFromURL(msg, URL);
})
.catch((error) => {
errorMessage = `The bot ran into an error when joining your voice channel: ${error}`;
handleErrorMessage(msg, joinVoiceThenPlaySoundFromURL.name, errorMessage);
});
} else if (botCurrentVoiceChannelInGuild && (botCurrentVoiceChannelInGuild === msgSenderVoiceChannel) && !voiceConnections[msgSenderVoiceChannel.id]) {
handleErrorMessage(msg, joinVoiceThenPlaySoundFromURL.name, "Woah there! I was already in a voice channel, but I didn't realize it. I'll try to leave. If that doesn't work, kick me out manually. Then, try the `play` command.");
botCurrentVoiceChannelInGuild.leave();
} else if (botCurrentVoiceChannelInGuild && (botCurrentVoiceChannelInGuild === msgSenderVoiceChannel) && voiceConnections[msgSenderVoiceChannel.id]) {
playSoundFromURL(msg, URL);
} else {
errorMessage = "Unhandled state.";
handleErrorMessage(msg, joinVoiceThenPlaySoundFromURL.name, errorMessage);
}
}
function handleErrorMessage(msg, functionName, errorMessage, suppressChannelMessage) {
console.error(`Error in \`${functionName}()\` for Guild \`${msg.guild}\`:\n${errorMessage}\n`);
if (!suppressChannelMessage) {
msg.channel.send(errorMessage);
}
}
function handleSuccessMessage(msg, functionName, successMessage, suppressChannelMessage) {
console.log(`Success in \`${functionName}()\` for Guild \`${msg.guild}\`:\n${successMessage}\n`);
if (!suppressChannelMessage) {
msg.channel.send(successMessage);
}
}
function handleStatusMessage(msg, functionName, statusMessage, suppressChannelMessage) {
console.log(`Status in \`${functionName}()\` for Guild \`${msg.guild}\`:\n${statusMessage}\n`);
if (!suppressChannelMessage) {
msg.channel.send(statusMessage);
}
}
function pushPlaylistEndingSoundThenPlayThenLeave(msg) {
let msgSenderVoiceChannel = msg.member.voice.channel;
let voiceConnection = voiceConnections[msgSenderVoiceChannel.id];
let randomEndingSoundFolder = './botResources/sounds/playlistEndingSounds/';
let randomEndingSoundFolderContents = fs.readdirSync(randomEndingSoundFolder);
let randomEndingSoundFilename = randomEndingSoundFolderContents[Math.floor(Math.random() * randomEndingSoundFolderContents.length)];
if (!randomEndingSoundFilename) {
return;
}
let randomEndingSoundPath = randomEndingSoundFolder + randomEndingSoundFilename;
let readStream = fs.createReadStream(randomEndingSoundPath);
if (!msgSenderVoiceChannel) {
// No-op.
} else if (!voiceConnections[msgSenderVoiceChannel.id]) {
handleErrorMessage(msg, pushPlaylistEndingSoundThenPlayThenLeave.name, "No voice connection!");
} else if (streamDispatchers[msgSenderVoiceChannel]) {
streamDispatchers[msgSenderVoiceChannel] = voiceConnection.play(readStream, {
"volume": 1.0
});
streamDispatchers[msgSenderVoiceChannel].on('close', () => {
handleVolumeCommand(msg, [1.0]);
streamDispatchers[msgSenderVoiceChannel].removeAllListeners('close');
});
streamDispatchers[msgSenderVoiceChannel].on('finish', (reason) => {
handleVolumeCommand(msg, [1.0]);
streamDispatchers[msgSenderVoiceChannel].removeAllListeners('finish');
handleStopCommand(msg);
});
streamDispatchers[msgSenderVoiceChannel].on('error', (err) => {
handleVolumeCommand(msg, [1.0]);
streamDispatchers[msgSenderVoiceChannel].removeAllListeners('error');
handleErrorMessage(msg, "StreamDispatcher on 'error'", `The \`StreamDispatcher\` emitted an \`error\` event. Error: ${err}`);
});
} else {
handleErrorMessage(msg, pushPlaylistEndingSoundThenPlayThenLeave.name, 'Unhandled state.');
}
}
function handleStopCommand(msg, args, playLeaveSoundBeforeLeaving) {
let guild = msg.guild;
let botCurrentVoiceChannelInGuild = getBotCurrentVoiceChannelInGuild(msg);
let msgSenderVoiceChannel = msg.member.voice.channel;
let retval = {
"didLeave": false
};
if (!msgSenderVoiceChannel) {
handleErrorMessage(msg, handleStopCommand.name, "It's rude for you to try to change playback while you're not in a voice channel. >:(");
} else if (!botCurrentVoiceChannelInGuild && playlistInfo[guild]) {
handleStatusMessage(msg, handleStopCommand.name, "I'm not in a voice channel, so I can't stop anything. I'll still reset the Current Playlist Index, though.");
playlistInfo[guild].currentPlaylistIndex = -1;
} else if (!botCurrentVoiceChannelInGuild && !playlistInfo[guild]) {
handleStatusMessage(msg, handleStopCommand.name, "I'm not in a voice channel, so I can't stop anything. There's also no playlist associated with this Guild, so I'm going to do nothing.");
} else if (botCurrentVoiceChannelInGuild && !playlistInfo[guild]) {
handleStatusMessage(msg, handleStopCommand.name, "There's no playlist associated with this Guild, so I won't reset the Current Playlist Index. However, I will try to leave the voice channel I'm in. If I don't leave the voice channel, please remove me manually.");
botCurrentVoiceChannelInGuild.leave();
retval.didLeave = true;
} else if (botCurrentVoiceChannelInGuild && playlistInfo[guild] && voiceConnections[msgSenderVoiceChannel.id] && !playLeaveSoundBeforeLeaving) {
handleSuccessMessage(msg, handleStopCommand.name, "Resetting Current Playlist Index and leaving voice channel.", true);
playlistInfo[guild].currentPlaylistIndex = -1;
voiceConnections[msgSenderVoiceChannel.id].disconnect();
voiceConnections[msgSenderVoiceChannel.id] = null;
} else if (botCurrentVoiceChannelInGuild && playlistInfo[guild] && voiceConnections[msgSenderVoiceChannel.id] && playLeaveSoundBeforeLeaving) {
handleSuccessMessage(msg, handleStopCommand.name, "Resetting Current Playlist Index and leaving voice channel after a short sound clip...", true);
pushPlaylistEndingSoundThenPlayThenLeave(msg);
} else if (botCurrentVoiceChannelInGuild && playlistInfo[guild] && !voiceConnections[msgSenderVoiceChannel.id]) {
handleSuccessMessage(msg, handleStopCommand.name, "I'm in a voice channel, but I don't have a Voice Connection. I'm going to reset the Current Playlist Index and attempt to leave. If I don't leave the voice channel, please remove me manually.");
playlistInfo[guild].currentPlaylistIndex = -1;
botCurrentVoiceChannelInGuild.leave();
retval.didLeave = true;
voiceConnections[msgSenderVoiceChannel.id] = null;
}
return retval;
}
function changeSoundBasedOnCurrentPlaylistIndex(msg) {
let successMessage, errorMessage;
let guild = msg.guild;
if (playlistInfo[guild] && playlistInfo[guild].currentPlaylistIndex && playlistInfo[guild].currentPlaylistIndex === -1) {
handlePlaylistNext(msg);
return;
}
let soundToPlay = playlistInfo[guild].playlist[playlistInfo[guild].currentPlaylistIndex].URL;
if (!playlistInfo[guild] || !playlistInfo[guild].playlist) {
errorMessage = "Uh oh! I couldn't find a playlist for your server.";
handleErrorMessage(msg, changeSoundBasedOnCurrentPlaylistIndex.name, errorMessage);
} else if (playlistInfo[guild].playlist && soundToPlay) {
successMessage = `Attempting to play Sound: \`${soundToPlay}\``;
handleSuccessMessage(msg, changeSoundBasedOnCurrentPlaylistIndex.name, successMessage, true);
joinVoiceThenPlaySoundFromURL(msg, soundToPlay);
} else {
errorMessage = "Unhandled state.";
handleErrorMessage(msg, changeSoundBasedOnCurrentPlaylistIndex.name, errorMessage);
}
}
function handlePlaylistNext(msg, playLeaveSoundBeforeLeaving) {
let guild = msg.guild;
let successMessage, errorMessage;
if (!playlistInfo[guild] || !playlistInfo[guild].playlist) {
let errorMessages = [
"You can't 'next' if there's no playlist!",
"You can't fool me :)"
];
errorMessage = errorMessages[Math.floor(Math.random() * errorMessages.length)];
handleErrorMessage(msg, handlePlaylistNext.name, errorMessage);
} else if (playlistInfo[guild] && playlistInfo[guild].currentPlaylistIndex < (playlistInfo[guild].playlist.length - 1)) {
successMessage = "Playing the next Sound...";
handleSuccessMessage(msg, handlePlaylistNext.name, successMessage);
playlistInfo[guild].currentPlaylistIndex++;
changeSoundBasedOnCurrentPlaylistIndex(msg);
} else if (playlistInfo[guild] && playlistInfo[guild].currentPlaylistIndex >= (playlistInfo[guild].playlist.length - 1) && (playlistInfo[guild].repeatMode !== "all" || playlistInfo[guild].playlist.length === 0)) {
successMessage = "There are no more Sounds in the Sound Playlist. Stopping playback...";
handleSuccessMessage(msg, handlePlaylistNext.name, successMessage);
handleStopCommand(msg, null, playLeaveSoundBeforeLeaving);
} else if (playlistInfo[guild] && playlistInfo[guild].currentPlaylistIndex >= (playlistInfo[guild].playlist.length - 1) && playlistInfo[guild].repeatMode === "all") {
successMessage = `The Playlist's repeat mode is "all". That was the end of the playlist. Starting the playlist over...`;
handleSuccessMessage(msg, handlePlaylistNext.name, successMessage);
playlistInfo[guild].currentPlaylistIndex = -1;
handlePlaylistNext(msg);
} else {
errorMessage = "Unhandled state.";
handleErrorMessage(msg, handlePlaylistNext.name, errorMessage);
}
}
function handlePlaylistPrev(msg) {
let guild = msg.guild;
let successMessage, errorMessage;
if (!playlistInfo[guild] || !playlistInfo[guild].playlist) {
let errorMessages = [
"You can't 'prev' if there's no playlist!"
];
errorMessage = errorMessages[Math.floor(Math.random() * errorMessages.length)];
handleErrorMessage(msg, handlePlaylistPrev.name, errorMessage);
} else if (playlistInfo[guild] && playlistInfo[guild].currentPlaylistIndex > 0) {
successMessage = "Skipping to the previous Sound...";
handleSuccessMessage(msg, handlePlaylistPrev.name, successMessage);
playlistInfo[guild].currentPlaylistIndex--;
changeSoundBasedOnCurrentPlaylistIndex(msg);
} else if (playlistInfo[guild] && playlistInfo[guild].currentPlaylistIndex === 0) {
successMessage = "There are no more previous Sounds in the Sound Playlist. Stopping playback...";
handleSuccessMessage(msg, handlePlaylistPrev.name, successMessage);
playlistInfo[guild].currentPlaylistIndex = -1;
changeSoundBasedOnCurrentPlaylistIndex(msg);
} else {
errorMessage = "Unhandled state.";
handleErrorMessage(msg, handlePlaylistPrev.name, errorMessage);
}
}
function handlePlaylistClear(msg) {
let guild = msg.guild;
if (playlistInfo[guild]) {
playlistInfo[guild].playlist = [];
handleSuccessMessage(msg, handlePlaylistClear.name, "Playlist cleared.");
handleStopCommand(msg);
} else {
handleErrorMessage(msg, handlePlaylistClear.name, 'Unhandled state.');
}
}
const possibleRepeatModes = ["none", "one", "all"];
function handlePlaylistChangeRepeatMode(msg, newRepeatMode) {
let guild = msg.guild;
if (!possibleRepeatModes.indexOf(newRepeatMode) === -1) {
handleErrorMessage(msg, handlePlaylistChangeRepeatMode.name, 'Unhandled repeat mode.');
} else if (playlistInfo[guild]) {
playlistInfo[guild].repeatMode = newRepeatMode;
handleSuccessMessage(msg, handlePlaylistChangeRepeatMode.name, `Playlist repeat mode is now "${newRepeatMode}".`);
} else if (!playlistInfo[guild]) {
maybeSetupGuildPlaylist(msg);
handlePlaylistChangeRepeatMode(msg, newRepeatMode);
} else {
handleErrorMessage(msg, handlePlaylistClear.name, 'Unhandled state.');
}
}
function onSoundsPlaylistSpliced(msg, deletedIndex) {
let guild = msg.guild;
if (!playlistInfo[guild].playlist) {
handleErrorMessage(msg, handleDeleteFromPlaylist.name, "I'm not quite sure how you got here...but you don't have a playlist.");
} else if (deletedIndex === playlistInfo[guild].currentPlaylistIndex) {
playlistInfo[guild].currentPlaylistIndex--;
handlePlaylistNext(msg);
}
}
function handleDeleteFromPlaylist(msg, indexToDelete) {
let guild = msg.guild;
indexToDelete = parseInt(indexToDelete);
if (isNaN(indexToDelete)) {
showCommandUsage(msg, "y", "del");
} else if (!playlistInfo[guild].playlist) {
handleErrorMessage(msg, handleDeleteFromPlaylist.name, "There's no playlist from which I can delete.");
} else if (indexToDelete >= playlistInfo[guild].playlist.length || indexToDelete < 0) {
handleErrorMessage(msg, handleDeleteFromPlaylist.name, "Deletion index out of range.");
} else if (indexToDelete < playlistInfo[guild].playlist.length && indexToDelete >= 0) {
playlistInfo[guild].playlist.splice(indexToDelete, 1);
handleSuccessMessage(msg, handleDeleteFromPlaylist.name, `Sound with index ${indexToDelete} deleted from Playlist.`);
onSoundsPlaylistSpliced(msg, indexToDelete);
} else {
handleErrorMessage(msg, handleDeleteFromPlaylist.name, 'Unhandled state.');
}
}
function handlePlaylistList(msg) {
let guild = msg.guild;
if (!playlistInfo[guild] || !playlistInfo[guild].playlist || playlistInfo[guild].playlist.length === 0) {
handleErrorMessage(msg, handlePlaylistList.name, "There's no playlist here.");
} else if (playlistInfo[guild].playlist && playlistInfo[guild].playlist.length > 0) {
console.log(`Listing playlist for guild ${guild}...`);
let playlistString;
for (let i = 0; i < playlistInfo[guild].playlist.length; i++) {
if (playlistInfo[guild].currentPlaylistIndex === i) {
playlistString += "🎶 ";
}
let currentDisplayTitle = playlistInfo[guild].playlist[i].title;
if (!currentDisplayTitle) {
currentDisplayTitle = playlistInfo[guild].playlist[i].URL;
}
playlistString += `${i}. ${currentDisplayTitle}`;
let addedBy = playlistInfo[guild].playlist[i].addedBy;
if (addedBy) {
playlistString += ` - Added by ${addedBy}`;
}
playlistString += `\n`;
}
let splitMsg = stringChop2000(playlistString);
splitMsg.forEach((strToSend) => {
msg.channel.send(`\`\`\`${strToSend}\`\`\``);
});
} else {
handleErrorMessage(msg, handlePlaylistList.name, 'Unhandled state.');
}
}
function handlePlaylistGoto(msg, args) {
let guild = msg.guild;
let indexToGoTo = parseInt(args[1]);
if (isNaN(indexToGoTo)) {
handleErrorMessage(msg, handlePlaylistGoto.name, "Invalid index specified.");
} else if (!playlistInfo[guild] || !playlistInfo[guild].playlist || playlistInfo[guild].playlist.length === 0) {
handleErrorMessage(msg, handlePlaylistGoto.name, "There's no playlist here.");
} else if (indexToGoTo < 0 || indexToGoTo > playlistInfo[guild].playlist.length - 1) {
handleErrorMessage(msg, handlePlaylistGoto.name, "Specified index out of range.");
} else if (playlistInfo[guild].playlist && playlistInfo[guild].playlist.length > 0 && !isNaN(indexToGoTo) && indexToGoTo >= 0 && indexToGoTo <= playlistInfo[guild].playlist.length - 1) {
playlistInfo[guild].currentPlaylistIndex = indexToGoTo;
changeSoundBasedOnCurrentPlaylistIndex(msg);
} else {
handleErrorMessage(msg, handlePlaylistGoto.name, 'Unhandled state.');
}
}
function handlePlaylistCommand(msg, args) {
if (args[0] && args[0] === "next") {
handlePlaylistNext(msg);
} else if (args[0] && args[0] === "back" || args[0] && args[0] === "prev") {
handlePlaylistPrev(msg);
} else if (args[0] && args[0] === "clear") {
handlePlaylistClear(msg);
} else if (args[0] && args[0] === "repeat" && args[1] && args[1] === "none") {
handlePlaylistChangeRepeatMode(msg, args[1]);
} else if (args[0] && args[0] === "repeat" && args[1] && args[1] === "one") {
handlePlaylistChangeRepeatMode(msg, args[1]);
} else if (args[0] && args[0] === "repeat" && args[1] && args[1] === "all") {
handlePlaylistChangeRepeatMode(msg, args[1]);
} else if (args[0] && args[0] === "del" && args[1]) {
handleDeleteFromPlaylist(msg, args[1]);
} else if (args[0] && args[0] === "list") {
handlePlaylistList(msg);
} else if (args[0] && args[0] === "goto" && args[1]) {
handlePlaylistGoto(msg, args);
} else if (args[0] && args[0] === "list" && args[1] && args[1] === "save") {
handleErrorMessage(msg, handlePlaylistCommand, `Wow, you actually wanted to save a playlist? My developer hasn't implemented this yet because nobody uses it. Message him and maybe he'll get this working again.`);
} else if (args[0] && args[0] === "list" && args[1] && args[1] === "load") {
handleErrorMessage(msg, handlePlaylistCommand, `Wow, you actually wanted to load a playlist? My developer hasn't implemented this yet because nobody uses it. Message him and maybe he'll get this working again.`);
} else {
showCommandUsage(msg, "p");
}
}
function handlePlayCommand(msg, args) {
let msgSenderVoiceChannel = msg.member.voice.channel;
if (!msgSenderVoiceChannel) {
handleErrorMessage(msg, handlePlayCommand.name, "It's rude for you to try to change playback while you're not in a voice channel. >:(");
} else if (streamDispatchers[msgSenderVoiceChannel] && streamDispatchers[msgSenderVoiceChannel].paused) {
streamDispatchers[msgSenderVoiceChannel].resume();
} else {
changeSoundBasedOnCurrentPlaylistIndex(msg);
}
}
function handlePauseCommand(msg, args) {
let msgSenderVoiceChannel = msg.member.voice.channel;
if (!msgSenderVoiceChannel) {
handleErrorMessage(msg, handlePauseCommand.name, "It's rude for you to try to change playback while you're not in a voice channel. >:(");
} else if (!streamDispatchers[msgSenderVoiceChannel]) {
handleStatusMessage(msg, handlePauseCommand.name, "Nothing to pause, captain.");
} else if (streamDispatchers[msgSenderVoiceChannel]) {
streamDispatchers[msgSenderVoiceChannel].pause();
}
}
function handleLeaveCommand(msg, args) {
let botCurrentVoiceChannelInGuild = getBotCurrentVoiceChannelInGuild(msg);
if (botCurrentVoiceChannelInGuild) {
handleStopCommand(msg);
} else {
handleErrorMessage(msg, handleLeaveCommand.name, "I'm either not in a voice channel or I can't detect that I'm in one.");
}
}
function handleVolumeCommand(msg, args) {
let msgSenderVoiceChannel = msg.member.voice.channel;
if (!msgSenderVoiceChannel) {
handleErrorMessage(msg, handleVolumeCommand.name, "It's rude for you to try to change playback while you're not in a voice channel. >:(");
return;
}
let volumeChanged = false;
if (!isNaN(args[0]) && playlistInfo[msg.guild] && playlistInfo[msg.guild].volume !== args[0]) {
playlistInfo[msg.guild].volume = args[0];
volumeChanged = true;
} else if (!isNaN(args[0]) && !playlistInfo[msg.guild]) {
playlistInfo[msg.guild] = {
"volume": args[0]
};
volumeChanged = true;
}
if (volumeChanged) {
handleStatusMessage(msg, handleVolumeCommand.name, `Volume changed to \`${args[0]}\`.`)
}
if (!isNaN(args[0]) && streamDispatchers[msgSenderVoiceChannel]) {
streamDispatchers[msgSenderVoiceChannel].setVolume(playlistInfo[msg.guild].volume);
} else if (!isNaN(args[0]) && !streamDispatchers[msgSenderVoiceChannel]) {
// No-op; logic handled by sets of conditionals above.
// We want to set the volume for the current guild's playlist, and that volume
// will get picked up the next time we start playing a Sound.
} else {
showCommandUsage(msg, "vol");
}
}
function handleHelpCommand(msg, args) {
if (args[0] && args[1]) {
showCommandUsage(msg, args[0], args[1]);
} else if (args[0] && !args[1]) {
showCommandUsage(msg, args[0]);
} else if (!args[0]) {
let commandDictionaryKeys = Object.keys(commandDictionary);
let allHelpMessage = `Here are the commands I support right now:\n`;
allHelpMessage += '```';
for (let i = 0; i < commandDictionaryKeys.length; i++) {
allHelpMessage += `${commandDictionaryKeys[i]}\n`
}
allHelpMessage += '```\n';
allHelpMessage += `You can get usage help with each individual command by typing \`${commandInvocationCharacter}help <command>\`.`;
msg.channel.send(allHelpMessage);
} else {
showCommandUsage(msg, "help");
}
}
const emojiFolder = "./bigEmoji/";
function refreshEmojiSystem() {
let emojiFolderContents = fs.readdirSync(emojiFolder);
for (let i = 0; i < emojiFolderContents.length; i++) {
if (emojiFolderContents[i] === "README.md") {
continue;
}
availableEmojis[emojiFolderContents[i].slice(0, -4).toLowerCase()] = emojiFolderContents[i];
}
}
var availableEmojis = {};
function handleEmojiCommand(msg, args) {
if (!args[0] || args[1]) {
showCommandUsage(msg, "e");
return;
}
refreshEmojiSystem();
msg.channel.send({
files: [
{
"attachment": emojiFolder + availableEmojis[args[0].toLowerCase()],
"name": availableEmojis[args[0].toLowerCase()]
}
]
});
}
function formatAvailableEmojiNames(msg) {
refreshEmojiSystem();
return (Object.keys(availableEmojis).join(", "))
}
function getDominantColor(imagePath, callback) {
if (!callback) {
callback = function () { }
}
var imArgs = [imagePath, '-scale', '1x1\!', '-format', '%[pixel:u]', 'info:-']
imageMagick.convert(imArgs, function (err, stdout) {
if (err) {
callback(err);
return;
}
var rgba = stdout.slice(stdout.indexOf('(') + 1, stdout.indexOf(')')).split(',');
var hex = rgbHex(stdout);
callback(null, { "rgba": rgba, "hex": hex });
});
}
function handleRoleColorCommand(msg, args) {
if (args[0] && args[0] === "auto") {
console.log(`Trying to automatially get the dominant color from ${msg.author.avatarURL()}...`);
let filename = `${__dirname}${path.sep}temp${path.sep}${Date.now()}.${(msg.author.avatarURL()).split('.').pop().split('?')[0]}`;
console.log(`Saving profile pic to ${filename}...`);
const file = fs.createWriteStream(filename);
const request = https.get(msg.author.avatarURL(), function (response) {
response.pipe(file);
file.on('finish', function () {
file.close(function () {
console.log(`Saved profile pic to ${filename}!`);
console.log(`Trying to get dominant color...`);
getDominantColor(filename, function (err, outputColorObj) {
fs.unlinkSync(filename);
if (err) {
console.log(`Error when getting dominant color: ${err}`);
msg.channel.send("Yikes, something bad happened on my end. Sorry. Blame Zach.");
return;
}
let outputColorHex = outputColorObj.hex;
let outputColorRgba = outputColorObj.rgba;
let r = parseInt(outputColorRgba[0]);
let g = parseInt(outputColorRgba[1]);
let b = parseInt(outputColorRgba[2]);
let outputColorHue;
let maxRGB = Math.max(r, g, b);
let minRGB = Math.min(r, g, b);
if (maxRGB === r) {
outputColorHue = 60 * (g - b) / (maxRGB - minRGB);
} else if (maxRGB === g) {
outputColorHue = 60 * (2 + (b - r) / (maxRGB - minRGB));
} else {
outputColorHue = 60 * (4 + (r - g) / (maxRGB - minRGB));
}
outputColorHue = Math.round(outputColorHue);
if (outputColorHue < 0) {
outputColorHue += 360;
}
console.log(`\`outputColorHue\` is ${outputColorHue}`);
if (!outputColorHue) {
console.log(`Error when getting dominant color: No \`outputColorHue\`. outputColorObj: ${JSON.stringify(outputColorObj)}`);
msg.channel.send("Yikes, something bad happened on my end. Sorry. Blame Zach, and he'll check the logs.");
return;
}
let scheme = new ColorScheme;
scheme.from_hue(outputColorHue).scheme('contrast');
let colorSchemeColors = scheme.colors();
colorSchemeColors = colorSchemeColors.map(i => '#' + i);
if (outputColorHex.length === 8) {
outputColorHex = outputColorHex.slice(0, 6);
}
outputColorHex = `#${outputColorHex}`;
let guildMember = msg.member;
let memberRoles = guildMember.roles;
memberRoles.highest.setColor(outputColorHex, `User set their color automatically based on their profile picture.`)
.then(updated => {
console.log(`Automatically set color of role named ${memberRoles.highest} to ${outputColorHex} based on their profile picture: ${msg.author.avatarURL()}`);
msg.channel.send(`I've selected ${outputColorHex} for you. You might also like one of the following colors:\n${colorSchemeColors.join(', ')}`);
})
.catch(console.error);
});
});
});
});
} else if (args[0] && ((args[0].startsWith("#") && args[0].length === 7) || (args[0].length === 6))) {
let hexColor = args[0].length === 6 ? "#" + args[0] : args[0];
let guildMember = msg.member;
let memberRoles = guildMember.roles;
memberRoles.highest.setColor(hexColor, `User set their color manually.`)
.then(updated => {
console.log(`Set color of role named ${memberRoles.highest} to ${hexColor}.`);