-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
1510 lines (1266 loc) · 57 KB
/
index.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
const fs = require('fs');
const path = require('path');
const Discord = require('discord.js');
var FileWriter = require('wav').FileWriter;
var replaceExt = require('replace-ext');
const ytsr = require('ytsr');
const ytdl = require('ytdl-core');
const ytfps = require('ytfps');
const urlParser = require('js-video-url-parser')
var stringSimilarity = require('string-similarity');
const wordsToNumbers = require('words-to-numbers');
var SpotifyWebApi = require('spotify-web-api-node');
var spotifyUri = require('spotify-uri');
var config;
var spotifyApi;
var musicStream;
var pause = false;
var python = "python3";
var queue = [];
var dispatcher;
var voiceChannel;
let voiceConnections = new Map();
let voiceReceivers = new Map();
let client = new Discord.Client();
let textChannel;
var voiceRecognitionTotalTime = 0;
var voiceRecognitionInstances = 0;
var repeat = false;
var volume = 20;
var afkTimer = 0;
var following = null;
var configFile = './config.json';
client.on('ready', () => {
console.log("[" + new Date().toISOString() + "]", "Started!");
setVolume();
disconnectChannel();
setStatus();
setInterval(deleteOldAudio, 20000); //
setInterval(botAfkTimer, 12000);
return;
});
/*
Still not functional and bad naming scheme. Should be hibernationFile, and its basically an
auto save feature so if the bot crashes, it has necessary data to reboot and go back to doing
what it was doing before.
*/
function updateConfig() {
if (following != null) {
var config = {
displayName: following.displayName,
userID: following.user.id,
currentGuildID: following.guild.id,
paused: pause,
queue: queue
}
} else {
var config = {
displayName: null,
userID: null,
currentGuildID: null,
paused: pause,
queue: queue
}
let data = JSON.stringify(config);
fs.writeFileSync('./configSecond.json', data);
}
}
/*
Reads from volume file to have a history of previously used volumes
*/
async function setVolume() {
try {
var data = fs.readFile('./volume.txt', 'utf8');
var lines = data.split('\n');
volume = lines[lines.length - 1];
} catch (err) {
//If there was an error reading the volume file, set a new volume that will populate the volume file on its own.
song_volume(null, 100)
//volume = 100;
}
}
/*
Removes old temp data of recordings that aren't necessary anymore. Default time till it gets deleted is 60s.
*/
function deleteOldAudio() {
fs.readdir("./voicedata/", (err, files) => {
if (err) console.log("[" + new Date().toISOString() + "]", err);
files.forEach(file => {
try {
if (Date.now() - file.split("-")[0] > 60000) {
fs.unlink(`./voicedata/${file}`, (err) => {
});
}
} catch (err) {
}
});
});
}
/*
Sets discord bot user activity. (My sample uses STREAMING so his icon is purple.)
*/
function setStatus() {
client.user.setActivity(config.statusActivity, {
type: config.statusType,
url: config.statusURL
}).catch(console.error);
}
function disconnectChannel() {
for (const channel of client.channels.cache) {
if (channel[1].type == "voice") {
for (const member of channel[1].members) {
if (member[0] == client.user.id) {
member[1].voice.channel.join().then(connection => {
member[1].voice.channel.leave();
});
console.log("[" + new Date().toISOString() + "]", 'Disconnect from channel')
}
}
}
}
}
/*
Searches guild for member the member with this ID. Useful if you only have userID or user object and need guildMember
*/
async function getGuildMemberFromServerIDAndUserID(serverID, id) {
for (const guild of client.guilds.cache) {
if (guild[1].id == serverID) {
for (const member of guild[1].members.cache) {
if (member[1].id == id) {
return member[1];
}
}
}
}
return;
}
client.on('message', (msg) => {
if (msg.content.charAt(0) === config.commandPrefix) {
textChannel = msg.channel;
var rawString = msg.content.slice(1);
var cmd = rawString.split(' ')[0].toLowerCase();
var tmp = rawString.split(" ");
tmp.shift();
var contents = tmp.join(" ");
switch (cmd) {
case 'test':
getSpotifyList().then(function (genreList) {
var names = [];
for (item of genreList.fields) {
names.push(item.name);
}
//gaming 13
var matches = stringSimilarity.findBestMatch('gaming', names);
if (matches.bestMatch.rating < .7) {
console.log("[" + new Date().toISOString() + "]", "None close found")
} else {
console.log("[" + new Date().toISOString() + "]", matches.bestMatchIndex + ":" + matches.bestMatch.target);
}
});
break;
case 'fix':
playMusic();
break;
case 'times':
msg.channel.send(`Average Speech Recognition Timer: ${voiceRecognitionTotalTime / voiceRecognitionInstances}ms.`);
break;
case 'queue':
//console.log("["+new Date().toISOString()+"]", client.voiceConnections);
sendQueue(msg.channel);
//console.log("["+new Date().toISOString()+"]", queue);
break;
case 'play':
case 'playtop':
if (msg.member.voice.channel) {
var top = true;
if (cmd == 'play') top = false;
voiceChannel = msg.member.voice.channel;
console.log("[" + new Date().toISOString() + "]", 'play command ' + cmd)
commandPlay(msg.member, cmd, contents, top);
} else {
console.log("[" + new Date().toISOString() + "]", "Authors voice channel doesnt exist");
}
break;
case 'spotify':
case 'playlist':
if (config.spotifyClientID && config.spotifyClientSecret) {
if (!msg.member.voice.channel) {
msg.channel.send("`Must be in a voice channel to use this command.`");
} else {
voiceChannel = msg.member.voice.channel;
spotifyGenreList(msg.channel, contents, msg.member);
}
} else {
console.log("[" + new Date().toISOString() + "]", "spotifyClientID or spotifyClientSecret missing. Will not be able to use spotify functionality.");
}
break;
case 'volume':
if (!isNaN(parseInt(contents.trim().split(' ')[0]))) {
song_volume(msg.channel, contents.split(' ')[0]);
} else {
msg.channel.send("`Volume: " + volume + "`");
}
break;
case 'skip':
msg.channel.send("`Song skipped.`")
console.log("[" + new Date().toISOString() + "]", 'Song skipped.');
song_skip();
break;
case 'pause':
msg.channel.send("`Song paused.`")
console.log("[" + new Date().toISOString() + "]", 'Song paused.');
song_pause();
break;
case 'resume':
msg.channel.send("`Song resumed.`")
console.log("[" + new Date().toISOString() + "]", 'Song resumed.');
song_resume();
break;
case 'clear':
msg.channel.send("`Song cleared.`")
console.log("[" + new Date().toISOString() + "]", 'Queue cleared.');
song_clear();
break;
case 'shuffle':
song_shuffle(msg.channel);
break;
case 'follow':
textChannel = msg.channel;
follow(msg.member);
break;
case 'on':
case 'join':
textChannel = msg.channel;
start(msg.member);
break;
case 'off':
case 'stop':
case 'disconnect':
case 'reset':
case 'restart':
stop(msg.member);
break;
case 'crash':
if (msg.author.id == config.discordDevID) {
msg.member.send("Crash command sent.");
process.exit(0);
}
default:
break;
}
//updateConfig();
}
});
/*
Huge command needs to be split up. Uses spotify api to get a list of pregenerated genres from spotify website
and list them out OR if given a genre name string, prints out the spotify playlist for that genre OR
when given a genre name string and number selection of the playlists, starts playing the songs from
that specific playlist.
Example inputs
content = "3 1" //plays the 3rd genre and the 1st playlist from that genre list.
//with no contents, will output a list of all featured genres
//with 1 number content, will output all playlists for that genre
//with 2 numberse in content, will goto that genre and find that playlist and then send to spotifyPlayListOrAlbum()
*/
function spotifyGenreList(channel, content, author) {
content.trim();
if (content.split(' ') == '') {
content = []
} else {
content = content.split(' ');
}
console.log("[" + new Date().toISOString() + "]", content);
var playlistSelected;
if (content.length == 2) {
}
//with no contents, will output a list of all featured genres
//with 1 number content, will output all playlists for that genre
//with 2 numberse in content, will goto that genre and find that playlist and then send to spotifyPlayListOrAlbum()
//
if (content.length <= 2) {
spotifyApi.clientCredentialsGrant().then(function (data) {
console.log("[" + new Date().toISOString() + "]", 'The access token expires in ' + data.body['expires_in']);
console.log("[" + new Date().toISOString() + "]", 'The access token is ' + data.body['access_token']);
// Save the access token so that it's used in future calls
spotifyApi.setAccessToken(data.body['access_token']);
spotifyApi.getCategories({
limit: 50,
offset: 0,
country: 'US',
locale: 'sv_SE'
})
.then(function (data) {
if (content.length == 0) {
channel.send("`Listing all featured genres on spotify.`");
getSpotifyList().then(function (genreList) {
});
/////////////////////////////////////////////////////////////
var embedCount = Math.ceil((data.body.categories.total / 25));
if (embedCount > 2) embedCount = 2;
for (var i = 0; i < embedCount; i++) {
var currentIndex = i + 1; //Add 1 so that we dont start with 0 for nicer look
var genreList = {
title: "\u200b",
url: 'https://open.spotify.com/browse/genres',
color: 1947988, //this is spotify green in their weird color system thing https://leovoel.github.io/embed-visualizer/
footer: {
icon_url: client.user.defaultAvatarURL,
text: `Page ${currentIndex}/${embedCount}`
},
thumbnail: {
url: 'https://1000logos.net/wp-content/uploads/2017/08/Spotify-Logo.png'
},
author: {
name: "Spotify Genre List",
url: "https://open.spotify.com/browse/genres",
icon_url: client.user.defaultAvatarURL
},
fields: []
}
genreList.fields = [];
data.body.categories.items.forEach(function (item, i) {
if (i >= ((currentIndex - 1) * 25) && i < (currentIndex * 25)) {
var name = item.name
genreList.fields.push({
name: '\u200b',
value: "`" + (i + 1) + "`. [" + item.name + "](" + 'https://open.spotify.com/view/' + item.id + "-page" + ")"
});
}
});
//console.log("["+new Date().toISOString()+"]", genreList);
if (genreList.fields.length >= data.body.categories.items.length % 25) { //only sends if it has enough fields to take into account all the playlists
channel.send({
embed: genreList
});
} else {
channel.send('`Error sending this embed.`')
channel.send({
embed: genreList
});
}
}
/////////////////////////////////////////////////////////////////////////////////////
}
if (content.length >= 1) {
var genreSelected = parseInt(content[0]);
if (isNaN(genreSelected)) return;
genreSelected--; //To make up for starting at 0
} else {
return;
}
var selectedGenre = data.body.categories.items[genreSelected];
spotifyApi.getPlaylistsForCategory(data.body.categories.items[genreSelected].id, {
country: 'US',
limit: 50,
offset: 0
})
.then(function (data) {
if (content.length == 1) {
channel.send("`Listing all playlists for " + selectedGenre.name + "`");
//////////////////////////////////////////////////////////////
var embedCount = Math.ceil((data.body.playlists.total / 25));
if (embedCount > 2) embedCount = 2;
for (var i = 0; i < embedCount; i++) {
var currentIndex = i + 1; //Add 1 so that we dont start with 0 for nicer look
var genrePlayListList = {
title: "\u200b",
url: 'https://open.spotify.com/view/' + selectedGenre.id + "-page",
color: 1947988, //this is spotify green in their weird color system thing https://leovoel.github.io/embed-visualizer/
footer: {
icon_url: client.user.defaultAvatarURL,
text: `Page ${currentIndex}/${embedCount}`
},
thumbnail: {
url: 'https://1000logos.net/wp-content/uploads/2017/08/Spotify-Logo.png'
},
author: {
name: selectedGenre.name + " Playlists",
url: 'https://open.spotify.com/view/' + selectedGenre.id + "-page",
icon_url: client.user.defaultAvatarURL
},
fields: []
}
genrePlayListList.fields = [];
data.body.playlists.items.forEach(function (item, i) {
if (i >= ((currentIndex - 1) * 25) && i < (currentIndex * 25)) {
var name = item.name
genrePlayListList.fields.push({
name: '\u200b',
value: "`" + (i + 1) + "`. [" + item.name + "](" + 'https://open.spotify.com/playlist/' + item.id + ")",
url: 'https://open.spotify.com/playlist/' + item.id,
});
}
});
//console.log("["+new Date().toISOString()+"]", genreList);
if (genrePlayListList.fields.length >= data.body.playlists.items.length % 25) { //only sends if it has enough fields to take into account all the playlists
channel.send({
embed: genrePlayListList
});
} else {
//console.log("["+new Date().toISOString()+"]", data.body.playlists);
channel.send('`Error sending this embed.`');
channel.send({
embed: genrePlayListList
});
}
}
///////////////////////////////////////////////////////////////
//console.log("["+new Date().toISOString()+"]", data.body.playlists.items);
}
if (content.length >= 2) {
var playlistSelected = parseInt(content[1]);
if (isNaN(playlistSelected)) return;
playlistSelected--; //To make up for starting at 0
console.log("[" + new Date().toISOString() + "]", "Playing spotify playlist " + data.body.playlists.items[playlistSelected].id);
channel.send("`Playlist selected " + data.body.playlists.items[playlistSelected].name + "`");
spotifyPlaylistOrAlbum(data.body.playlists.items[playlistSelected].id, 'playlist', author)
}
}, function (err) {
console.log("[" + new Date().toISOString() + "]", "Something went wrong!", err);
});
}, function (err) {
console.log("[" + new Date().toISOString() + "]", "Something went wrong!", err);
});
},
function (err) {
console.log("[" + new Date().toISOString() + "]", 'Something went wrong when retrieving an access token', err);
});
}
}
function getSpotifyList() {
return new Promise(function (resolve, reject) {
spotifyApi.clientCredentialsGrant().then(function (data) {
console.log("[" + new Date().toISOString() + "]", 'The access token expires in ' + data.body['expires_in']);
console.log("[" + new Date().toISOString() + "]", 'The access token is ' + data.body['access_token']);
// Save the access token so that it's used in future calls
spotifyApi.setAccessToken(data.body['access_token']);
spotifyApi.getCategories({
limit: 50,
offset: 0,
country: 'US',
locale: 'sv_SE'
})
.then(function (data) {
/////////////////////////////////////////////////////////////
var embedCount = Math.ceil((data.body.categories.total / 25));
if (embedCount > 2) embedCount = 2;
for (var i = 0; i < embedCount; i++) {
var currentIndex = i + 1; //Add 1 so that we dont start with 0 for nicer look
var genreList = {
title: "\u200b",
url: 'https://open.spotify.com/browse/genres',
color: 1947988, //this is spotify green in their weird color system thing https://leovoel.github.io/embed-visualizer/
footer: {
icon_url: client.user.defaultAvatarURL,
text: `Page ${currentIndex}/${embedCount}`
},
thumbnail: {
url: 'https://1000logos.net/wp-content/uploads/2017/08/Spotify-Logo.png'
},
author: {
name: "Spotify Genre List",
url: "https://open.spotify.com/browse/genres",
icon_url: client.user.defaultAvatarURL
},
fields: []
}
genreList.fields = [];
data.body.categories.items.forEach(function (item, i) {
if (i >= ((currentIndex - 1) * 25) && i < (currentIndex * 25)) {
genreList.fields.push({
name: item.name,
number: (i + 1),
value: 'https://open.spotify.com/view/' + item.id + "-page"
});
}
});
//console.log("["+new Date().toISOString()+"]", genreList);
if (genreList.fields.length >= data.body.categories.items.length % 25) { //only sends if it has enough fields to take into account all the playlists
resolve(genreList);
} else {
reject("Error");
}
}
})
})
});
}
/*
First parses different potential volume inputs because could potentially be from speech recognition. Ex. fifty turns into 50
Then updates the dispatcher and updates the volume file.
*/
function song_volume(channel, vol) {
if (isNaN(vol)) {
if (isNaN(wordsToNumbers(vol))) {
return;
} else {
vol = wordsToNumbers(vol);
}
}
if (vol < 0 || vol > 100) return;
if (channel) channel.send("`Volume set to " + vol + ".`");
volume = vol;
fs.appendFile('./volume.txt', '\n' + vol, (err) => {
if (err) throw err;
});
if (dispatcher) {
dispatcher.setVolumeLogarithmic(volume / 100);
}
}
function song_shuffle(channel) {
if (queue.length > 2) {
var tmp = [].concat(queue);
tmp.shift();
tmp = shuffle(tmp);
//console.log("["+new Date().toISOString()+"]", tmp);
var tmp2 = [queue[0]];
for (var i = 0; i < tmp.length; i++) {
tmp2.push(tmp[i]);
//console.log("["+new Date().toISOString()+"]", tmp2);
}
queue = tmp2;
//console.log("["+new Date().toISOString()+"]", tmp2);
//queue = [queue[0]];
//queue.concat(shuffle(tmp));
//console.log("["+new Date().toISOString()+"]", queue);
channel.send("`Queue has been shuffled.`")
} else {
channel.send("`Not enough songs to shuffle.`");
}
}
/* Not my code needs to be fixed. */
function shuffle(arra1) {
var ctr = arra1.length,
temp, index;
// While there are elements in the array
while (ctr > 0) {
// Pick a random index
index = Math.floor(Math.random() * ctr);
// Decrease ctr by 1
ctr--;
// And swap the last element with it
temp = arra1[ctr];
arra1[ctr] = arra1[index];
arra1[index] = temp;
}
return arra1;
}
function sendQueue(channel) {
try {
if (queue.length == 0) {
channel.send("`There are no songs in queue.`");
return;
}
const exEmb = {
title: "__" + queue[0].TITLE + "__",
url: queue[0].URL,
color: 10181046, //this is purple in their weird color system thing https://leovoel.github.io/embed-visualizer/
footer: {
icon_url: client.user.displayAvatarURL(),
text: queue.length + " songs in queue."
},
thumbnail: {
url: queue[0].THUMBNAIL
},
author: {
name: "Song queue",
url: "",
icon_url: client.user.defaultAvatarURL
},
fields: [
]
}
exEmb.fields = [];
queue.forEach(function (video, i) {
if (i < 25 && i > 0) {
var name = queue[i - 1].MEMBER.user.username
exEmb.fields.push({
name: "`Requested by: " + name + "`",
value: "`" + i + "`. [" + video.TITLE + "](" + video.URL + ")",
url: video.URL,
//value: "`Requested By: " + video.MEMBER.user.username + "`"
});
//exampleEmbed.addField(`${i}. [${video.TITLE}](${video.URL})`, '.');
}
});
channel.send({
embed: exEmb
});
} catch (err) {
channel.send("`Error while sending queue.`");
console.log("[" + new Date().toISOString() + "]", queue);
console.log("[" + new Date().toISOString() + "]", err);
}
}
/*
All of these are pretty obvious utility functions for the dispatcher.
*/
function song_clear() {
if (queue.length >= 1) {
queue = [queue[0]];
}
}
function song_resume() {
if (dispatcher) {
pause = false;
dispatcher.resume();
}
}
function song_pause() {
if (dispatcher) {
pause = true;
dispatcher.pause();
}
}
function song_skip() {
if (dispatcher) {
dispatcher.end();
playMusic();
//dispatcher.end();
}
}
/*
Simple AFK timer so that bot doesnt stick in voice channels for too long.
Its attached to a setInterval() function so that this function gets run every 2 minutes.
Once the AFkTimer count value gets to 5 (10 minutes), with 0 people in the same voice channel
that hes in, he will leave and remove the song queue.
*/
function botAfkTimer() {
if (client.voice.connections.size > 0) {
//console.log("["+new Date().toISOString()+"]", client.voiceConnections.first(1)[0].channel.members.size);
if (client.voice.connections.first(1)[0].channel.members.size < 2) {
afkTimer++;
} else {
afkTimer = 0;
}
}
if (afkTimer >= 5) { //2 minutes 5 instances so 10 minute timer.
console.log("[" + new Date().toISOString() + "]", 'Been AFK for 10 minutes. DCing');
stop(client.voice.connections.first(1)[0].channel.members.first(1)[0]);
}
}
//find if message is link
//if message is valid link, get youtube info
//else do youtube search query and get youtube info for first
//after either, add to queue
function commandPlay(member, cmd, content, top) {
try {
searchYoutube(member, content, top);
return;
} catch (err) {
console.log("[" + new Date().toISOString() + "]", `Error on commandPlay function: ${err}`);
}
}
function errorFindingVideo(err) {
console.log("[" + new Date().toISOString() + "]", err);
console.log("[" + new Date().toISOString() + "]", 'Error finding video');
textChannel.send("`Error: Error finding video.`")
song_skip();
// fs.appendFileSync('./console.txt', 'Error finding video' + '\n');
}
async function searchYoutube(author, content, top) {
// console.log("["+new Date().toISOString()+"]", urlParser.parse(content));
if (urlParser.parse(content)) {
//Checks to see if its a video, on youtube, and IS NOT a playlist
if ((urlParser.parse(content)).mediaType == 'video' && (urlParser.parse(content)).provider == 'youtube' && !(urlParser.parse(content)).list) {
console.log("[" + new Date().toISOString() + "]", 'valid youtube url');
if (content.indexOf("start_radio") == -1) {
var video = await ytdl.getBasicInfo(content);
var chosenVideo;
//console.log("["+new Date().toISOString()+"]", video);
chosenVideo = {
URL: content,
TITLE: video.videoDetails.title,
DURATION: video.videoDetails.lengthSeconds,
THUMBNAIL: video.videoDetails.thumbnails[0].url,
MEMBER: author
}
add_to_queue(chosenVideo, top, false)
}
//If its not a video, then check if its youtube and IS a list
} else if ((urlParser.parse(content)).provider == 'youtube' && (urlParser.parse(content)).list) {
console.log("[" + new Date().toISOString() + "]", 'going for ' + (urlParser.parse(content)).list);
ytfps((urlParser.parse(content)).list).then(items => {
textChannel.send('`Adding playlist to queue.`');
textChannel.send("`" + items.videos.length + " songs from playlist added to queue.`");
items.videos.forEach(item => {
if (item.title == 'Private video') {
return;
}
var thumbnailURL = 'https://awmaa.com/wp-content/uploads/2017/04/default-image.jpg'
if (item.thumbnail_url) thumbnailURL = item.thumbnail_url;
var video = {
URL: `https://www.youtube.com/watch?v=${item.id}`,
TITLE: item.title,
DURATION: parseInt(item.milis_length / 1000),
THUMBNAIL: thumbnailURL,
MEMBER: author
};
add_to_queue(video, top, true);
})
}).catch(err => {
throw err;
});
}
} else if (content.indexOf('spotify') != -1) {
if (spotifyUri.parse(content).type == 'album' || spotifyUri.parse(content).type == 'playlist') {
spotifyPlaylistOrAlbum(spotifyUri.parse(content).id, spotifyUri.parse(content).type, author);
}
} else {
try {
var video = null;
const filters = await ytsr.getFilters(content);
const filter = filters.get('Type').get('Video');
var options = {
limit: 5,
nextpageRef: filter.ref,
}
const searchResults = await ytsr(content, options);
// console.log("["+new Date().toISOString()+"]", searchResults)
const videos = searchResults.items;
for (var i = 0; i < videos.length; i++) { //Checks if the duration of the video is greater than 0 to avoid live videos.
if (videos[i].duration) {
video = videos[i];
break;
}
}
if (video == null) {
console.log("[" + new Date().toISOString() + "]", 'No video found.');
// fs.appendFileSync('./console.txt', 'No Video found' + '\n');
throw new Error("No video found")
}
var hours = 0;
var minutes = 0;
var seconds = 0;
var durationArray = video.duration.split(':');
if (durationArray.length == 2) { //minutes:seconds
minutes = durationArray[0];
seconds = durationArray[1];
} else if (durationArray.length == 3) { //hours:minutes:seconds
hours = durationArray[0];
minutes = durationArray[1];
seconds = durationArray[2];
}
var durationSeconds = (hours * 3600) + (minutes * 60) + (seconds * 1); //duration in seconds
var chosenVideo;
chosenVideo = {
URL: video.url,
TITLE: video.title,
DURATION: durationSeconds,
THUMBNAIL: video.bestThumbnail.url,
MEMBER: author
};
add_to_queue(chosenVideo, top, false)
} catch (err) {
console.log("[" + new Date().toISOString() + "]", err);
}
}
}
function spotifyPlaylistOrAlbum(id, type, author) {
try {
spotifyApi.clientCredentialsGrant().then(
function (data) {
console.log("[" + new Date().toISOString() + "]", 'The access token expires in ' + data.body['expires_in']);
console.log("[" + new Date().toISOString() + "]", 'The access token is ' + data.body['access_token']);
// Save the access token so that it's used in future calls
spotifyApi.setAccessToken(data.body['access_token']);
if (type == 'playlist') {
spotifyApi.getPlaylist(id).then(function (data) {
//console.log("["+new Date().toISOString()+"]", data.body.tracks.items);
data.body.tracks.items.forEach(function (item, index) {
if (item.track == null) return;
var song_name = item.track.name;
var artists = [];
item.track.artists.forEach(artist => {
artists.push(artist.name);
})
var track = {
URL: `https://open.spotify.com/track/${item.track.id}`,
TITLE: (artists.join(', ') + " - " + song_name),
DURATION: parseInt(item.track.duration_ms / 1000),
THUMBNAIL: 'https://1000logos.net/wp-content/uploads/2017/08/Spotify-Logo.png',
MEMBER: author
};
add_to_queue(track, false, true);
});
}, function (err) {
console.log("[" + new Date().toISOString() + "]", 'Something went wrong!', err);
});
} else if (type == 'album') {
spotifyApi.getAlbumTracks(id, {
limit: 50,
offset: 0
})
.then(function (data) {
//console.log("["+new Date().toISOString()+"]", data.body.items);
data.body.items.forEach(function (item, index) {
if (item == null) return;
var song_name = item.name;
var artists = [];
item.artists.forEach(artist => {
artists.push(artist.name);
})
var track = {
URL: `https://open.spotify.com/track/${item.id}`,
TITLE: (artists.join(', ') + " - " + song_name),
DURATION: parseInt(item.duration_ms / 1000),
THUMBNAIL: 'https://1000logos.net/wp-content/uploads/2017/08/Spotify-Logo.png',
MEMBER: author
};
add_to_queue(track, false, true);
});
}, function (err) {
console.log("[" + new Date().toISOString() + "]", 'Something went wrong!', err);
});
} else {
console.log("[" + new Date().toISOString() + "]", 'Not playlist or album');
}
},
function (err) {
console.log("[" + new Date().toISOString() + "]", 'Something went wrong when retrieving an access token', err);
});
} catch (err) {
console.log("[" + new Date().toISOString() + "]", err);
}
}
function add_to_queue(video, top, playlist) {
console.log("[" + new Date().toISOString() + "]", "adding to queue " + video.URL);
var position = queue.length;
if (top == true) {
if (queue.length > 0) {
position = 1;
} else {
position = 0;
}
}
if (playlist == false) {
const addedToQueueEmbed = new Discord.MessageEmbed()
.setColor('#9b59b6')
.setTitle(video.TITLE)
.setURL(video.URL)
.setAuthor('Added to queue', video.MEMBER.user.avatarURL, '')
.setThumbnail(video.THUMBNAIL)
.addField('Song Duration', convertTime(video.DURATION), true)
.addField('Position in queue', position, true);
textChannel.send(addedToQueueEmbed);
}