forked from AlphaKretin/bastion-bot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbastion.js
3314 lines (3232 loc) · 95.9 KB
/
bastion.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
let fs = require('fs');
let config = JSON.parse(fs.readFileSync('config/config.json', 'utf8'));
//load data from JSON. Expected values can be inuited from console feedback or seen in the readme.
if (!config.token) {
console.log("No Discord user token found at config.token! Exiting..."); //need the token to work as a bot, rest can be left out or defaulted.
exit();
}
let imagesEnabled = false;
let imageUrlMaster;
let imageUrlAnime;
let imageUrlCustom;
//these defaults are overwritten by what's in the config, if possible
let imageSize = 100;
let triviaTimeLimit = 30000;
let triviaHintTime = 10000;
let triviaMaxRounds = 20;
let triviaLocks = {};
let imageExt = "png";
let markdownno = 0;
let embCT;
if (config.imageUrl) {
imageUrlMaster = config.imageUrl;
imagesEnabled = true;
//a bunch of stuff relies on images, and other config fields related to them only need to be checked if images exist
if (config.imageUrlAnime) {
imageUrlAnime = config.imageUrlAnime;
} else {
imageUrlAnime = imageUrlMaster;
console.log("URL for anime image source not found at config.imageUrlAnime! Defaulting to same source as official cards, " + imageUrlMaster + "!");
}
if (config.imageUrlCustom) {
imageUrlCustom = config.imageUrlCustom;
} else {
imageUrlCustom = imageUrlMaster;
console.log("URL for custom image source not found at config.imageUrlCustom! Defaulting to same source as official cards, " + imageUrlMaster + "!");
}
if (config.imageSize) {
imageSize = config.imageSize;
} else {
console.log("Size for images not found at config.imageSize! Defaulting to " + imageSize + "!");
}
if (config.triviaTimeLimit) {
triviaTimeLimit = config.triviaTimeLimit;
} else {
console.log("No time limit for trivia found at config.triviaTimeLimit! Defaulting to " + triviaTimeLimit + "!");
}
if (config.triviaHintTime) {
triviaHintTime = config.triviaHintTime;
} else {
console.log("No hint time for trivia found at config.triviaHintTime! Defaulting to " + triviaHintTime + "!");
}
if (config.triviaMaxRounds) {
triviaMaxRounds = config.triviaMaxRounds;
} else {
console.log("No hint time for trivia found at config.triviaMaxRounds! Defaulting to " + triviaMaxRounds + "!");
}
if (config.triviaLocks) {
triviaLocks = config.triviaLocks;
} else {
console.log("No specifications for channels to lock trivia to found at config.triviaLocks! Defaulting to nothing, configure with \".tlock\" command!");
}
if (config.imageExt) {
imageExt = config.imageExt;
} else {
console.log("No file extension for images found at config.imageExt! Defaulting to " + imageExt + "!");
}
} else {
console.log("URL for image source not found at config.imageUrl! Image lookup and trivia will be disabled.");
}
let emoteMode = 0;
let emoteDB;
let thumbsup = "👍";
let thumbsdown;
if (config.emoteMode && config.emoteMode > 0 && config.emotesDB) {
emoteMode = config.emoteMode;
let path = "config/" + config.emotesDB;
emoteDB = JSON.parse(fs.readFileSync(path, "utf-8"));
thumbsup = emoteDB["thumbsup"];
if (emoteDB["thumbsdown"]) {
thumbsdown = emoteDB["thumbsdown"];
}
} else if (config.emoteMode && config.emoteMode > 0) {
console.log("Emote database not found at config.emotesDB! Emotes display will be disabled.");
} else if (config.emoteMode === undefined || config.emoteMode === null) {
console.log("Emote mode specification not found at config.emoteMode! Defaulting to " + emoteMode + "!");
}
let messageMode = 0;
let embedColor = 0x1;
let embcDB;
if (config.messageMode) {
messageMode = config.messageMode;
} else {
console.log("Message mode specification not found at config.messageMode! Defaulting to " + messageMode + "!");
}
if (messageMode & 0x2 && config.embedColor) {
embedColor = config.embedColor;
} else if (messageMode & 0x2) {
console.log("Embed color specification not found at config.embedColor! Defaulting to " + embedColor + "!");
}
if (config.embedColorDB) {
let path = "config/" + config.embedColorDB;
embcDB = JSON.parse(fs.readFileSync(path, "utf-8"));
} else {
console.log("Embed color database not found at config.embedColorDB! Card Type specific embed color will be set to default.");
}
let quo = messageMode & 0x1 && "`" || "";
let bo = messageMode & 0x1 && "**" || "";
let jvex = messageMode & 0x1 && "java\n" || "";
let scriptsEnabled = false;
let scriptUrlMaster;
let scriptUrlAnime;
let scriptUrlCustom;
let scriptBackupEnabled = false;
let scriptUrlBackup;
if (config.scriptUrl) {
scriptUrlMaster = config.scriptUrl;
scriptsEnabled = true;
if (config.scriptUrlAnime) {
scriptUrlAnime = config.scriptUrlAnime;
} else {
scriptUrlAnime = scriptUrlMaster;
console.log("URL for anime script source not found at config.scriptUrlAnime! Defaulting to same source as official cards, " + scriptUrlMaster + "!");
}
if (config.scriptUrlCustom) {
scriptUrlCustom = config.scriptUrlCustom;
} else {
scriptUrlCustom = scriptUrlMaster;
console.log("URL for custom script source not found at config.scriptUrlCustom! Defaulting to same source as official cards, " + scriptUrlMaster + "!");
}
if (config.scriptUrlBackup) {
scriptUrlBackup = config.scriptUrlBackup;
scriptBackupEnabled = true;
} else {
console.log("URL for backup script source not found at config.scriptUrlBackup! Bastion will not try to find an alternative to missing scripts!");
}
} else {
console.log("URL for script source not found at config.scriptUrl! Script lookup will be disabled.");
}
let pre = ".";
if (config.prefix) {
pre = config.prefix;
} else {
console.log("No prefix found at config.prefix! Defaulting to \"" + pre + "\"!");
}
let longStr = "...\n__Type `" + pre + "long` to be PMed the rest!__";
if (config.longStr) {
longStr = config.longStr;
} else {
console.log("No long message string found at config.longStr! Defaulting to \"" + longStr + "\"!");
}
let helpMessage = "I am a Yu-Gi-Oh! card bot made by AlphaKretin#7990.\nPrice data is from the <https://yugiohprices.com> API.\nYou can find my help file and source here: <https://github.com/AlphaKretin/bastion-bot/>\nYou can support my development on Patreon here: <https://www.patreon.com/alphakretinbots>\nType `" + pre + "commands` to be DMed a short summary of my commands without going to an external website.";
if (config.helpMessage) {
helpMessage = config.helpMessage;
} else {
console.log("Help message not found at console.helpMessage! Defaulting to \"" + helpMessage + "\"!");
}
if (messageMode & 0x1) {
helpMessage = bo + quo + helpMessage + quo + bo;
}
let maxSearches = 3;
if (config.maxSearches) {
maxSearches = config.maxSearches;
} else {
console.log("No upper limit on searches in one message found at config.maxSearches! Defaulting to " + maxSearches + "!");
}
let dbs = {
"en": ["cards.cdb"]
};
if (config.dbs) {
dbs = config.dbs;
} else {
console.log("List of card databases not found at config.dbs! Defaulting to one database named " + dbs.en[0] + ".");
}
let dbMemory = 33554432;
if (config.dbMemory) {
dbMemory = config.dbMemory;
} else {
console.log("Size of memory allocated for card databases not found at config.dbMemory! Defaulting to " + dbMemory + ".");
}
let owner;
let servLogEnabled = false;
if (config.botOwner) {
servLogEnabled = true;
owner = config.botOwner;
} else {
console.log("Bot owner's ID not found at config.botOwner! Owner commands will be disabled.");
}
let libFuncEnabled = false;
let libFunctions;
let libConstEnabled = false;
let libConstants;
let libParamsEnabled = false;
let libParams;
if (config.scriptFunctions) {
let path = "dbs/" + config.scriptFunctions;
libFunctions = JSON.parse(fs.readFileSync(path, "utf-8"));
libFuncEnabled = true;
} else {
console.log("Path to function library not found at config.scriptFunctions! Function library will be disabled!");
}
if (config.scriptConstants) {
let path = "dbs/" + config.scriptConstants;
libConstants = JSON.parse(fs.readFileSync(path, "utf-8"));
libConstEnabled = true;
} else {
console.log("Path to constant library not found at config.scriptFunctions! Constant library will be disabled!");
}
if (config.scriptParams) {
let path = "dbs/" + config.scriptParams;
libParams = JSON.parse(fs.readFileSync(path, "utf-8"));
libParamsEnabled = true;
} else {
console.log("Path to parameter library not found at config.scriptFunctions! Parameter library will be disabled!");
}
let skillsEnabled = false;
let skills = [];
let skillNames = [];
if (config.skillDB) {
let path = "dbs/" + config.skillDB;
skills = JSON.parse(fs.readFileSync(path, "utf-8"));
skillsEnabled = true;
for (let skill of skills) { //populate array of objects containing names for the sake of fuzzy search
skillNames.push({
name: skill.name,
});
}
} else {
console.log("Path to Duel Links Skill database not found at config.skillDB! Skill lookup will be disabled.");
}
//more config files, all explained in the readme
let shortcuts = JSON.parse(fs.readFileSync('config/shortcuts.json', 'utf8'));
let setcodes = JSON.parse(fs.readFileSync('config/setcodes.json', 'utf8'));
let lflist = JSON.parse(fs.readFileSync('config/lflist.json', 'utf8'));
//discord setup
let Discord = require('discord.io');
let bot = new Discord.Client({
token: config.token,
autorun: true
});
bot.on('ready', function() {
console.log('Logged in as %s - %s\n', bot.username, bot.id);
});
bot.on('disconnect', function() { //Discord API occasionally disconnects bots for an unknown reason.
console.log("Disconnected. Reconnecting...");
bot.connect();
});
//sql setup
Module = {
TOTAL_MEMORY: dbMemory
};
let SQL = require('sql.js');
let contents = {};
let names = {};
let ids = {};
let aliases = {};
let nameList = {};
let langs = [];
for (let lang in dbs) { //this reads the keys of an object loaded above, which are supposed to be the languages of the card databases in that field of the object
console.log("loading " + lang + " database");
langs.push(lang);
let filebuffer = fs.readFileSync("dbs/" + dbs[lang][0]);
let db = new SQL.Database(filebuffer);
ids[lang] = [];
aliases[lang] = [];
nameList[lang] = [];
contents[lang] = db.exec("SELECT * FROM datas"); //see SQL.js documentation/example for the format of this return, it's not the most intuitive
names[lang] = db.exec("SELECT * FROM texts");
for (let card of contents[lang][0].values) { //temporary ID list for the sake of overwrites
ids[lang].push(card[0]);
}
if (dbs[lang].length > 1) { //a language can have multiple DBs, and if so their data needs to be loaded into the results from the first as if they were all one DB.
for (let i = 1; i < dbs[lang].length; i++) {
let newbuffer = fs.readFileSync("dbs/" + dbs[lang][i]);
let newDB = new SQL.Database(newbuffer);
let newContents = newDB.exec("SELECT * FROM datas");
let newNames = newDB.exec("SELECT * FROM texts");
for (let card of newContents[0].values) {
let ind = ids[lang].indexOf(card[0]);
if (ind > -1) { //if the ID is the same (NOT to be confused with aliases, where alt arts etc. reference another ID), it's a fix entry and should overwrite the original.
contents[lang][0].values[ind] = card;
} else {
contents[lang][0].values.push(card);
ids[lang].push(card[0]);
}
}
for (let card of newNames[0].values) {
let ind = ids[lang].indexOf(card[0]);
if (ind > -1) {
names[lang][0].values[ind] = card;
} else {
names[lang][0].values.push(card);
}
}
}
}
ids[lang] = []; //reset array to repopulate after overwrites and additions
for (let card of contents[lang][0].values) { //populate ID list for easy checking of card validity
ids[lang].push(card[0]);
aliases[lang].push(card[2]);
}
for (let card of names[lang][0].values) { //populate array of objects containing names for the sake of fuzzy search
nameList[lang].push({
name: card[1],
id: card[0]
});
}
}
//fuse setup
let Fuse = require('fuse.js');
let options = {
shouldSort: true,
includeScore: true,
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 64,
minMatchCharLength: 1,
keys: [
"name"
]
};
let fuse = {};
for (let lang of langs) {
fuse[lang] = new Fuse(nameList[lang], options);
}
let skillFuse = {};
if (skillsEnabled) {
skillFuse = new Fuse(skillNames, options);
}
let request = require('request');
let https = require('https');
let url = require('url');
let jimp = require('jimp');
let filetype = require('file-type');
//these are used for various data that needs to persist between commands or uses of a command
let longMsg = "";
let gameData = {};
let searchPage = {
active: false
};
//command declaration
bot.on('message', function(user, userID, channelID, message, event) {
if (userID === bot.id) { //ignores own messages to prevent loops
return;
}
let lowMessage = message.toLowerCase();
if (lowMessage.indexOf(pre + "randcard") === 0) {
randomCard(user, userID, channelID, message, event);
return;
}
if (scriptsEnabled && lowMessage.indexOf(pre + "script") === 0) {
script(user, userID, channelID, message, event);
return;
}
if (imagesEnabled && lowMessage.indexOf(pre + "trivia") === 0) {
trivia(user, userID, channelID, message, event);
return;
}
if (imagesEnabled && lowMessage.indexOf(pre + "tlock") === 0 && checkForPermissions(userID, channelID, [8192])) { //user must have Manage Message permission to use this command
tlock(user, userID, channelID, message, event);
return;
}
if (lowMessage.indexOf(pre + "matches") === 0) {
matches(user, userID, channelID, message, event);
return;
}
if (lowMessage.indexOf(pre + "set") === 0) {
set(user, userID, channelID, message, event);
return;
}
if (lowMessage.indexOf(pre + "id") === 0) {
getSingleProp("id", user, userID, channelID, message, event);
return;
}
if (lowMessage.indexOf(pre + "notext") === 0) {
getSingleProp("notext", user, userID, channelID, message, event);
return;
}
if (lowMessage.indexOf(pre + "effect") === 0) {
getSingleProp("effect", user, userID, channelID, message, event);
return;
}
if (lowMessage.indexOf(pre + "strings") === 0) {
strings(user, userID, channelID, message, event);
return;
}
if (lowMessage.startsWith(pre + "deck")) {
deck(user, userID, channelID, message, event);
return;
}
if (lowMessage.indexOf(pre + "commands") === 0) {
commands(user, userID, channelID, message, event);
return;
}
if (libFuncEnabled && (lowMessage.indexOf(pre + "f") === 0 || lowMessage.indexOf(pre + "function") === 0)) {
searchFunctions(user, userID, channelID, message, event);
return;
}
if (libConstEnabled && (lowMessage.indexOf(pre + "c") === 0 || lowMessage.indexOf(pre + "constant") === 0)) {
searchConstants(user, userID, channelID, message, event);
return;
}
if (libParamsEnabled && lowMessage.indexOf(pre + "param") === 0) {
searchParams(user, userID, channelID, message, event);
return;
}
if (searchPage.active && lowMessage.indexOf(pre + "p") === 0 && lowMessage.indexOf("param") === -1) {
libPage(user, userID, channelID, message, event);
return;
}
if (searchPage.active && lowMessage.indexOf(pre + "d") === 0) {
libDesc(user, userID, channelID, message, event);
return;
}
if (skillsEnabled && lowMessage.indexOf(pre + "skill") === 0) {
searchSkill(user, userID, channelID, message, event);
return;
}
if (servLogEnabled && userID === owner && lowMessage.indexOf(pre + "servers") === 0) {
servers(user, userID, channelID, message, event);
return;
}
if (message.indexOf("<@" + bot.id + ">") > -1 || lowMessage.indexOf(pre + "help") === 0) {
//send help message
if (messageMode & 0x2) {
bot.sendMessage({
to: channelID,
embed: {
color: embedColor,
description: helpMessage,
}
});
} else {
bot.sendMessage({
to: channelID,
message: helpMessage
});
}
}
if (longMsg.length > 0 && lowMessage.indexOf(pre + "long") === 0) {
if (messageMode & 0x2) {
bot.sendMessage({
to: userID,
embed: {
color: embedColor,
description: bo + quo + quo + quo + longMsg,
}
});
} else {
bot.sendMessage({
to: userID,
message: bo + quo + quo + quo + longMsg
});
}
return;
}
if (channelID in gameData) {
switch (gameData[channelID].game) { //switch statement where if would do to futureproof for adding more games
case "trivia":
answerTrivia(user, userID, channelID, message, event);
break;
default:
break;
}
return;
}
let blockRe = /`{1,3}[\s\S\r\n]*?[\s\S\r\n][\s\S\r\n]*?`{1,3}/g; //gets all text between ``, to remove them, so they're not searched
message = message.replace(blockRe, "");
let re = /{(.*?)}/g; //gets text between {}
let results = [];
let regx;
do {
regx = re.exec(message);
if (regx !== null) {
if (regx[1].length > 0 && regx[1].indexOf(":") !== 0 && regx[1].indexOf("@") !== 0 && regx[1].indexOf("#") !== 0 && regx[1].indexOf("http") === -1) { //ignores <@mentions>, <#channels>, <http://escaped.links> and <:customEmoji:126243>. All these only apply for <>, but doesn't hurt to use the same check here
results.push(regx[1]);
}
}
} while (regx !== null);
let results2 = [];
if (imagesEnabled) {
let re2 = /<(.*?)>/g; //gets text between <>
let regx2;
do {
regx2 = re2.exec(message);
if (regx2 !== null) {
if (regx2[1].length > 0 && regx2[1].indexOf(":") !== 0 && regx2[1].indexOf("@") !== 0 && regx2[1].indexOf("#") !== 0 && regx2[1].indexOf("http") === -1) { //ignores <@mentions>, <#channels>, <http://escaped.links> and <:customEmoji:126243>
results2.push(regx2[1]);
}
}
} while (regx2 !== null);
}
if (results.length + results2.length > maxSearches) {
if (messageMode & 0x2) {
bot.sendMessage({
to: channelID,
embed: {
color: embedColor,
description: "You can only search up to " + maxSearches + " cards!",
}
});
} else {
bot.sendMessage({
to: channelID,
message: "You can only search up to " + maxSearches + " cards!"
});
}
} else {
//second parameter here is whether to display image or not
if (results.length > 0) {
for (let result of results) {
searchCard(result, false, user, userID, channelID, message, event);
}
}
if (results2.length > 0) {
for (let result of results2) {
searchCard(result, true, user, userID, channelID, message, event);
}
}
}
});
bot.on('messageUpdate', function(oldMsg, newMsg, event) { //a few commands can be met by edit
if (newMsg.author && newMsg.author.id === bot.id) { //have to check a lot of variables exist at all because for some stupid reason an embed being added also counts as editing a message. Dammit Discord
return;
}
let lowMessage = newMsg.content && newMsg.content.toLowerCase();
if (searchPage.active && lowMessage && lowMessage.indexOf(pre + "p") === 0 && lowMessage.indexOf("param") === -1) {
libPage(newMsg.author.username, newMsg.author.id, newMsg.channelID, newMsg.content, event);
}
if (searchPage.active && lowMessage && lowMessage.indexOf(pre + "d") === 0) {
libDesc(newMsg.author.username, newMsg.author.id, newMsg.channelID, newMsg.content, event);
}
});
function commands(user, userID, channelID, message, event) {
//obviously these don't all need to be seperate lines and I don't even need to define anything here but I like having each command on a new line of code.
let out = "Type a card name or ID between `{}` (or `<>` for images) to see its profile.\n";
out += "`" + pre + "randcard` displays a random card profile.\n";
out += "`" + pre + "script` displays the YGOPro script of the specified card.\n";
out += "`" + pre + "matches` displays the 10 card names Bastion thinks are most similar to the text you type after.\n";
out += "`" + pre + "skill` searches for a skill from Duel Links.\n";
out += "`" + pre + "set` translates between YGOPro setcodes and their name.\n";
out += "`" + pre + "f`, `" + pre + "c` and `" + pre + "p` search for the functions, constants and parameters respectively used for scripting in YGOPro.\n";
out += "`" + pre + "trivia` plays a game where you guess a card name from its image.\n";
out += "See the readme for details and other commands I skimmed over: <https://github.com/AlphaKretin/bastion-bot/>";
if (messageMode & 0x2) {
bot.sendMessage({
to: userID,
embed: {
color: embedColor,
description: out,
}
});
} else {
bot.sendMessage({
to: userID,
message: out
});
}
}
async function randomCard(user, userID, channelID, message, event) { //anything that gets card data has to be async because getting the price involves a Promise
try {
let args = message.toLowerCase().split(" ");
let code;
let i = 0;
let outLang = "en";
for (let arg of args) {
if (langs.indexOf(arg) > -1) {
outLang = arg;
}
}
if (args.length > 1) {
let matches = [];
for (let id of ids[outLang]) { //gets a list of all cards that meet specified critera, before getting a random one of those cards
if (randFilterCheck(id, args, outLang)) { //a number of filters can be specified in the command, and this checks that a card meets them
matches.push(id);
}
}
if (matches.length === 0) {
return;
}
code = matches[Math.floor(Math.random() * matches.length)];
} else {
code = ids[outLang][Math.floor(Math.random() * ids[outLang].length)];
}
let out = await getCardInfo(code, outLang, user, userID, channelID, message, event); //returns a list of IDs for the purposes of cards with multiple images, as well as of course the card's profile
if (imagesEnabled && args.indexOf("image") > -1) {
if (out[1].length == 1 && messageMode & 0x2) {
sendLongMessage(out[0], user, userID, channelID, message, event, embCT, out[1][0]);
} else {
postImage(out[1], out[0], outLang, user, userID, channelID, message, event); //postImage also handles sending the message
}
} else {
sendLongMessage(out[0], user, userID, channelID, message, event, embCT); //in case a message is over 2k characters (thanks Ra anime), this splits it up
}
} catch (e) {
console.log(e);
}
}
//from hereon out, some functions and logic will be re-used from randomCard() - I won't repeat myself, just check that.
async function script(user, userID, channelID, message, event) {
let input = message.slice((pre + "script ").length);
let inInt = parseInt(input);
let index = ids.en.indexOf(inInt);
if (index > -1) {
try {
let out = await getCardScript(index, user, userID, channelID, message, event);
sendLongMessage(out, user, userID, channelID, message, event);
} catch (e) {
console.log("Error with search by ID:");
console.log(e);
}
} else { //if index doesn't exist it's probably because it was a name and not an ID
try {
let index = nameCheck(input, "en"); //this handles all the fuzzy search stuff
if (index > -1 && index in ids.en) { //other functions have variable language, this currently defaults to english. I'll probably change this later
let out = await getCardScript(index, user, userID, channelID, message, event);
sendLongMessage(out, user, userID, channelID, message, event);
} else {
console.log("Invalid card ID or name, please try again.");
return;
}
} catch (e) {
console.log("Error with search by name:");
console.log(e);
}
}
}
async function searchCard(input, hasImage, user, userID, channelID, message, event) {
let args = input.split(",");
let inLang = args[args.length - 2] && args[args.length - 2].replace(/ /g, "").toLowerCase(); //expecting cardname,lang,lang
let outLang = args[args.length - 1] && args[args.length - 1].replace(/ /g, "").toLowerCase();
if (langs.indexOf(inLang) > -1 && langs.indexOf(inLang) > -1) {
input = args.splice(0, args.length - 2).toString();
} else {
inLang = "en";
outLang = "en";
}
let inInt = parseInt(input);
if (ids[outLang].indexOf(inInt) > -1) {
try {
let out = await getCardInfo(inInt, outLang, user, userID, channelID, message, event);
if (hasImage) {
if (out[1].length == 1 && messageMode & 0x2) {
sendLongMessage(out[0], user, userID, channelID, message, event, embCT, out[1][0]);
} else {
postImage(out[1], out[0], outLang, user, userID, channelID, message, event);
}
} else {
sendLongMessage(out[0], user, userID, channelID, message, event, embCT);
}
} catch (e) {
console.log("Error with search by ID:");
console.log(e);
}
} else {
try {
let index = nameCheck(input, inLang);
if (index > -1 && index in ids[inLang]) {
index = ids[outLang].indexOf(ids[inLang][index]); //this is kind of messy - it takes the index nameCheck returned for the in language, and gets the index in the out language with the same ID.
if (index > -1 && index in ids[inLang]) {
let out = await getCardInfo(ids[outLang][index], outLang, user, userID, channelID, message, event);
if (hasImage) {
if (out[1].length == 1 && messageMode & 0x2) {
sendLongMessage(out[0], user, userID, channelID, message, event, embCT, out[1][0]);
} else {
postImage(out[1], out[0], outLang, user, userID, channelID, message, event);
}
} else {
sendLongMessage(out[0], user, userID, channelID, message, event, embCT);
}
} else {
console.log("No corresponding entry in out language DB, please try again.");
return;
}
} else {
console.log("Invalid card ID or name, please try again.");
return;
}
} catch (e) {
console.log("Error with search by name:");
console.log(e);
}
}
}
function getCardInfo(code, outLang, user, userID, channelID, message, event) {
markdownno = 0;
let index = ids[outLang].indexOf(code);
if (index === -1) {
console.log("Invalid card ID, please try again.");
return "Invalid card ID, please try again.";
}
let card = contents[outLang][0].values[index]; //blame SQL.js
let name = names[outLang][0].values[index];
return new Promise(function(resolve, reject) {
let out = "__**" + quo + name[1] + quo + "**__\n"; //within the SQL.js results, calls like this refer to columns of the SQL table in order, in this case it's the actual name. See readme for SQL schema.
markdownno += quo.length * 2;
let alIDs = [code];
let ot = getOT(ids[outLang].indexOf(code), outLang);
if (aliases[outLang][ids[outLang].indexOf(code)] > 0) {
if (ot === getOT(ids[outLang].indexOf(aliases[outLang][ids[outLang].indexOf(code)]), outLang)) { //*goes cross-eyed* If the card with the alias is the same OT as the card with the base ID, then it's an alt art as opposed to an anime version or pre errata or something.
code = aliases[outLang][ids[outLang].indexOf(code)];
ot = getOT(ids[outLang].indexOf(code), outLang);
alIDs = [code];
for (let i = 0; i < aliases[outLang].length; i++) {
if (aliases[outLang][i] === code && getOT(i, outLang) === ot) {
alIDs.push(ids[outLang][i]);
}
}
}
} else if (aliases[outLang].indexOf(code) > 0) {
for (let i = 0; i < aliases[outLang].length; i++) {
if (aliases[outLang][i] === code && getOT(i, outLang) === ot) {
alIDs.push(ids[outLang][i]);
}
}
}
if (messageMode & 0x1) {
out += bo + quo + quo + quo + jvex + "ID: ";
} else {
out += "**ID**: ";
}
markdownno += quo.length * 3 + bo.length + jvex.length;
out += alIDs.join("|") + "\n";
let sets = setCodeCheck(index, outLang, user, userID, channelID, message, event); //this handles all the archetype stuff
if (sets) { //returns false if part of no archetypes
if (messageMode & 0x1) {
out += "Archetype: ";
} else {
out += "**Archetype**: ";
}
out += sets.join(", ");
}
out += "\n";
let stat = getOT(index, outLang);
Object.keys(lflist).forEach(function(key, index) { //keys of the banlist table are card IDs, values are number of copies allowed
if (stat.indexOf(key) > -1) {
let lim = 3;
if (lflist[key][code] || lflist[key][code] === 0) {
lim = lflist[key][code];
}
let re = new RegExp(key);
stat = stat.replace(re, key + ": " + lim);
}
});
request('https://yugiohprices.com/api/get_card_prices/' + name[1], function(error, response, body) { //https://yugiohprices.docs.apiary.io/#reference/checking-card-prices/check-price-for-card-name/check-price-for-card-name
if (!error && response.statusCode === 200 && JSON.parse(body).status === "success") {
let data = JSON.parse(body);
let low = 9999999999;
let hi = 0;
let avgs = [];
for (let price of data.data) {
if (price.price_data.status === "success") {
if (price.price_data.data.prices.high > hi) {
hi = price.price_data.data.prices.high;
}
if (price.price_data.data.prices.low < low) {
low = price.price_data.data.prices.low;
}
avgs.push(price.price_data.data.prices.average);
}
}
if (avgs.length > 0) {
let avg = (avgs.reduce((a, b) => a + b, 0)) / avgs.length;
if (messageMode & 0x1) {
out += "Status: " + stat + " Price: $" + low.toFixed(2) + "-$" + avg.toFixed(2) + "-$" + hi.toFixed(2) + " USD\n";
} else {
out += "**Status**: " + stat + " **Price**: $" + low.toFixed(2) + "-$" + avg.toFixed(2) + "-$" + hi.toFixed(2) + " USD\n";
}
} else {
if (messageMode & 0x1) {
out += "Status: ";
} else {
out += "**Status**: ";
}
out += stat + "\n";
}
} else {
if (messageMode & 0x1) {
out += "Status: ";
} else {
out += "**Status**: ";
}
out += stat + "\n";
}
embCT = null;
let types = getTypes(index, outLang);
if (checkType(index, outLang, 0x1000000000)) {
embCT = "Dark Synchro";
}
if (types.indexOf("Monster") > -1) {
let arrace = addEmote(getRace(index, outLang), "|");
let typesStr;
if (emoteMode < 2 && messageMode != 1) {
typesStr = types.join("/").replace("Monster", arrace[emoteMode]);
} else {
typesStr = types.join("/").replace("Monster", arrace[0]);
if (messageMode != 1) {
typesStr += " " + arrace[1];
}
}
if (messageMode & 0x1) {
out += "Type: " + typesStr + " Attribute: " + addEmote(getAtt(index, outLang), "|")[0] + "\n";
} else {
out += "**Type**: " + typesStr + " **Attribute**: " + addEmote(getAtt(index, outLang), "|")[emoteMode] + "\n";
}
let lvName = "Level";
let lv = getLevelScales(index, outLang);
let def = true;
if (types.indexOf("Xyz") > -1) {
lvName = "Rank";
} else if (types.indexOf("Link") > -1) {
lvName = "Link Rating";
def = false;
}
if (messageMode & 0x1) {
out += lvName + ": " + lv[0];
} else {
out += "**" + lvName + "**: " + lv[0] + " ";
}
if (emoteMode > 0) {
if (messageMode & 0x1) {
if (lvName == "Level") {
out += "✪";
} else if (lvName == "Rank") {
out += "⍟";
}
} else {
if (checkType(index, outLang, 0x1000000000)) { //is dark synchro
out += emoteDB["NLevel"] + " ";
} else {
out += emoteDB[lvName] + " ";
}
}
}
out += " ";
if (messageMode & 0x1) {
out += "ATK: ";
} else {
out += "**ATK**: ";
}
out += convertStat(card[5]) + " ";
if (def) {
if (messageMode & 0x1) {
out += "DEF: ";
} else {
out += "**DEF**: ";
}
out += convertStat(card[6]);
} else {
if (messageMode & 0x1) {
out += "Link Markers: ";
} else {
out += "**Link Markers**: ";
}
out += getMarkers(index, outLang);
}
if (types.indexOf("Pendulum") > -1) {
if (messageMode & 0x1) {
out += " Pendulum Scale: ";
} else {
out += " **Pendulum Scale**: ";
}
if (emoteMode > 0) {
if (messageMode & 0x1) {
out += "←" + lv[1] + "/" + lv[2] + "→ ";
} else {
out += " " + lv[1] + emoteDB["L.Scale"] + " " + emoteDB["R.Scale"] + lv[2] + " ";
}
} else {
out += lv[1] + "/" + lv[2];
}
}
out += "\n";
out += quo + quo + quo + quo + quo + quo;
markdownno += quo.length * 6;
let cardText = getCardText(index, outLang);
let textName = "Monster Effect";
if (types.indexOf("Normal") > -1) {
textName = "Flavour Text";
}
if (cardText.length === 4) {
if (messageMode & 0x1) {
out += cardText[0] + "``` ``" + cardText[2] + "``\n" + "```" + cardText[1] + "`````" + cardText[3] + "``";
} else {
out += "**" + cardText[2] + "**: " + cardText[0] + "\n";
out += "**" + cardText[3] + "**: " + cardText[1];
}
} else {
if (messageMode & 0x1) {
out += cardText[0] + "``` ``" + textName + "``";
} else {
out += "**" + textName + "**: " + cardText[0];
}
}
markdownno += quo.length * 3;
} else if (types.indexOf("Spell") > -1 || types.indexOf("Trap") > -1) {
let typeemote = addEmote(types, "/");
if ((typeemote[0] == "Spell" || typeemote[0] == "Trap") && emoteMode > 0) {
typeemote[1] += emoteDB["NormalST"];
typeemote[2] += emoteDB["NormalST"];
}
if (checkType(index, outLang, 0x100)) { //is trap monster
let arrace = addEmote(getRace(index, outLang), "|");
let typesStr;
if (emoteMode < 2 && messageMode != 1) {
typesStr = arrace[emoteMode] + "/" + typeemote[emoteMode];
} else {
typesStr = arrace[0] + "/" + typeemote[0];
if (messageMode != 1) {
typesStr += " " + arrace[1] + typeemote[1];
}
}
if (messageMode & 0x1) {
out += "Type: " + typesStr + " Attribute: " + addEmote(getAtt(index, outLang), "|")[0] + "\n";
out += "Level: " + getLevelScales(index, outLang)[0];
} else {
out += "**Type**: " + typesStr + " **Attribute**: " + addEmote(getAtt(index, outLang), "|")[emoteMode] + "\n";
out += "**Level**: " + getLevelScales(index, outLang)[0];
}
if (emoteMode > 0) {
if (messageMode & 0x1) {
out += "✪";
} else {
out += " " + emoteDB["Level"];
}
}
if (messageMode & 0x1) {
out += " " + " ATK: " + convertStat(card[5]) + " DEF: " + convertStat(card[6]) + "\n";
} else {
out += " " + " **ATK**: " + convertStat(card[5]) + " **DEF**: " + convertStat(card[6]) + "\n";
}
} else {
if (messageMode & 0x1) {
out += "Type: " + typeemote[0] + "\n";
} else {
out += "**Type**: " + typeemote[emoteMode] + "\n";
}
}
if (messageMode & 0x1) {
out += "``````" + name[2].replace(/\n/g, "\n") + "``` ``Effect``\n";
} else {
out += "**Effect**: " + name[2].replace(/\n/g, "\n");
}
markdownno += quo.length * 3;
} else {
if (messageMode & 0x1) {
out += "``````" + name[2].replace(/\n/g, "\n") + "``` ``Card Text``";
} else {
out += "**Card Text**: " + name[2].replace(/\n/g, "\n");
}
markdownno += quo.length * 3;
}
out += bo;
resolve([out, alIDs]);
});
});
}
async function postImage(code, out, outLang, user, userID, channelID, message, event) {
try {
let imageUrl = imageUrlMaster;
let ot = getOT(ids[outLang].indexOf(code[0]), outLang);
if (["Anime", "Illegal", "Video Game"].indexOf(ot) > -1) {
imageUrl = imageUrlAnime;
}
if (ot === "Custom") {
imageUrl = imageUrlCustom;
}
if (code.length > 1) {
let pics = [];
for (let cod of code) {