-
Notifications
You must be signed in to change notification settings - Fork 1
/
index_deployable.js
1763 lines (1670 loc) · 73.3 KB
/
index_deployable.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 PREFIX = "?";
const ytdl = require('ytdl-core');
const ytpl = require('ytpl');
const YouTube = require("discord-youtube-api");
const Discord = require("discord.js");
const filestream = require("fs");
const client = new Discord.Client();
const sauce = 'https://github.com/ItsRuntimeException/Paimon-chan';
const DICE = 6;
/* set up envrionment token for heroku deployment */
const TOKEN = process.env.BOT_TOKEN;
const HOST_DIR = process.env.URL;
const BOT_OWNERID = process.env.OWNER_ID;
const youtube = new YouTube(process.env.YOUTUBE_API_KEY); /* Personal Youtube-API key */
/* music variables */
var servers = {};
/* bot online */
client.on("ready", () => {
console.log("\nOne freshly baked Paimon. Now ready to serve!");
console.log("\n\nLOGGING STARTED:\n");
});
/* initial message after getting invited to a new server */
client.on("guildCreate", guild => {
/* give guild owner access to 'SuperAccess' commands */
var owner_is_guildmember = guild.owner;
/* create file if not exist , then get Object and index */
try_create_admins_JSON(guild);
var servers_Obj = get_Object_Index_Pair(guild)[0];
var filter_Obj = get_Object_Index_Pair(guild)[1];
var index = get_Object_Index_Pair(guild)[2];
/* Check if this server already has this user as admin, if not then add it */
try_add_admin(servers_Obj, filter_Obj, owner_is_guildmember, index);
});
client.on("message", async message => {
/* initialize music queue */
if (message.guild != null) {
if (!servers[message.guild.id]) {
servers[message.guild.id] = JSON.parse(readTextFile('./json_data/default_server_metadata.json'));
}
}
if (message.mentions.has(client.user)) {
message.reply("If you need help from Paimon, please try ?help");
}
/* Ignore messages that don"t start with prefix or written by bot */
if (!message.content.startsWith(PREFIX) || message.author.bot) return;
const args = message.content.slice(PREFIX.length).split(/ +/);
const command = args.shift().toLowerCase();
/* Voice only works in guilds, if the message does not come from a guild, then ignore it */
if (!message.guild) return;
/* commands & voice */
switch (command) {
case "help":
userHelp(message)
break;
case "join":
join(message);
break;
case "play":
var server = servers[message.guild.id];
/* string logic: */
var search_string = args.toString().replace(/,/g,' ');
/**
* VALIDATE ARG NOT undefined
* FOUND EDGE-CASE: search_string.startsWith('?') fix -> TypeError: Cannot read property 'substr' of null
*/
if (search_string == '' || search_string.startsWith('?')) {
return message.channel.send(`${message.author}.`
+"\nThis command plays your specified Youtube-link or keyword searched."
+"\n\nUsage: " + "?play [Link | Keywords]"
+"\n\nLink example:\n"
+"\t\tyoutube.com/watch?v=oHg5SJYRHA0"
+"\n\nKeywords example:\n"
+"\t\tPekora bgm music 1 hour").then(console.log(`${message.member.user.tag} requested for a specific bot functions.`));
}
/* IN-CHANNEL CHECK */
if (!message.member.voice.channel) {
return message.reply("please join a voice channel first!", {files: ['./moji/PaimonCookies.gif']});
}
if (server.local && server.queue.length > 0) {
return message.channel.send('Please finish local playlist first!');
}
/** Queue Logic
* 0 = no song; queue then play
* 1 = playing; queue
* 1+ = queue
*/
if (server.queue.length == 0) {
server.playToggle = true;
server.local = false;
queueLogic(message, search_string);
}
else if (server.queue.length >= 1) {
server.playToggle = false;
server.local = false;
queueLogic(message, search_string);
}
break;
case "playlocal":
var search_string = args.toString().replace(/,/g,' ');
if (search_string == '' || search_string.startsWith('?')) {
return message.channel.send(`${message.author}.`
+"\nThis command plays local_folder music, given a specified category."
+"\n\nUsage: " + "?playLocal [Category]"
+"\n\nCategory example:\n"
+"\t\tAnime | Persona | Ghibli | VN").then(console.log(`${message.member.user.tag} requested for a specific bot functions.`));
}
var server = servers[message.guild.id];
if (server.dispatcher != undefined) {
return message.channel.send('Please wait until all local music has been finished playing OR ?Stop.');
}
/* IN-CHANNEL CHECK */
if (!message.member.voice.channel) {
return message.reply("please join a voice channel first!", {files: ['./moji/PaimonCookies.gif']});
}
if (!server.local && server.queue.length > 0) {
return message.channel.send('Please finish stream playlist first!');
}
server.playToggle = true;
server.local = true;
/* https://regexr.com/ */
if (search_string.match(/anime/gi)) {
queueLogic(message, './anime_music/');
}
else if (search_string.match(/persona/gi)) {
queueLogic(message, './persona_music/');
}
else if (search_string.match(/vn|visual novel|visualnovel/gi)) {
queueLogic(message, './vn_music/');
}
else if (search_string.match(/ghibli/gi)) {
queueLogic(message, './ghibli_music/');
}
else if (search_string == undefined) {
console.log('playLocal: User did not specify category');
return message.channel.send('Please specify Category! (Anime, Persona, etc...)').then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
}
else {
console.log('playLocal: Category does not exist!');
return message.channel.send('Please specify Category! (Anime, Persona, etc...)').then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
}
break;
case "shuffle":
console.log(`[Server: ${message.guild.id}] Queue Shuffle Requested.`);
var server = servers[message.guild.id];
/* Fisher–Yates Shuffle Algorithm */
var n = server.queue.length;
var que_index = 1; /* currentSong playing is always at [0] -> [currentSong, 1, 2, 3, ..., n] */
for (var i = n-1; i > que_index; i--) {
/* random index */
let r = rand(que_index,i);
/* swap */
let temp = server.queue[i];
server.queue[i] = server.queue[r];
server.queue[r] = temp;
temp = server.cached_video_info[i];
server.cached_video_info[i] = server.cached_video_info[r];
server.cached_video_info[r] = temp;
}
if (n > 1) {
message.channel.send('Queue Shuffle Complete!');
queueInfo(message);
console.log(server.queue);
}
else {
message.channel.send('There is nothing to shuffle!');
}
break;
case "queue":
var server = servers[message.guild.id];
if (server.queue[0] != undefined) {
queueInfo(message, args[0]);
}
else {
message.channel.send('There is nothing playing.');
}
break;
case "musicinfo":
var server = servers[message.guild.id];
if (server.queue[0] != undefined) {
musicInfo_Lookup(message);
}
else {
message.channel.send('There is nothing to lookup.');
}
break;
case "vol":
vol_music(message, args[0]);
break;
case "loop":
loop_music(message, args[0]);
break;
case "pause":
console.log(`[Server: ${message.guild.id}][tag: ${message.member.user.tag}] requested to pause music.`);
pause_music(message);
break;
case "resume":
console.log(`[Server: ${message.guild.id}][tag: ${message.member.user.tag}] requested to resume music.`);
resume_music(message);
break;
case "skip":
console.log(`[Server: ${message.guild.id}][tag: ${message.member.user.tag}] requested to skip music.`);
/* IN-CHANNEL CHECK */
if (!message.member.voice.channel) {
return message.reply("please join a voice channel first!", {files: ['./moji/PaimonCookies.gif']});
}
skip_music(message, args[0]);
break;
case "stop":
console.log(`[Server: ${message.guild.id}][tag: ${message.member.user.tag}] requested to stop music.`);
var server = servers[message.guild.id];
if (server.dispatcher != undefined) {
stop_music(message);
message.channel.send('Music stopped.');
}
else {
message.channel.send('There is nothing to stop.');
}
break;
case "leave":
leave(message);
break;
case "source":
source_send(message);
break;
case "reset":
resetVoice(message);
break;
case "roll":
roll(message);
break;
case "maplestory":
guildLink(message);
break;
case "valorant":
vSens(message, args[0], args[1]);
break;
case "gcreate":
create_genshin_table(message);
break;
case "gshowtable":
showtable(message);
break;
case "gpity":
genshin_pity_calculation(message, args[0]);
break;
case "gwish":
wishCount(message, args[0], args[1], args[2]);
break;
case "greset":
wishReset(message, args[0]);
break;
case "gfile":
let genshin_file_path = './json_data/genshin_wish_tables.json';
message.channel.send({files:[genshin_file_path]});
break;
default:
/* Super Access Commands, etc... */
if (command.match(/clean|clear/g)) {
if (is_superAccess(message)) {
return clean_messages(message, args[0]);
}
} else if (command.match(/shutdown|kill/g)) {
/* only bot-owner may shutdown the bot */
if (is_Owner(message)) {
return emergency_food_time(message);
}
} else if (command.match(/caching/g)) {
if (is_superAccess(message)) {
set_cached_audio_mode(message, args[0]);
}
} else if (command.match(/dlmusic/g)) {
if (is_superAccess(message)) {
download_music(message);
}
} else if (command.match(/add/g)) {
const command2 = args.shift().toLowerCase();
if (command2 != undefined) {
if (command2.match(/superaccess|super/g)) {
if (is_superAccess(message)) {
return add_superAccess(message, args[0]);
}
}
}
else {
message.channel.send(`${message.author}. You didn't provide a VALID function argument!`);
}
} else if (command.match(/remove/gi)) {
const command2 = args.shift();
if (command2 != undefined) {
if (command2.match(/superaccess|super/)) {
if (is_superAccess(message)) {
return remove_superAccess(message, args[0]);
}
}
}
else {
message.channel.send(`${message.author}. You didn't provide a VALID function argument!`);
}
} else
message.channel.send(`${message.author}. You didn't provide a VALID function argument!`);
break;
}
});
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////// HELP DISPLAY ///////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function userHelp(message) {
console.log(`${message.member.user.tag} requested for a general list of bot functions.`);
message.author.send({embed: {
author: {
name: 'Paimon-chan\'s Embedded Info',
icon_url: client.user.avatarURL(),
url: sauce
},
title: "COMMANDS",
description: `[Currently Hosting from ${HOST_DIR}]\nMusic Support Enabled!`,
fields: [{
name: "?Help",
value: "Display a general list of commands."
},
{
name: "?Join|Leave",
value: "Paimon will join/leave your voice channel!"
},
{
name: "?Play [YouTube-Link|Keyword]",
value: "1: Play audio from the user's provided link.\n2: Perform a search on the user's provided keyword."
},
{ name: "?PlayLocal [Category]",
value: "Play host's local audio files."
},
{
name: "?Queue",
value: "Display server's current music queue."
},
{
name: "?MusicInfo",
value: "Fetch details of current song."
},
{
name: "?Pause|Resume|Skip|Stop|Shuffle|Loop",
value: "Music Control Logic."
},
{
name: "?Vol [Percent]",
value:"Set the current music volume."
},
{
name: "?Source",
value: "Paimon's delicious sauce code~"
},
{
name: "?Roll",
value: "Random Number between 1-6."
},
{
name: "?MapleStory",
value: "MapleStory guild page."
},
{
name: "?g[Create|Showtable|Pity|Wish|Reset|File]",
value: "Genshin Impact's manual \'Gacha Count-Table\'."
},
{
name: "?Valorant [GameCode] [Sensitivity]",
value: "Convert other games' sensitivity ↦ Valorant's."
}
],
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL(),
text: '© Rich Embedded Frameworks'
}
}});
message.author.send({embed: {
author: {
name: 'Paimon-chan\'s Embedded Info',
icon_url: client.user.avatarURL(),
url: sauce
},
title: "SUPER ACCESS COMMANDS",
description: `Can be used if 'SuperAccess' is granted by the owner | exisiting admin w/ 'SuperAcess'`,
fields: [
{
name: "?add Super|SuperAccess [@userTag]",
value: "Add a user as one of paimon's masters!"
},
{
name: "?remove Super|SuperAccess [@userTag]",
value: "Remove a user from one of paimon's masters!"
},
{
name: "?Shutdown|Kill",
value: "Paimon shall be served as food T^T"
},
{
name: "?Clean|Clear",
value: "Paimon will clean up your mess!"
},
{
name: "?Caching|Dlmusic",
value: "Extra Music Control Logic."
}
],
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL(),
text: '© Rich Embedded Frameworks'
}
}});
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////// MAIN FUNCTIONS /////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
async function join(message) {
const voiceChannel = await message.member.voice.channel;
if (!voiceChannel) {
return message.reply("please join a voice channel first!");
}
else {
message.member.voice.channel.join();
}
}
async function leave(message) {
let clientVoiceConnection = message.guild.voice.connection;
if (clientVoiceConnection == undefined){
message.channel.send("I'm not in a channel!", {files: ['./moji/PaimonAngry.png']});
}
/* valid compare */
else if (clientVoiceConnection.channel != undefined) {
stop_music(message);
clientVoiceConnection.disconnect();
message.channel.send("I have left the voice channel.");
}
}
async function queueLogic(message, search_string) {
var server = servers[message.guild.id];
var video = undefined;
if (server.local) {
let soundPath = search_string;
/* create directory if not exist */
if (!filestream.existsSync(soundPath)) {
filestream.mkdirSync(soundPath);
console.log(`New ${soundPath.replace(/\/|\./g,'')} folder created!`);
}
/* push files into queue -> play */
filestream.readdir(soundPath, function (err, files) {
if (err) {
console.log(err);
return;
}
for (var i = 0; i < files.length; i++) {
/* push into queue if filetype matches '.mp3' format */
if (files[i].match(/.mp3/gi))
server.queue.push(files[i]);
}
if (server.queue[0] != undefined) {
queueInfo(message);
console.log(server.queue);
play_music(message, soundPath);
}
else {
/* USE: https://regexr.com/ to help build a regex */
/* GOAL: get rid of './' or '/' */
/* RESULT: ./local_music/ -----> 'local_music' */
console.log(`${soundPath.replace(/\/|\./g,'')} folder currently has no music files!`);
return message.channel.send(`${soundPath.replace(/\/|\./g,'')} folder currently has no music files!`);
}
});
}
else {
/* queue the search_string only, only fetch metadata upon playing */
let validateURL = ytdl.validateURL(search_string);
let validate_playlist = ytpl.validateID(search_string);
if (!validate_playlist) {
/* PRELOAD */
try {
if (validateURL)
video = await youtube.getVideo(search_string);
else
video = await youtube.searchVideos(search_string);
} catch (error) {
console.log(error);
return message.channel.send('Something went wrong!\n\n' + error);
}
/* cache the video data for faster lookup */
server.queue.push(video.url);
server.cached_video_info.push({
title: video.title,
url: video.url,
duration: sec_Convert(video.durationSeconds),
data: video.data,
thumbnail: video.thumbnail
});
queueInfo(message);
console.log(server.queue);
}
else if (validate_playlist) {
/* PRELOAD PLAYLIST */
try {
message.channel.send(`Fetching only up to 50 videos, please be patient if this takes awhile...`).then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
var yt_playlist = await youtube.getPlaylist(search_string);
} catch (error) {
console.log(error);
return message.channel.send('Something went wrong!\n\n' + error);
}
/* LOAD PLAYLIST VIDEOS */
for (var i = 0; i < yt_playlist.length; i++) {
/* PRELOAD */
try {
var video = await youtube.getVideo(yt_playlist[i].url);
} catch (error) {
console.log(error);
return message.channel.send('Something went wrong!\n\n' + error);
}
/* cache the video data for faster lookup */
server.queue.push(video.url);
server.cached_video_info.push({
title: video.title,
url: video.url,
duration: sec_Convert(video.durationSeconds),
data: video.data,
thumbnail: video.thumbnail
});
}
queueInfo(message);
console.log(server.queue);
}
/*
* server.queue only seems to have updated inside this function instead of client.on(...),
* call play_music here to avoid playing [undefined] song.
*/
if (server.playToggle) {
if (server.cached_audio_mode == true) {
play_music_cached(message);
}
else {
play_music(message);
}
}
}
}
function download_music(message) {
console.log(`[Server: ${message.guild.id}][tag: ${message.member.user.tag}] requested to download cached music.`);
var server = servers[message.guild.id];
var cached_path = './stream_fetched_audio/';
if (server.cached_video_info[0] == undefined) {
return message.channel.send('There is no cache to download.');
}
if (!filestream.existsSync(cached_path)){
filestream.mkdirSync(cached_path);
}
let audio_title = server.cached_video_info[0].title.replace(/[/:*?"<>|\\]/g, '_');
if (filestream.existsSync(`${cached_path}${audio_title}.mp3`)) {
message.channel.send({files:[`${cached_path}${audio_title}.mp3`]});
}
else {
console.log('Unable to download music, current music is not cached!');
message.channel.send('Unable to download music, current music is not cached!');
}
}
async function play_music_cached(message) {
var server = servers[message.guild.id];
if (server.connection == undefined)
server.connection = await message.member.voice.channel.join();
/* PLAY MUSIC VIA CACHED_MODE */
let audio_title = server.cached_video_info[0].title.replace(/[/:*?"<>|\\]/g, '_');
var cached_path = './stream_fetched_audio/';
if (!filestream.existsSync(cached_path)){
filestream.mkdirSync(cached_path);
}
if (server.loop === 'off' || !filestream.existsSync(`${cached_path}${audio_title}.mp3`)) {
var audio_WritableStream = filestream.createWriteStream(`${cached_path}${audio_title}.mp3`)
var audio_ReadableStream = ytdl(server.queue[0], { filter: 'audioonly' });
console.log(`Caching audio file to '${cached_path}'`);
var stream = audio_ReadableStream.pipe(audio_WritableStream);
}
stream.on('finish', function () {
musicInfo_Lookup(message);
server.dispatcher = server.connection.play(`${cached_path}${audio_title}.mp3`, {volume: server.volume});
console.log(`[Stream-Mode][Server: ${message.guild.id}] Now Playing: ${audio_title}\nDuration: ${server.cached_video_info[0].duration}\n`);
/* cached_audio dispatcher */
server.dispatcher.on('finish', function () {
music_loop_logic(message, cached_path, '', audio_title);
});
});
}
async function play_music(message, soundPath = '') {
var server = servers[message.guild.id];
if (server.connection == undefined)
server.connection = await message.member.voice.channel.join();
var cached_path = './stream_fetched_audio/';
var audio_title = '';
if (server.local) {
/* PLAY MUSIC LOCAL */
if (server.queue[0] != undefined) {
let song = soundPath + server.queue[0];
let songName = server.queue[0].split('.mp3')[0];
server.dispatcher = server.connection.play(song, {volume: server.volume});
console.log('[Local-Mode][Server: '+message.guild.id+'] Now Playing: ' + songName);
}
}
else {
/* PLAY MUSIC VIA STREAM_MODE */
audio_title = server.cached_video_info[0].title.replace(/[/:*?"<>|\\]/g, '_');
var stream = ytdl(server.queue[0], { filter: 'audioonly' });
musicInfo_Lookup(message);
server.dispatcher = server.connection.play(stream, {volume: server.volume});
console.log(`[Stream-Mode][Server: ${message.guild.id}] Now Playing: ${server.cached_video_info[0].title}\nDuration: ${server.cached_video_info[0].duration}\n`);
}
/* stream dispatcher */
server.dispatcher.on('finish', function () {
music_loop_logic(message, cached_path, soundPath, audio_title);
});
}
function musicInfo_Lookup(message) {
var server = servers[message.guild.id];
if (!server.local) {
var cached = server.cached_video_info;
message.channel.send({embed: {
author: {
name: 'Paimon-chan\'s Embedded Info',
icon_url: client.user.avatarURL(),
url: sauce
},
title: cached[0].title,
url: cached[0].url,
thumbnail: cached[0].thumbnail,
fields:
[{
name: "Duration",
value: cached[0].duration
}],
timestamp: new Date(),
footer:{
icon_url: client.user.avatarURL(),
text: '© Rich Embedded Frameworks'
}
}}).then(newMessage => newMessage.delete({timeout: 10000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
}
else
return message.channel.send('Local Music does not support Info-Lookup');
}
async function queueInfo(message, qNum = 10) {
var server = servers[message.guild.id];
var cached = server.cached_video_info;
var queueString = '';
var playString = 'None';
/* delete old embedMessage */
if (server.embedMessage != undefined)
server.embedMessage.delete().catch((error) => {console.log(`${error}: 'Tried to delete embedMessage, but it was already deleted!`)});
/* playString */
if (server.queue[0] != undefined) {
if (ytdl.validateURL(server.queue[0])) /* check link validity */
playString = cached[0].title;
else
playString = server.queue[0].split('.mp3')[0];
}
/* queueString */
for (var i = 1; i < server.queue.length; i++) {
if (qNum <= 15) {
if (i <= qNum) {
/* check link validity */
if (ytdl.validateURL(server.queue[i]))
queueString += i+'.) '+cached[i].title+'\n'; /* Ex: 1. [songName]... */
else
queueString += i+'.) '+server.queue[i].split('.mp3')[0]+'\n'; /* Ex: 1. [songName]... */
}
else break;
}
else {
return message.channel.send('Max queue display is 15 songs!');
}
}
/* send new embed */
message.channel.send({embed: {
author: {
name: 'Paimon-chan\'s Embedded Info',
icon_url: client.user.avatarURL(),
url: sauce
},
description: `[Server: ${message.guild.name}]\n\tvolume: ${(server.volume*100)}%`,
thumbnail: ((server.local) ? undefined : cached[0].thumbnail),
fields: [{
name: "Now Playing:",
value: playString
},
{
name: "In the Queue:",
value: ((server.queue.length >= 2) ? queueString : 'None')
}
],
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL(),
text: '© Rich Embedded Frameworks'
}
}}).then(newMessage => server.embedMessage = newMessage);
}
function vol_music(message, num) {
var server = servers[message.guild.id];
if (num == undefined) {
console.log(`[Server: ${message.guild.id}] Current volume: ${server.volume*100}%`);
return message.channel.send(`Current volume: ${server.volume*100}%`).then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
}
var percentage = parseFloat(num);
if (isNaN(percentage)) {
console.log(`[Server: ${message.guild.id}][tag: ${message.member.user.tag}] requested for volume change, but reached INVALID number.`);
return message.channel.send(`${message.author}. You need to supply a VALID number!`);
}
if (server.dispatcher != undefined) {
/* Sets the volume relative to the input stream - i.e. 1 is normal, 0.5 is half, 2 is double. */
server.volume = percentage / 100;
if (server.volume <= 1) {
server.dispatcher.setVolume(server.volume);
console.log(`[Server: ${message.guild.id}] Volume set to ${percentage}%`);
message.channel.send(`Volume set to ${percentage}%`).then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
}
else {
console.log(`[Server: ${message.guild.id}] Cannot set volume greater than 100%`);
message.channel.send(`Cannot set volume greater than 100%`).then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
}
}
else {
message.channel.send('Music is not playing.').then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'})).catch( (error) => {console.log(`${error}`)});
}
}
function loop_music(message, mode_string) {
var server = servers[message.guild.id];
var switcher = 'off';
if (mode_string == undefined) {
if (server.loop === switcher) {
return message.channel.send('Loop Mode Status: OFF').then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
}
else {
return message.channel.send(`Loop Mode Status: ${server.loop.toUpperCase()}`).then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
}
}
/* this line below will check for conflicting mode */
else if ( mode_string.match(/single/gi) && mode_string.match(/list/gi) ) {
return message.channel.send('Please only specify one mode...').then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
}
/* this line below will check for either-or */
else if ( mode_string.match(/single/gi) || mode_string.match(/list/gi) ) {
switcher = 'on';
}
/* finally execute the flip-switch */
switch (switcher) {
case 'on':
server.loop = mode_string.toLowerCase();
console.log(`[Server: ${message.guild.id}] Loop Mode is turned ON: ${server.loop.toUpperCase()}`);
message.channel.send(`Loop Mode is turned ON: ${server.loop.toUpperCase()}`);
break;
case 'off':
server.loop = switcher;
console.log(`[Server: ${message.guild.id}] Loop Mode is turned OFF`);
message.channel.send('Loop Mode is turned OFF');
break;
default:
message.channel.send('Usage: ?loop [SINGLE | LIST | OFF]');
break;
}
}
function set_cached_audio_mode (message, switcher) {
var server = servers[message.guild.id];
if (switcher == undefined) {
if (server.cached_audio_mode) {
return message.channel.send('Audio Caching: ON').then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
}
else {
return message.channel.send('Audio Caching: OFF').then(newMessage => newMessage.delete({timeout: 5000, reason: 'fewer text clutter.'}).catch( (error) => {console.log(`${error}`)} ));
}
}
switcher = switcher.toLowerCase();
switch (switcher) {
case 'on':
server.cached_audio_mode = true;
console.log(`[Server: ${message.guild.id}] Audio Caching is turned ON`);
message.channel.send('Audio Caching is turned ON');
break;
case 'off':
server.cached_audio_mode = false;
console.log(`[Server: ${message.guild.id}] Audio Caching is turned OFF`);
message.channel.send('Audio Caching is turned OFF');
break;
default:
message.channel.send('Usage: ?caching ON|OFF');
break;
}
}
function pause_music(message) {
let server = servers[message.guild.id];
if (server.dispatcher != undefined) {
server.dispatcher.pause(true);
message.channel.send('Music paused.');
}
else {
message.channel.send('There is nothing to pause.');
}
}
function resume_music(message) {
let server = servers[message.guild.id];
if (server.dispatcher != undefined) {
server.dispatcher.resume();
message.channel.send('Music resume.');
}
else {
message.channel.send('There is nothing to resume.');
}
}
function skip_music(message, sNum) {
let server = servers[message.guild.id];
server.skip = true;
if (sNum == undefined) {
sNum = 1;
}
server.skipAmount = sNum;
if (server.dispatcher != undefined) {
server.dispatcher.end();
}
else {
message.channel.send('There is nothing to skip.');
}
}
function stop_music(message) {
let server = servers[message.guild.id];
if (server.dispatcher != undefined) {
/* clear queue */
while (server.queue.length > 0) {
server.queue.shift();
server.cached_video_info.shift();
}
server.dispatcher.end();
}
/* base case: do nothing */
}
function resetVoice(message) {
console.log(`[Server: ${message.guild.id}][tag: ${message.member.user.tag}] requested to reset server metadata!`);
var server = servers[message.guild.id];
var cached_path = './stream_fetched_audio/';
if (server.cached_video_info[0] != undefined) {
let audio_title = server.cached_video_info[0].title.replace(/[/:*?"<>|\\]/g, '_');
if (filestream.existsSync(`${cached_path}${audio_title}.mp3`)) {
filestream.unlinkSync(`${cached_path}${audio_title}.mp3`, function (err) {
if (err) return console.log(err);
console.log('cached audio deleted successfully');
});
}
}
/* destroy & reset */
if (server.dispatcher != undefined) {
server.dispatcher.destroy();
}
while (server.queue.length > 0){
server.queue.shift();
server.cached_video_info.shift();
}
server = JSON.parse(readTextFile('./json_data/default_server_metadata.json'));
console.log(server);
message.channel.send('Bot Reset Complete!');
}
function source_send(message) {
message.channel.send(`Paimon's delicious source code: ${sauce}`);
console.log(`${message.member.user.tag} requested Paimon as food!`);
}
async function clean_messages(message, numline) {
/* Checks if the `amount` parameter is a number. If not, the command throws an error */
if (numline == undefined) {
/* continue */
}
else if (isNaN(numline))
return message.reply('The amount parameter isn`t a number!');
/* Checks if the `numline` integer is bigger than 100 */
else if (numline > 99)
return message.reply('Maximum of clearing **99 messages** at once!');
/* Checks if the `numline` integer is smaller than 1 */
else if (numline < 1)
return message.reply('You must delete **at least 1 message!**');
/* Fetching the execution command and sweep that first, catch any errors.
* Fetch the given number of messages to sweeps: numline+1 to include the execution command
* Sweep all messages that have been fetched and are not older than 14 days (due to the Discord API), catch any errors.
*/
var bulkMessages = ((numline == undefined) ? await message.channel.messages.fetch() : await message.channel.messages.fetch( {limit: ++numline} ));
message.channel.bulkDelete(bulkMessages, true).then(console.log('message cleaning requested!'));
console.log(`Cleaned ${bulkMessages.array().length-1} messages.`);
}
function vSens(message, gameCode, sens) {
if (gameCode == undefined || sens == undefined) {
console.log(`\n gameCode = ${gameCode}, sensitivity = ${sens}\n\n`);
return message.channel.send(`${message.author}.`
+"\nThis command converts your CSGO sensitivity to Valorant."
+"\n\nUsage: " + "Valorant [GameCode] [Sensitivity]"
+"\n\nGameCode:\n"
+"\t\t[A]: APEX LEGEND\n"
+"\t\t[B]: RAINBOW SIX\n"
+"\t\t[C]: CSGO\n"
+"\t\t[O]: OVERWATCH"
+"\n\nSensitivity:\n"
+"\t\t[A Decimal Number]").then(console.log(`${message.member.user.tag} requested for a specific bot functions.`));
}
gameCode = gameCode.toLowerCase();
var sensitivity = parseFloat(sens);
/* is Not a Number */
if (isNaN(sensitivity))
return message.channel.send(`${message.author}. You need to supply a VALID sensitivity!`)
.then(console.log(`${message.member.user.tag} requested for VALORANT sensitivity conversion, but reached INVALID sensitivity.`));
else {
var convertedSens = 0;
var gameName = undefined;
switch (gameCode) {
case "a":
convertedSens = (sensitivity / 3.18181818);
gameName = "APEX LEGEND";
break;
case "b":
convertedSens = (sensitivity * 1.2);
gameName = "RAINBOW SIX";
break;
case "c":
convertedSens = (sensitivity / 3.18181818);
gameName = "CSGO";
break;
case "o":
convertedSens = (sensitivity / 10.6);
gameName = "OVERWATCH";
break;
default:
return message.channel.send(`${message.author}. Unsupported GameCode, cannot determine your sensitivity.`)
.then(console.log(`${message.member.user.tag} requested for VALORANT sensitivity conversion, but reached INVALID GameCode.`));
}
console.log(`\n${message.member.user.tag} requested for VALORANT sensitivity conversion.`);
console.log(`\n Converted ${message.member.user.tag}'s game sensitivity.`);
console.log(` [${gameName} ↦ VALORANT] : [${sensitivity} ↦ ${convertedSens.toFixed(5)}]\n`);
message.channel.send(`Converting your sensitivity: [ ${gameName} ↦ VALORANT ]`)
message.channel.send(`${message.author}. Your VALORANT game sensitivity = ${convertedSens.toFixed(5)}`);
}
}
function create_genshin_table(message) {
var path = './json_data/genshin_wish_tables.json';
var text = readTextFile(path);
var array_Obj = JSON.parse(text);
var new_userdata = {
uid: message.author.id,
username: message.member.user.tag,
bannerTypes: { event:0, weapon:0, standard:0 }
};
if (objLength(array_Obj.users) == 0) {
array_Obj.users.push(new_userdata);
}
if (objLength(array_Obj.users) > 0) {
/* this is inefficient if the # of users gets too large, would be nice to convert it into a database to filter duplicates. */
for (var i = 0; i < objLength(array_Obj.users); i++) {
/* this user table already exist. */
if (array_Obj.users[i].uid === message.author.id) {
/* check if this user has recently changed his/her userTag. */