forked from OceanUwU/slaytabase
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.js
More file actions
1900 lines (1766 loc) · 85.5 KB
/
commands.js
File metadata and controls
1900 lines (1766 loc) · 85.5 KB
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
import { bot, search, setActivity } from './index.js';
import db from './models/index.js';
import { User, EmbedBuilder } from 'discord.js';
import { createCanvas, createImageData, loadImage, registerFont } from 'canvas';
import drawMultilineText from './canvas-multiline-text.js';
import GIFEncoder from 'gif-encoder-2';
import { fmFunc } from 'calculator-by-str';
import { ChartJSNodeCanvas } from 'chartjs-node-canvas';
import { plot } from 'plot';
import '@plotex/render-image';
import fs from 'fs';
import fn from './fn.js';
import embed from './embed.js';
import cfg from './cfg.js';
import fetch from 'node-fetch';
import FormData from 'form-data';
import gm from 'gm';
import { execFile } from 'child_process';
import optipng from 'optipng-bin';
import owofify from 'owoifyx';
const owoify = owofify.default;
import petPetGif from 'pet-pet-gif';
import canvasGif from 'canvas-gif';
import googleIt from 'google-it';
import Perspective from './perspectivejs.js';
import { JSDOM } from 'jsdom';
import { off } from './dailyDiscussion.js';
registerFont('./memetemplates/Kreon-Regular.ttf', {family: "Kreon"});
const mtsbotdata = JSON.parse(fs.readFileSync('./docs/mtsbotdata.json'));
const charter = new ChartJSNodeCanvas({width: 800, height: 600, backgroundColour: 'white'});
const delSearchLimit = 25;
const masks = {};
['a', 's', 'p'].forEach(i => masks[i] = loadImage(`./artpreview/${i}.png`));
const shadows = {};
['a', 's', 'p'].forEach(i => shadows[i] = loadImage(`./artpreview/${i}s.png`));
const cuts = {};
['a', 's', 'p'].forEach(i => cuts[i] = loadImage(`./artpreview/${i}c.png`));
const cardTypes = {
Attack: 'a',
Power: 'p',
Skill: 's',
Status: 's',
Curse: 's'
};
const optimise = async filename => new Promise(res => execFile(optipng, ['-out', filename, filename], res));
async function getMemeItems(arg, options, msg) {
try {
let args = arg.split('=');
if (args.length != options.items.length)
return {title: `This meme requires exactly ${options.items.length} item${options.items.length == 1 ? '' : 's'}. Separate items with the "=" symbol.`};
let items = await Promise.all(args.map(async (a, i) => {
a = new String(a.trim());
a.filter = arg.filter;
if (a.startsWith('user?')) {
let id = a.slice(5)
let user;
if (id == 'me')
user = msg.author;
else
user = await bot.users.fetch(id).catch(e => {});
if (user) {
user.url = user.avatarURL().replace('webp', 'png');
user.image = await loadImage(user.url);
return user;
}
} else if (a.startsWith('att?')) {
let n = parseInt(a.slice(4));
let attachment = msg.attachments.at(n-1);
if (attachment == undefined)
return {title: 'format for attachments is att?n?name where n is the number of the attachment e.g. att?1?awsom'};
attachment.image = await loadImage(attachment.url);
attachment.item = {name: a.slice(6)};
return attachment;
}
return options.items[i] == 1 ? a+"" : fn.find(a);
}));
for (let i in items) {
if (options.items[i] == 0) {
let item = items[i];
if (items[i] instanceof User || items[i].hasOwnProperty('ephemeral')) continue;
item.embed = await embed({...item.item, score: item.score, query: arg});
if (item.embed.data.thumbnail == null)
return {title: `No image for ${item.item.itemType} "${item.item.name}"`};
item.url = item.embed.data.thumbnail.url
item.image = await loadImage(item.url);
if (args[i].endsWith("?left") || args[i].endsWith("?right")) {
let canvas = createCanvas(item.image.width/2,item.image.height);
canvas.getContext('2d').drawImage(item.image, args[i].endsWith("?left") ? 0 : -item.image.width/2, 0);
item.image = canvas;
}
}
}
return items;
} catch(e) {
console.error(e);
return {title: 'failed to generate image'};
}
}
async function meme(msg, arg, options) {
try {
let items = await getMemeItems(arg, options, msg);
if (!Array.isArray(items))
return items;
if (options.hasOwnProperty('bg')) {
let canvas = createCanvas(options.w, options.h);
let ctx = canvas.getContext('2d');
ctx.drawImage(await loadImage('./memetemplates/'+options.bg), 0, 0);
if (options.hasOwnProperty('put'))
for (let p of options.put) {
if (Array.isArray(p[1])) (new Perspective(ctx, items[p[0]].image)).draw(p[1]);
else ctx.drawImage(typeof p[0] == 'number' ? items[p[0]].image : await loadImage('./memetemplates/'+p[0]), p[1], p[2], p[3], p[4]);
}
if (options.hasOwnProperty('texts'))
for (let t of options.texts) {
ctx.fillStyle = t[5];
let text = typeof items[t[0]] == 'string' ? items[t[0]] : (items[t[0]] instanceof User ? items[t[0]].username : items[t[0]].item.name.toUpperCase());
drawMultilineText(ctx, options.upper ? text.toUpperCase() : text, {
rect: {x: t[1], y: t[2], width: t[3], height: t[4]},
lineHeight: 1.0,
minFontSize: 1,
maxFontSize: 500,
});
/*drawText.default(ctx, typeof items[t[0]] == 'string' ? items[t[0]] : (items[t[0]] instanceof User ? items[t[0]].username : items[t[0]].item.name.toUpperCase()), font,
{x: t[1], y: t[2], width: t[3], height: t[4]},
{minSize: 5, maxSize: 200, vAlign: 'center', hAlign: 'center', textFillStyle: t[5], fitMethod: 'box', drawRect: false}
);*/
}
let encoder = new GIFEncoder(options.w, options.h);
encoder.setDelay(500);
encoder.start();
encoder.addFrame(ctx);
encoder.finish();
let filename = `export${String(Math.random()).slice(2)}.gif`;
fs.writeFileSync(filename, encoder.out.getData());
return {
title: ' ',
image: {url: 'attachment://'+filename},
files: [filename],
color: typeof items[0] == 'string' || items[0] instanceof User || items[0].hasOwnProperty('ephemeral') ? null : items[0].embed.data.color,
};
}
} catch(e) {
console.error(e);
return {title: 'failed to generate image'};
}
}
async function gifMeme(msg, arg, bg, fn, options={}) {
try {
let items = await getMemeItems(arg, {items: [0]}, msg);
if (!Array.isArray(items))
return items;
let buffer = await canvasGif(bg, (ctx, w, h, totalFrames, currentFrame) => fn(ctx, w, h, totalFrames, currentFrame, items), options);
let filename = `export${String(Math.random()).slice(2)}.gif`;
fs.writeFileSync(filename, buffer);
return {
title: ' ',
image: {url: 'attachment://'+filename},
files: [filename],
color: typeof items[0] == 'string' || items[0] instanceof User || items[0].hasOwnProperty('ephemeral') ? null : items[0].embed.data.color,
};
} catch (e) {
console.error(e);
return {title: 'failed to generate gif'};
}
}
async function makesweetMeme(template, arg, msg) {
try {
if (cfg.mkswtKey == null)
return {title: "This kind of gif is not currently enabled to generate."};
let items = await getMemeItems(arg, {items: [0]}, msg);
if (!Array.isArray(items))
return items;
let filename = `export${String(Math.random()).slice(2)}.png`;
await new Promise(async (resolve, reject) => {
let stream = fs.createWriteStream(filename);
let res = await fetch(items[0].url);
res.body.pipe(stream);
res.body.on("error", reject);
stream.on("finish", resolve);
});
let img = await loadImage(filename);
let canvas = createCanvas(img.width/(arg.endsWith("?left") || arg.endsWith("?right") ? 2 : 1),img.height);
canvas.getContext('2d').drawImage(img, arg.endsWith("?right") ? -img.width/2 : 0, 0);
fs.rmSync(filename);
filename = filename.replace('png', 'jpg');
fs.writeFileSync(filename, canvas.toBuffer('image/jpeg'));
let body = new FormData();
body.append('images', fs.readFileSync(filename), 'file.jpg');
let req = await fetch(`https://api.makesweet.com/make/${template}?text=${typeof items[0] == 'string' ? items[0] : (items[0] instanceof User ? items[0].username : items[0].item.name)} my beloved`, {
method: 'POST',
headers: {'Authorization': cfg.mkswtKey},
body
});
if (req.status === 200) {
fs.rmSync(filename);
filename = filename.replace('jpg', 'gif');
await new Promise(async res => {
let stream = fs.createWriteStream(filename);
req.body.pipe(stream);
stream.on("finish", res);
});
return {
title: ' ',
image: {url: 'attachment://'+filename},
files: [filename],
color: typeof items[0] == 'string' || items[0] instanceof User || items[0].hasOwnProperty('ephemeral') ? null : items[0].embed.color,
};
} else {
fs.rmSync(filename);
return {title: `Error: ${(await req.json()).error}`};
}
} catch(e) {
console.error(e);
return {title: 'failed to generate gif'};
}
}
const commands = {
exact: {
'help': () => ({
title: bot.user.username,
description: `Search for items from Slay the Spire with <item>.
Search for items from mods with [[item]].
You can use up to 10 commands in a message.
If you edit or delete your message, I will update my reply to it, according to your changes.
Use **/i** to use autocomplete to find an item.
Type <fullhelp> for information on all of the bot's commands.`,
thumbnail: {url: bot.user.avatarURL()},
}),
'fullhelp': () => ({
title: bot.user.username,
description: `Search for an item with <item name>.
If the result isn\'t what you were looking for, you can also include the following in your search query: character, item type (e.g. card, relic, potion), type (e.g. skill, elite), or text from its description.
Anything highlighted in **bold** is a searchable keyword.
You can use up to 10 commands in a message.
If you edit or delete your message, I will update my reply to it, according to your changes.
I'll spoiler tag my reply to any messages which include "(s)" anywhere.
I'll ignore any messages which include the backtick (\`) symbol anywhere.
<item> will search through items from only vanilla Slay the Spire and mods specific to the server (can be set by server admins with **/addservermod**).
You can replace <item> with [[item]] to search through ALL mods.
You can use **/i** to use autocomplete to find an item.
You can use **/run** to run commands without anyone else seeing your result.
You can also search online at ${cfg.exportURL}/search
Server admins can add custom commands with **/customcommands**
__Commands:__
<[item name]> displays info about an item
- search query may include the following filters:
- - cost=? - only returns cards with specified cost
- - type=? - specify item type (e.g. relic, card, attack)
- - mod=? - specify mod name
- - rarity=? - specify item rarity
- - in=drawpile - results must include the phrase "draw pile" (ignores spaces)
- - ex=? - no results will include the specified phrase
- - r=2 - get second result
<s~item>, <d~[item]>, <i~[item name]>, <t~[item]>, <f~[item]> and <~[item]> are the same as the above, but the result is formatted differently
<customcommands> - lists the server's custom commands
<del> deletes your last search in this channel
<?[search query]> shows the most likely results for a search query
- page=? - specify result page
<show10 [search query]> shows the full item details for the first 10 results for a search query
<count?[search query]> shows the total number of results for a search query (more helpful with filters!)
<ws?[mod]> - searches for a slay the spire mod on the steam workshop
<mtsbot?[item]> - searches ModTheSpire Bot's data for an item. has a different search, type <mtsbot?> for help
<memes> help with the bot's meme generator
<artpreview [card name]> takes your first attachment and uses it as card art for a card
<c~artpreview [card name]> compares the art preview to the current card
<cut~artpreview [card name]>
<searchtext [item name]> shows the text the bot can use when searching for an item
<choose [word1 word2 word3...]> chooses one of the specified words for you at random
<exporttxt [search query]> exports the search details for the first 100 results for a search query formatted as a text file
<exportjson [search query]> same as the above, but returns the raw json details
<calc [equation]> https://www.npmjs.com/package/calculator-by-str
<plot [equation] [args]> - type <plot help> for more information
<remindme [time]> links you to a message in a certain amount of time (e.g. 10m, 5h, 30d)
<feedback?[message]> sends a message to a channel seen only by the bot author
<lists> links to the bot's data
<wiki?[search]> searches certain modding-related github repos for wiki pages
<mtg?[card]> searches scryfall for a card from magic the gathering
`,
thumbnail: {url: bot.user.avatarURL()},
}),
'del': async msg => {
let messages = await msg.channel.messages.fetch();
messages = messages.filter(i => i.author.id == bot.user.id);
let i = 0;
for (let m of messages) {
i++;
m = m[1];
let found = true;
let repliedTo;
if (m.reference)
repliedTo = await msg.channel.messages.fetch(m.reference.messageId).catch(()=>{});
if (m.content.includes(msg.author.id) || (repliedTo != null && repliedTo.author.id == msg.author.id)) {
await m.delete().catch(e => {});
await msg.delete().catch(e => {});
return;
}
if (i >= delSearchLimit) break;
}
return;
},
'spoiler': async msg => {
let messages = await msg.channel.messages.fetch();
messages = messages.filter(i => i.author.id == bot.user.id && i.reference != null);
let i = 0;
for (let m of messages) {
i++;
m = m[1];
let found = true;
let repliedTo = await msg.channel.messages.fetch(m.reference.messageId).catch(e => found = false);
if (!found) continue;
if (repliedTo.author.id == msg.author.id) {
await msg.delete().catch(e => {});
//spoiler hack
let origEmbeds = m.embeds;
if (origEmbeds.length > 0) {
await m.edit({content: `||https://bit.ly/3aSgJDF||`, embeds: [], allowedMentions: {repliedUser: false}}).catch(e => {});
await (new Promise(res => setTimeout(res, 1000)));
await m.edit({content: m.content, embeds: origEmbeds, allowedMentions: {repliedUser: false}}).catch(e => {});
}
return;
}
if (i >= delSearchLimit) break;
}
return;
},
'lists': async () => ({
title: "lists",
description: `web search: ${cfg.exportURL}/search\nexport: ${cfg.exportURL}\nfull data: https://github.com/OceanUwU/slaytabase/blob/main/docs/data.json\nfull data (formatted): https://github.com/OceanUwU/slaytabase/blob/main/docs/dataformatted.json\nmanually added items: https://github.com/OceanUwU/slaytabase/blob/main/extraItems.js`,
}),
'customcommands': async msg => {
if (!msg.inGuild()) return {title: "You must be in a server to use custom commands."};
let commands = await db.CustomCommand.findAll({where: {guild: msg.guildId}});
return {title: `Custom commands in the \`${msg.guild.name}\` server:`, description: commands.map(c => `<${c.call}>`).join(', ')};
},
'forcestop': async (msg, arg) => {
if (cfg.overriders.includes(msg.author.id)) {
off.off = true;
bot.user.setStatus('idle');
bot.user.setActivity('about to restart...');
return {title: "stopping soon."};
} else return {title: "...nice try"};
},
'make me a card idea': async (msg, arg) => {
let numEffects = 2 + Math.round(Math.random());
let cost = Math.floor(Math.random() * 4);
let rarity = ['Common', 'Uncommon', 'Rare'][Math.floor(Math.random() * 3)];
let name = [];
let cardEffects = [];
let query = new String('randomitem type=card');
query.filter = arg.filter;
for (let i = 0; i < numEffects; i++) {
let card = fn.find(query).item;
let nameWords = card.name.split(' ');
let effects = card.description.split('.').filter(e => fn.unPunctuate(e).length > 2);
if (effects.length == 0) continue;
name.push(nameWords[Math.floor(Math.random() * nameWords.length)]);
cardEffects.push(effects[Math.floor(Math.random() * effects.length)].replaceAll('\n','').trim());
}
name = name.join(' ');
let description = cardEffects.join('.\n').replaceAll('*', '')+'.';
let cardType = description.toLowerCase().includes('deal') && description.toLowerCase().includes('damage') ? 'Attack' : (Math.random() > 0.8 ? 'Power' : 'Skill');
let generated = await meme(msg, `${cost}=${name.replaceAll('=','')}=${description.replaceAll('~', '').replaceAll('=','').replace(/\<\:(.*)\>/g, '')}=${cardType}`, {
w: 350,
h: 500,
bg: 'makeacard.png',
items: [1, 1, 1,1],
put: [],
texts: [
[0, 43, 32, 40, 42, 'white'],
[1, 72, 75, 217, 32, 'white'],
[2, 67, 283, 198, 156, 'white'],
[3, 146, 235, 55, 16, 'white'],
]
});
return {
title: name,
description: `${rarity} ${cardType} / ${cost} <:colorless_energy:382625433016991745> / The Slaytabase / No One\n\n${description}`,
thumbnail: generated.image,
files: generated.files,
footer: {text: 'i made this one just for you <3'}
};
},
'adventurer board forecast': async msg => {
return {
title: 'The board forecast for this week:',
url: 'https://steamcommunity.com/sharedfiles/filedetails/?id=2848995399',
description: [-1, 0, 1, 2, 3, 4, 5, 6].map(d => {
let date = new Date(Date.now() + d * 1000 * 60 * 60 * 24);
let boards = fn.findAll(`type=board`);
let dayOfYear = Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
let board = boards[dayOfYear % boards.length];
return `${d==0?'__':''}${date.toLocaleDateString(undefined, {weekday: 'long', day: 'numeric', month: 'long', timeZone: 'UTC'})}${d==0?'__':''}: [${board.item.name}](${board.item.url})`;
}).join('\n')
}
},
'star compass': msg => ({title: ' ', description: 'Oops, I dropped it. Oh well.'}),
'xy': msg => ({
title: 'Looks like a case of the good ol\' XY problem.',
url: 'https://xyproblem.info/',
description: 'Ask about the issue, not about your attempted solution and give us some goddamn info!!',
thumbnail: {url: 'https://i.imgur.com/bCmEbPU.png'},
color: 15438388,
})
},
prefix: {
'?': async (msg, arg, args) => {
if (arg.startsWith('??')) {
let nArg = new String('?'+arg);
nArg.filter = arg.filter;
let item = fn.find(nArg);
return (await embed({...item.item, score: item.score, query: nArg}, undefined, undefined, false)).data;
}
let results = fn.findAll(arg);
let page = results.page;
let totalResults = results.total;
results = results.slice(0, 10);
let resultText = results.map((i, index) => `${(page*10)+index+1}: ${i.item.itemType == 'card' ? i.item.character[0].replace('The ', '').toLowerCase() : ''} ${i.item.itemType} **${i.item.name}** - ${i.score.toFixed(2)}`).join('\n');
let firstEmbed = results.length > 0 ? await embed(results[0].item, msg, undefined, false) : {data: {thumbnail: null}};
return {
title: `Searched for "${args.filter(a => !a.includes('=')).join(' ').slice(0, 70)}"`,
url: `${cfg.exportURL}/search?${encodeURIComponent(arg)}`,
description: results.length == 0 ? 'No results.' : resultText,
thumbnail: firstEmbed.data.thumbnail,
footer: {text: `Page ${page+1}/${Math.ceil(totalResults/10)}`},
color: 14598591,
};
},
'mtsbot?': async (msg, arg, args, oa) => {
try {
if (arg.length == 0 || arg == 'help' || arg == '?')
return {
title: 'ModTheSpire Bot data archive',
color: 16745472,
description: `You can use this command to search for items from the data of ModTheSpire Bot, which includes a bunch of older mods that may not be included in Slaytabase\'s data.
You must search for the exact item name with this search.
There are some filters available, but these are custom to this command and work differently from the ones from the regular search. Examples:
- cost=1 cost=x etc
- type=card type=skill etc
- rarity=boss
- mod=basegame mod=downfall etc (can be either modid or mod name)
- in=deal6damage in=gain5block etc (checks if the description has a certain string)
- ex=damage (makes sure description does NOT contain a certain string)
- r=2 r=3 etc (get nth result)
`
};
let filters = args.filter(a => a.includes('=') && !a.startsWith('=') && !a.endsWith("="));
args = args.filter(i => !filters.includes(i));
let argFilter = arg.filter;
arg = args.join(' ');
filters = filters.map(f => [f.slice(0, f.indexOf('=')), f.slice(f.indexOf('=')+1)]);
let items = mtsbotdata;
if (argFilter)
items = items.filter(i => argFilter({item: i}));
if (args.length > 0) {
items = items.filter(i => fn.unPunctuate(i.name) == arg);
if (oa.includes('+')) items = items.filter(i => i.name.includes('+'));
else items = items.filter(i => !i.name.includes('+'));
}
let resultNum = 0;
for (let f of filters)
switch (f[0]) {
case 'cost':
items = items.filter(i => i.hasOwnProperty('cost') && i.cost.toLowerCase() == f[1]);
break;
case 'type':
items = items.filter(i => i.hasOwnProperty('type') && i.type.toLowerCase() == f[1] || i.itemType == f[1]);
break;
case 'rarity':
items = items.filter(i => i.hasOwnProperty('rarity') && i.rarity.toLowerCase() == f[1] || i.hasOwnProperty('tier') && i.tier.toLowerCase() == f[1]);
break;
case 'mod':
items = items.filter(i => i.hasOwnProperty('modId') && i.modId.includes(f[1]) || i.hasOwnProperty('mod') && (fn.unPunctuate(i.mod.replaceAll(' ', '')).includes(f[1]) || f[1].includes(fn.unPunctuate(i.mod.replaceAll(' ', '')))));
break;
case 'in':
items = items.filter(i => i.hasOwnProperty('description') && fn.unPunctuate(i.description.replaceAll(' ', '')).includes(f[1]));
break;
case 'ex':
items = items.filter(i => i.hasOwnProperty('description') && !fn.unPunctuate(i.description.replaceAll(' ', '')).includes(f[1]));
break;
case 'r':
let r = Math.max(1, parseInt(f[1])) - 1;
if (!Number.isNaN(r)) resultNum += r;
break;
}
if (items.length >= resultNum+1) {
let i = items[resultNum];
let desc = '';
let keywordify = true;
switch (i.itemType) {
case 'mod':
desc = `\`Mod\` \`v${i.version}\`\nAuthor: ${i.authors.join(' ')}\n${i.description}`;
keywordify = false;
break;
case 'card':
desc = `\`${i.type}\` \`${i.cost}\` \`${i.rarity}\` \`${i.color}\` \`${i.mod}\`\n${i.description}`;
break;
case 'relic':
desc = `\`${i.tier} Relic\`${i.pool == '' ? '' : ` \`${i.pool}\``} \`${i.mod}\`\n${i.description}\n*${i.flavorText}*`;
break;
case 'potion':
desc = `\`${i.rarity} Potion\` \`${i.mod}\`\n${i.description}`;
break;
case 'keyword':
desc = `\`${i.mod} Keyword\`\n${i.description}`;
break;
case 'creature':
desc = `\`${i.mod} ${i.type} Creature\` \`${i.minHP}-${i.maxHP}HP\``;
break;
}
if (keywordify)
desc = desc.replaceAll('\n', '\n ').split(' ').map(w => w.includes(':') ? `**${w.slice(w.indexOf(':')+1)}**` : w).join(' ').replaceAll('\n ', '\n')
.replaceAll('[R]', '<:red_energy:382625376838615061>')
.replaceAll('[G]', '<:green_energy:646206147220471808>')
.replaceAll('[B]', '<:blue_energy:668151236003889184>')
.replaceAll('[W]', '<:purple_energy:620384758068674560>')
.replaceAll('[E]', '<:colorless_energy:382625433016991745>');
return {title: i.name, description: desc, footer: items.length > 1 ? {text: `result ${resultNum+1}/${items.length}`} : null, color: 16745472};
} else return {color: 0, title: `${items.length} results found.`}
} catch (e) {
console.error(e);
return {color: 0, title: 'some kind of error happened?'};
}
},
'count?': (msg, arg) => ({title: `Found ${fn.findAll(arg).total} results for "${arg}"`}),
'show': async (msg, arg, args) => {
let num = parseInt(args[0]);
if (Number.isNaN(num)) {
let nArg = new String('show'+arg);
nArg.filter = arg.filter;
let item = fn.find(nArg);
return (await embed({...item.item, score: item.score, query: nArg}, undefined, undefined, false)).data;
} else if (num < 1 || num > 10)
return {title: 'number of items to show must be 1-10'};
let query = new String(args.slice(1).join(' '));
query.filter = arg.filter;
let results = fn.findAll(query);
results = results.slice(0, num);
let embeds = await Promise.all(results.map(async (item, index) => {
let e = await embed({...item.item, score: item.score, query}, undefined, undefined, index != 0);
e.data.description = `${item.score.toFixed(2)} / ${e.data.description}`;
e.data.footer = null;//{text: `${String(Math.round((1 - item.score) * 100))}% sure`};
return e;
}));
if (embeds.length == 0)
return {title: 'no results'};
console.log({...embeds[0].data, extra_embeds: embeds.slice(1)});
return {...embeds[0].data, extra_embeds: embeds.slice(1)};
},
'searchtext ': async (msg, arg) => {
let result = fn.find(arg);
if (result.item.itemType == 'fail') return {title: "no result?"};
if (!result.hasOwnProperty('terms'))
return {
title: `"${arg}" yields:`,
description: result.item.searchText,
};
return {
title: `"${arg.slice(0,70)}" (${result.score}) yields:`,
description: result.item.searchText.split(' ').map(w => result.terms.includes(w) ? `__${w}__` : w).join(' '),
};
},
'data?': async (msg, arg) => {
let result = fn.find(arg);
if (result.item.itemType == 'fail') return {title: "no result?"};
return {
title: ' ',
description: `\`\`\`json\n${JSON.stringify(result.item, null, 4)}\n\`\`\``,
};
},
'exportjson': async (msg, arg) => {
let results = fn.findAll(arg).slice(0, 100);
results.forEach(r => delete r.matches);
let filename = `search${String(Math.random()).slice(2)}.json`;
fs.writeFileSync(filename, JSON.stringify(results, null, 4));
return {
title: `JSON file for first 100 results of search for query "${arg}" attached.`,
files: [filename],
};
},
'exporttxt': async (msg, arg) => {
let results = (await Promise.all(fn.findAll(arg).slice(0, 100).map(async r => {
let e = await embed({...r.item, score: r.score, query: arg}, msg);
return `${e.data.title} / ${e.data.description}`.replace(r.item.description, r.item.originalDescription).replaceAll('\n\n', '\n').replaceAll(r.item.character[2], '⚪');
}))).join('\n\n');
let filename = `search${String(Math.random()).slice(2)}.txt`;
fs.writeFileSync(filename, results);
return {
title: `Text file for first 100 results of search for query "${arg}" attached.`,
files: [filename],
};
},
'i~': async (msg, arg) => {
let item = fn.find(arg);
let itemEmbed = await embed({...item.item, score: item.score, query: arg}, undefined, undefined, false);
let image = itemEmbed.data.thumbnail;
if (arg.endsWith('?left') || arg.endsWith('?right')) {
try {
if (image && image.hasOwnProperty('url')) {
let img = await loadImage(image.url);
let canvas = createCanvas(img.width/2,img.height);
canvas.getContext('2d').drawImage(img, arg.endsWith("?left") ? 0 : -img.width/2, 0);
let filename = `export${String(Math.random()).slice(2)}.gif`;
fs.writeFileSync(filename, canvas.toBuffer());
return {
title: ' ',
image: {url: 'attachment://'+filename},
files: [filename],
color: itemEmbed.data.color,
};
}
} catch (e) {
return {title: 'error cropping'};
}
}
return {
title: image == null ? `No image for ${item.item.itemType} "${item.item.name}"` : ' ',
image: image,
color: itemEmbed.data.color,
};
},
'img ': async (msg, arg) => {
return await commands.prefix['i~'](msg, arg);
},
't~': async (msg, arg) => {
let item = fn.find(arg);
let itemEmbed = await embed({...item.item, score: item.score, query: arg}, undefined, undefined, false);
return {
title: itemEmbed.data.thumbnail == null ? `No image for ${item.item.itemType} "${item.item.name}"` : '',
thumbnail: itemEmbed.data.thumbnail,
color: itemEmbed.data.color,
};
},
'f~': async (msg, arg) => {
let item = fn.find(arg);
let itemEmbed = await embed({...item.item, score: item.score, query: arg}, undefined, undefined, false);
return {
...itemEmbed.data,
thumbnail: {},
image: itemEmbed.data.thumbnail,
};
},
'd~': async (msg, arg) => {
let item = fn.find(arg);
let itemEmbed = await embed({...item.item, score: item.score, query: arg}, undefined, undefined, false);
switch (item.item.itemType) {
case 'relic':
itemEmbed.data.description = itemEmbed.data.description.split('\n').slice(0,-1).join('\n');
break;
case 'boss':
itemEmbed.data.description = itemEmbed.data.description.split('\n').slice(0,3).join('\n');
break;
case 'event':
itemEmbed.data.description = `\n\n${item.item.description.replace('\n', ' ')}`;
break;
default:
break;
}
return {
...itemEmbed.data,
title: ' ',
thumbnail: null,
footer: null,
description: `[${itemEmbed.data.title}](${itemEmbed.data.url}): ${itemEmbed.data.description.split('\n').slice(2).join(' ')}`,
};
},
'~': async (msg, arg) => {
let item = fn.find(arg);
let itemEmbed = await embed({...item.item, score: item.score, query: arg}, undefined, undefined, false);
return {
...itemEmbed.data,
footer: null,
description: null,
};
},
's~': async (msg, arg) => {
let item = fn.find(arg);
let itemEmbed = await embed({...item.item, score: item.score, query: arg}, undefined, undefined, false);
switch (item.item.itemType) {
case 'event':
itemEmbed.data.description = `\n\n${item.item.description.replace('\n', ' ')}`;
break;
}
return {
...itemEmbed.data,
title: ' ',
description: `[${itemEmbed.data.title}](${itemEmbed.data.url}) - ${itemEmbed.data.description.replace('\n\n', '$$$$$').replaceAll('\n', ' ').replace('$$$', '\n')}`,
thumbnail: null,
footer: null,
};
},
'owo~': async (msg, arg) => {
let item = fn.find(arg);
let data = (await embed({...item.item, score: item.score, query: arg}, undefined, undefined, false)).data;
data.title = owoify(data.title);
data.description = owoify(data.description)
if (data.footer)
data.footer.text = owoify(data.footer.text)
return data;
},
'choose ': async (msg, arg, args) => {
if (args.length > 0)
return {
title: `I choose "${args[Math.floor(Math.random() * args.length)]}"`,
};
},
'c~artpreview ': async (msg, arg) => {
try {
let args = arg.split('=');
let att = 0;
if (args.length > 1)
att = parseInt(args[1])-1;
let art = msg.attachments.at(att);
if (art == undefined) return {title: 'you need to attach an image to preview!'};
args[0] = new String(args[0]);
args[0].filter = arg.filter;
let item = fn.find(args[0]);
if (!item.item.hasOwnProperty('itemType') || !['card', 'relic'].includes(item.item.itemType))
return {title: `that item couldn\'t be previewed. found ${item.item.itemType} "${item.item.name}"`};
let itemEmbed = await embed({...item.item, score: item.score, query: args[0]});
switch (item.item.itemType) {
case 'card':
let artcanvas = createCanvas(500,380);
let artctx = artcanvas.getContext('2d');
artctx.drawImage(await loadImage(art.url), 0, 0, 500, 380);
artctx.globalAlpha = 0.25;
artctx.drawImage(await shadows[cardTypes[item.item.type]], 0, 0);
artctx.globalAlpha = 1;
artctx.globalCompositeOperation = 'destination-out';
artctx.drawImage(await masks[cardTypes[item.item.type]], 0, 0);
let canvas = createCanvas(1356,874);
let ctx = canvas.getContext('2d');
ctx.drawImage(await loadImage(itemEmbed.data.thumbnail.url), 0, 0, 678, 874, 0, 0, 678, 874);
ctx.drawImage(artcanvas, 89, 123);
ctx.drawImage(await loadImage(itemEmbed.data.thumbnail.url), 678, 0);
let filename = `${(item.item.id.includes(':') ? item.item.id.slice(item.item.id.indexOf(':')+1) : item.item.id).replaceAll(' ', '-')}_preview-${String(Math.random()).slice(10)}.png`;
fs.writeFileSync(filename, canvas.toBuffer());
let cutcanvas = createCanvas(500,380);
let cutctx = cutcanvas.getContext('2d');
cutctx.drawImage(await loadImage(art.url), 0, 0, 500, 380);
cutctx.globalCompositeOperation = 'destination-out';
cutctx.drawImage(await cuts[cardTypes[item.item.type]], 0, 0);
let filename2 = filename.replace('_preview-', '_p-');
fs.writeFileSync(filename2, cutcanvas.toBuffer());
await optimise(filename2);
let smallcanvas = createCanvas(250,190);
let smallctx = smallcanvas.getContext('2d');
smallctx.drawImage(cutcanvas, 0, 3, 250, 190);
let filename3 = filename2.replace('_p-', '-');
fs.writeFileSync(filename3, smallcanvas.toBuffer());
await optimise(filename3);
return {
title: item.item.name,
description: '250x190 →',
image: {url: 'attachment://'+filename},
thumbnail: {url: 'attachment://'+filename3},
footer: {iconURL: 'attachment://'+filename2, text: '← 500x380'},
files: [filename, filename2, filename3],
color: itemEmbed.data.color,
};
case 'relic':
let rFilename = `${(item.item.id.includes(':') ? item.item.id.slice(item.item.id.indexOf(':')+1) : item.item.id).replaceAll(' ', '-')}_preview-${String(Math.random()).slice(10)}.png`;
let rFilename2 = rFilename.replace('_preview-', '_outline-');
let rFilename3 = rFilename.replace('_preview-', '-');
let relicanvas = createCanvas(256, 256);
let relictx = relicanvas.getContext('2d');
relictx.drawImage(await loadImage(art.url), 0, 0, 256, 256);
let relicImageData = relictx.getImageData(0, 0, 256, 256)
for (let i = 0; i < relicImageData.data.length; i += 4) {
relicImageData.data[i] = 255;
relicImageData.data[i+1] = 255;
relicImageData.data[i+2] = 255;
}
let outlinecanvas = createCanvas(256, 256);
let outlinectx = outlinecanvas.getContext('2d');
outlinectx.putImageData(relicImageData,0,0);
await new Promise(res => gm(outlinecanvas.toBuffer())
.edge(4, 4)
.write(rFilename2, err => {
if (err) throw err;
res();
}));
outlinectx.clearRect(0,0,256,256);
outlinectx.drawImage(await loadImage(rFilename2),0,0);
let outlineImageData = outlinectx.getImageData(0, 0, 256, 256);
let outlineImageDataBlack = createImageData(256,256);
for (let i = 0; i < outlineImageData.data.length; i += 4) {
outlineImageData.data[i] = 255;
outlineImageData.data[i+1] = 255;
outlineImageData.data[i+2] = 255;
outlineImageData.data[i+3] = 255-outlineImageData.data[i+3];
outlineImageDataBlack.data[i] = 0;
outlineImageDataBlack.data[i+1] = 0;
outlineImageDataBlack.data[i+2] = 0;
outlineImageDataBlack.data[i+3] = outlineImageData.data[i+3];
}
outlinectx.clearRect(0,0,256,256);
outlinectx.putImageData(outlineImageData,0,0);
fs.writeFileSync(rFilename2, outlinecanvas.toBuffer());
outlinectx.putImageData(outlineImageDataBlack,0,0);
let compareCanvas = createCanvas(300,150);
let compareCtx = compareCanvas.getContext('2d');
compareCtx.globalAlpha = 0.11;
compareCtx.drawImage(outlinecanvas, -53, -53);
compareCtx.globalAlpha = 1;
compareCtx.drawImage(relicanvas, -53, -53);
compareCtx.drawImage(await loadImage(itemEmbed.data.thumbnail.url), 150, 0);
fs.writeFileSync(rFilename, compareCanvas.toBuffer());
fs.writeFileSync(rFilename3, relicanvas.toBuffer());
await new Promise(res => gm(rFilename2).resize(128,128).write(rFilename2, res));
await new Promise(res => gm(rFilename3).resize(128,128).write(rFilename3, res));
await optimise(rFilename2);
await optimise(rFilename3);
return {
title: item.item.name,
description: '128x128 →',
image: {url: 'attachment://'+rFilename},
thumbnail: {url: 'attachment://'+rFilename3},
footer: {iconURL: 'attachment://'+rFilename2, text: '← outline'},
files: [rFilename, rFilename2, rFilename3],
color: itemEmbed.data.color,
};
}
} catch(e) {
console.error(e);
return {title: 'failed to generate image'};
}
},
'artpreview ': async (msg, arg) => {
try {
let preview = await commands.prefix['c~artpreview '](msg, arg);
let img = await loadImage(preview.files[0]);
let canvas = createCanvas(img.width/2,img.height);
let ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
fs.writeFileSync(preview.files[0], canvas.toBuffer());
return preview;
} catch(e) {
console.error(e);
return {title: 'failed to generate image'};
}
},
'cut~artpreview ': async (msg, arg) => {
try {
let preview = await commands.prefix['c~artpreview '](msg, arg);
delete preview.image;
fs.unlinkSync(preview.files[0]);
preview.files = preview.files.slice(1);
return preview;
} catch(e) {
console.error(e);
return {title: 'failed to generate image'};
}
},
'resize': async (msg, arg) => {
try {
let args = arg.split("=");
if (!args[0].includes('x'))
return {title: "resolution must be in the following format: 1280x720 (where 1280 is the width and 720 is the height)"}
let w = parseInt(args[0].split('x')[0]);
let h = parseInt(args[0].split('x')[1]);
if (w > 4000 || h > 4000 || w <= 0 || h <= 0 || isNaN(w) || isNaN(h))
return {title: "please make each dimension at least 1 and at most 4000"};
let n = args.length > 1 ? parseInt(args[1]) : 0;
let attachment = msg.attachments.at(n-1);
if (attachment == undefined)
return {title: 'format for attachments is att?n?name where n is the number of the attachment e.g. att?1?awsom'};
let origImg = await loadImage(attachment.url);
let canvas = createCanvas(origImg.width, origImg.height);
let ctx = canvas.getContext('2d')
ctx.drawImage(origImg, 0, 0);
let filename = `export${String(Math.random()).slice(2)}.png`;
let filename2 = filename.replace('export', 'resized');
fs.writeFileSync(filename, canvas.toBuffer());
await new Promise(res => gm(filename).resize(w,h,'!').write(filename2, res));
await optimise(filename);
await optimise(filename2);
return {
title: `${w}x${h} →`,
thumbnail: {url: 'attachment://'+filename2},
footer: {iconURL: 'attachment://'+filename, text: `← ${origImg.width}x${origImg.height}`},
files: [filename, filename2],
};
} catch (e) {
console.log(e);
return {title: "error resizing"};
}
},
'setnick ': async (msg, _, __, oa) => {
if (cfg.overriders.includes(msg.author.id) && msg.inGuild()) {
(await msg.guild.members.fetchMe()).setNickname(oa);
return {title: ':+1:'};
} else return {title: "oi!!"};
},
'setpresence ': async (msg, _, __, oa) => {
if (cfg.overriders.includes(msg.author.id)) {
fs.writeFileSync('presence.txt', Buffer.from(oa));
setActivity();
return {title: ':+1:'};
} else return {title: "this ain't for you"};
},
memes: () => ({
title: 'Meme generator',
description: `Some memes take more than one item, separate items with the "=" symbol.
The bot can also take users as arguments, to grab their profile pictures, with <meme user?[userId]> for example: <user?${bot.user.id} my beloved>
You can also use just "user?me" to specify yourself.
Add '?left' or '?right' after an item name to just take half of its image e.g. <strike?left my beloved>
__List of memes:__
<megamind no [item]>
<megamind textno [text]>
<friendship ended [bad item]=[good item]=[friender]>
<coolerdaniel [daniel]=[coolerdaniel]>
<5 dollar [footlong]>
<19 dollar [fortnite card]>
<distracted [gf]=[distraction]=[bf]>
<[item] my beloved>
<pet the [item]>