-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot-functions.js
892 lines (845 loc) · 37 KB
/
bot-functions.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
const request = require('request');
const { MessageEmbed, MessageActionRow, MessageButton, MessageSelectMenu } = require('discord.js');
const defs = require('./defines.json');
// General helper funcs
let formatter = new Intl.NumberFormat('en-US');
let getTimeDiff = function(t) {
let dtNow = new Date();
return Math.round((dtNow.getTime() - t * 1000) / 1000);
}
let unixTimestamp = function(t) {
let dt = new Date(t * 1000);
return dt.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
}
let getLastTime = function(t, max) {
let minutes = Math.floor(t / 60) % 60;
let hours = Math.floor(t / 60 / 60) % 24;
let days = Math.floor(t / 60 / 60 / 24);
if (days > 31) {
return false;
} else {
let lastTime = '';
let count = 0;
if (days > 0) {
lastTime += days + ' days ';
count++;
}
if (hours > 0 && count < max) {
lastTime += hours + ' hours ';
count++;
}
if (minutes > 0 && count < max) {
lastTime += minutes + ' minutes ';
}
if (lastTime == '') {
lastTime = 'Less than a minute ';
}
lastTime += 'ago';
return lastTime;
}
}
let printNumber = function(num) {
num = ' ' + num;
return '`' + num.substring(num.length - 4) + '`';
}
let shortenNumber = function(num) {
let options = [ "K", "M", "B" ];
let adjusted = Number(num);
let text = '';
for (let i = 0; i < options.length; i++) {
if (adjusted >= 1000000) {
adjusted = Math.floor(adjusted / 1000);
text = options[i];
}
else {
break;
}
}
return adjusted + text;
}
exports.getUserBalance = function(username, mode, reply) {
request('http://forum.toribash.com/tori_api.php?action=user_' + mode + '&username=' + escape(username), { json: true }, (err, res, body) => {
if (err || typeof body == 'undefined') {
reply({
embeds: [{
description: ':interrobang: **Error fetching data for ' + username + '.**\n...are you sure that\'s the proper username?',
}]
}, true);
return;
}
if (!isNaN(body.tc)) {
let descr = 'It ain\'t much, but it\'s honest work.';
if (body.tc < 1000) {
descr = 'Somebody please give this man a coin!';
}
if (body.tc > 50000) {
let forcePrices = [
{ name: 'Alpha', price: 300000 },
{ name: 'Aurora', price: 13500 },
{ name: 'Azurite', price: 60000 },
{ name: 'Demon', price: 240000 },
{ name: 'Gold', price: 12000 },
{ name: 'Knox', price: 450 },
{ name: 'Magma', price: 105000 },
{ name: 'Platinum', price: 42000 },
{ name: 'Superior', price: 250000 },
{ name: 'Vampire', price: 7500 },
{ name: 'Warrior', price: 90000 }
];
let selectedForce = forcePrices[Math.floor(Math.random() * forcePrices.length)];
descr = 'And can afford whole ' + Math.round(body.tc / selectedForce.price * 100) / 100 + ' ' + selectedForce.name + ' Forces with that!';
}
if (body.tc > 1000000) {
descr = 'Please report to authorities, they probably robbed ToriBank.';
}
if (body.username == 'ToriBot') {
descr = 'Though actually, it has limitless TC.';
}
reply({
embeds: [{
title: body.username + ' has ' + formatter.format(body.tc) + ' Toricredits!',
description: descr,
}]
});
}
else {
let descr = 'In terms of money, we have no money.';
if (body.st > 0 && body.st < 5) {
descr = '> Yes I got it from login rewards, so what???';
}
else if (body.st >= 5 && body.st < 15) {
descr = '...just waiting for the right ~~Steam~~ Toribash sale';
}
else if (body.st >= 15 && body.st < 50) {
descr = 'Someone likes hoarding.';
}
else if (body.st >= 50) {
descr = '***Someone loves hoarding.***\nPerhaps they forgot you can actually *spend* tokens?';
}
reply({
embeds: [{
title: body.username + ' has ' + formatter.format(body.st) + ' Shiai Tokens!',
description: descr
}]
});
}
});
}
exports.getUserInfo = function(username, reply) {
request('http://forum.toribash.com/tori_api.php?action=user_stats&username=' + escape(username), { json: true }, (err, res, body) => {
if (err || typeof body == 'undefined') {
reply({
embed: {
description: ':interrobang: **Error fetching data for ' + username + '.**\n...are you sure that\'s the proper username?',
}
}, true);
return;
}
let msgEmbed = new MessageEmbed()
.setTitle('Information about ' + body.username)
//.setDescription('[Profile on forums](https://forum.toribash.com/member.php?u=' + body.userid + ')')
.setThumbnail('https://cache.toribash.com/forum/customavatars/avatar' + body.userid + '_' + body.avatarrevision + '.gif');
if (body.belttitle) {
body.belt = body.belttitle + ' Belt';
}
if (typeof body.st == 'undefined') {
body.st = 0;
}
let msgFields = [
{ name: 'Belt', value: body.belt, inline: true },
{ name: 'Qi', value: formatter.format(body.qi), inline: true },
{ name: 'Toricredits', value: formatter.format(body.tc) + ' TC', inline: true },
{ name: 'Shiai Tokens', value: formatter.format(body.st) + ' ST', inline: true },
{ name: 'Join Date', value: unixTimestamp(body.joindate), inline: true }
];
let lastForumActivity = getTimeDiff(body.lastactivity);
if (lastForumActivity > 600) {
let lastOnline = getLastTime(lastForumActivity, 2);
if (!lastOnline) {
msgFields.push({ name: 'Last Forum Activity', value: unixTimestamp(body.lastactivity), inline: true });
} else {
msgFields.push({ name: 'Last Forum Activity', value: lastOnline, inline: true });
}
} else {
msgEmbed.setFooter('Online on forums', 'https://puu.sh/Gwhis/b5144b0056.png');
}
if (body.room) {
if (msgEmbed.footer) {
msgEmbed.footer.text += ' and in ' + body.room + ' room in game';
} else {
msgEmbed.setFooter('Online in ' + body.room + ' room in game', 'https://puu.sh/Gwhis/b5144b0056.png');
}
} else if (body.lastingame > 0) {
let lastIngameActivity = getTimeDiff(body.lastingame);
let lastOnline = getLastTime(lastIngameActivity, 2);
if (!lastOnline) {
msgFields.push({ name: 'Last Ingame Activity', value: unixTimestamp(body.lastingame), inline: true });
} else {
msgFields.push({ name: 'Last Ingame Activity', value: lastOnline, inline: true });
}
}
if (body.clanid > 0) {
msgFields.push({ name: 'Clan', value: '[' + body.clantag + ' ' + body.clanname + '](https://forum.toribash.com/clan.php?clanid=' + body.clanid + ')' });
}
msgFields.forEach(function(field) {
msgEmbed.addField(field.name, field.value, field.inline);
});
if (body.isBanned) {
msgEmbed.setFooter('This user is currently banned. Naughty!', 'https://puu.sh/GwhoY/e84b9ed9aa.png');
}
if (body.isAdmin || body.isMS || body.isES || body.isHS || body.isCS) {
msgEmbed.setFooter('This user is a staff member', 'https://cache.toribash.com/forum/images/banana/bananalama.gif');
}
if (body.isHS) {
msgEmbed.setColor([150, 150, 150]);
}
if (body.isMS) {
msgEmbed.setColor([0, 128, 0]);
}
if (body.isCS) {
msgEmbed.setColor([0, 0, 0]);
}
if (body.isES) {
msgEmbed.setColor([105, 0, 105]);
}
if (body.isSmod) {
msgEmbed.setColor([0, 0, 255]);
}
if (body.isAdmin) {
msgEmbed.setColor([255, 0, 0]);
}
reply({
embeds: [ msgEmbed ],
components: [ new MessageActionRow().addComponents(new MessageButton().setLabel("Toribash profile").setStyle('LINK').setURL('https://forum.toribash.com/member.php?u=' + body.userid)) ]
})
});
}
exports.getUserInventoryInfo = function(username, reply) {
request('http://forum.toribash.com/tori_api.php?action=user_inventory&mode=0&username=' + escape(username), { json: true }, (err, res, body) => {
if (err || typeof body != 'object') {
reply({
embeds: [{
title: 'Error fetching data for ' + username + '.',
description: '...are you sure that\'s the proper username?',
thumbnail: {
url: 'https://discordapp.com/assets/0756351ac9eb496a210cd591acecf1d0.svg'
}
}]
}, null, null, true);
return;
}
let inventoryItems = [];
for (let i = 0; i < body.itemstotal; i++) {
let index = inventoryItems.findIndex(function(item) { return (item.itemid == body.inventory[i].itemid && item.itemid != 1458) });
if (index !== -1) {
// clean data that we already stored
delete body.inventory[i]['itemid'];
delete body.inventory[i]['itemname'];
delete body.inventory[i]['description'];
delete body.inventory[i]['image'];
inventoryItems[index].items.push(body.inventory[i]);
inventoryItems[index].count += 1;
} else {
let itemDescription = body.inventory[i].description == null ? '' : body.inventory[i].description;
// All cleanup is now done in API response, no extra checks required
//itemDescription = itemDescription.replace(/<\/?br\/?>/gm, '\n');
//itemDescription = itemDescription.replace(/<(?:.|\n)*?>/gm, '');
let itemInfo = {
itemid: body.inventory[i].itemid,
itemname: body.inventory[i].itemname,
description: itemDescription,
image: body.inventory[i].image,
items: [],
count: 1
}
if (itemInfo.itemid == 1458) {
itemInfo.setcontents = [];
itemInfo.count = 0;
}
// clean some data not to store duplicates of it
delete body.inventory[i]['itemid'];
delete body.inventory[i]['itemname'];
delete body.inventory[i]['description'];
delete body.inventory[i]['image'];
itemInfo.items.push(body.inventory[i]);
if (body.inventory[i].setid == 0) {
inventoryItems.push(itemInfo);
} else {
let setid = inventoryItems.findIndex(function(item) { return item.itemid == 1458 && item.items[0].inventid == body.inventory[i].setid });
if (setid !== -1) {
inventoryItems[setid].setcontents.push(itemInfo);
inventoryItems[setid].count += 1;
}
}
}
}
if (typeof body.inventory != 'undefined') {
inventoryItems['username'] = body.username;
inventoryItems['userid'] = body.userid;
inventoryItems['itemstotal'] = inventoryItems.length;
inventoryItems['active'] = [];
inventoryItems['deactive'] = [];
inventoryItems['market'] = [];
for (let i = 0; i < inventoryItems.itemstotal; i++) {
let sale = false;
let active = false;
let deactive = false;
for (j = 0; j < inventoryItems[i].items.length; j++) {
let item = inventoryItems[i].items[j];
if (item.sale == 1) {
let idx = inventoryItems.market.length - 1;
if (!sale) {
inventoryItems.market.push(Object.assign({}, inventoryItems[i]));
inventoryItems.market[++idx].items = [];
if (!inventoryItems[i].setcontents) {
inventoryItems.market[idx].count = 0;
}
sale = true;
}
inventoryItems.market[idx].items.push(item);
if (!inventoryItems[i].setcontents) {
inventoryItems.market[idx].count++;
}
}
else if (item.active == 1) {
let idx = inventoryItems.active.length - 1;
if (!active) {
inventoryItems.active.push(Object.assign({}, inventoryItems[i]));
inventoryItems.active[++idx].items = [];
if (!inventoryItems[i].setcontents) {
inventoryItems.active[idx].count = 0;
}
active = true;
}
inventoryItems.active[idx].items.push(item);
if (!inventoryItems[i].setcontents) {
inventoryItems.active[idx].count++;
}
}
else {
let idx = inventoryItems.deactive.length - 1;
if (!deactive) {
inventoryItems.deactive.push(Object.assign({}, inventoryItems[i]));
inventoryItems.deactive[++idx].items = [];
if (!inventoryItems[i].setcontents) {
inventoryItems.deactive[idx].count = 0;
}
deactive = true;
}
inventoryItems.deactive[idx].items.push(item);
if (!inventoryItems[i].setcontents) {
inventoryItems.deactive[idx].count++;
}
}
}
}
inventoryItems.active.username = inventoryItems.deactive.username = inventoryItems.market.username = inventoryItems.username;
inventoryItems.active.userid = inventoryItems.deactive.userid = inventoryItems.market.userid = inventoryItems.userid;
inventoryItems.active.itemstotal = inventoryItems.active.length;
inventoryItems.deactive.itemstotal = inventoryItems.deactive.length;
inventoryItems.market.itemstotal = inventoryItems.market.length;
}
let pages = Math.ceil(inventoryItems.length / defs.INV_ITEMS_PER_PAGE);
let invCmdDetails = '`' + defs.COMMAND_PREFIX + 'invpage [page]` - view inventory page';
invCmdDetails += '\n`' + defs.COMMAND_PREFIX + 'invall` - view all inventory items at once';
if (pages == 0) {
reply({
embeds: [{
title: body.username + ' has no items!',
description: 'What, not even a Chronos Grip???'
}]
});
/*} else if (pages == 1) {
reply({
embeds: [{
title: body.username + ' has ' + body.itemstotal + ' items!',
description: 'I\'ve DMed you with more details, yay!'
}]
}, this.printInventoryPage(inventoryItems, 0, 1), inventoryItems);*/
} else {
let dmActions = new MessageActionRow().addComponents([
new MessageButton().setCustomId('inventory-all-' + body.userid + '-1').setLabel('All Items').setStyle('PRIMARY'),
new MessageButton().setCustomId('inventory-active-' + body.userid + '-1').setLabel('Active').setStyle('SECONDARY'),
new MessageButton().setCustomId('inventory-deactive-' + body.userid + '-1').setLabel('Deactive').setStyle('SECONDARY'),
new MessageButton().setCustomId('inventory-market-' + body.userid + '-1').setLabel('Market').setStyle('SUCCESS')
]);
reply({
embeds: [{
title: body.username + ' has ' + body.itemstotal + ' items!',
description: 'I\'ve DMed you with more details, yay!'
}]
},
{
embeds: [{
title: body.username + '\'s inventory information',
description: '[View inventory on forums](https://forum.toribash.com/tori_inventory.php?userid=' + body.userid + '&sid=0)',
fields: [
{ name: 'Total Items', value: body.itemstotal.toString(), inline: true },
{ name: 'Pages', value: pages.toString(), inline: true }
],
footer: {
text: 'Inventory data will be cached for 5 minutes'
}
}],
components: [ dmActions ]
}, inventoryItems);
}
});
}
let printInventoryStackedItems = function(invinfo, invid, page, mode) {
if (invinfo[invid].items.length == 1) {
console.log('Error: printInventoryStackedItems attempt on a single item');
return 'Error';
}
page = isNaN(page) ? 1 : Math.max(1, page);
let messageComponents = [];
let itemLookup = invinfo[invid].items;
let items = [];
let pagesTotal = Math.ceil(invinfo[invid].items.length / defs.INV_ITEMS_PER_PAGE);
for (let i = (page - 1) * defs.INV_ITEMS_PER_PAGE; i < page * defs.INV_ITEMS_PER_PAGE && i < itemLookup.length; i++) {
let item = itemLookup[i];
item.stackid = i + 1;
items.push(item);
}
let inventoryPageInfo = '';
let itemOptions = [];
items.forEach(function(item) {
inventoryPageInfo += printNumber(item.stackid) + ': ' + invinfo[invid].itemname;
if (typeof item.flamename !== 'undefined') {
inventoryPageInfo += ' (' + item.flamename + ')';
}
inventoryPageInfo += '\n';
itemOptions.push({ label: item.stackid + ': ' + invinfo[invid].itemname, value: (invid + 1) + '-' + item.stackid });
});
messageComponents.push(new MessageActionRow().addComponents(
new MessageSelectMenu().setCustomId('inventory-stackinfo-' + invinfo.userid + '-' + mode)
.setPlaceholder('Select item to show details').addOptions(itemOptions)
));
if (pagesTotal > 1) {
spawnPaginationControls(messageComponents, page, pagesTotal, invinfo, mode + ":expand" + (invid + 1));
}
return {
embeds: [{
title: invinfo.username + '\'s ' + invinfo[invid].itemname + 's' + (itemLookup.length > defs.INV_ITEMS_PER_PAGE ? (' page ( ' + page + ' of ' + pagesTotal + ')') : ''),
description: inventoryPageInfo
}],
components: messageComponents
}
}
let printInventorySetItems = function(invinfo, invid, page, mode) {
if (invinfo[invid].setcontents.length < 1) {
console.log("Error: printInventorySetItems attempt to show empty set");
return 'That set doesn\'t have any items inside! There is nothing to show there!!! AAAAAAA!!!!!!!';
}
page = isNaN(page) ? 1 : Math.max(1, page);
let messageComponents = [];
let itemLookup = invinfo[invid].setcontents;
let items = [];
let pagesTotal = Math.ceil(itemLookup.length / defs.INV_ITEMS_PER_PAGE);
for (let i = (page - 1) * defs.INV_ITEMS_PER_PAGE; i < page * defs.INV_ITEMS_PER_PAGE && i < itemLookup.length; i++) {
let item = itemLookup[i];
item.stackid = i + 1;
items.push(item);
}
let inventoryPageInfo = '';
let itemOptions = [];
items.forEach(function(item) {
inventoryPageInfo += printNumber(item.stackid) + ': ' + item.itemname;
if (typeof item.flamename !== 'undefined') {
inventoryPageInfo += ' (' + item.flamename + ')';
}
inventoryPageInfo += '\n';
itemOptions.push({ label: item.stackid + ': ' + item.itemname, value: invinfo[invid].cacheid + '-' + item.stackid });
});
messageComponents.push(new MessageActionRow().addComponents(
new MessageSelectMenu().setCustomId('inventory-stackinfo-' + invinfo.userid + '-' + mode)
.setPlaceholder('Select item to show details').addOptions(itemOptions)
));
if (pagesTotal > 1) {
spawnPaginationControls(messageComponents, page, pagesTotal, invinfo, mode + ":expand" + (invid + 1));
}
return {
embeds: [{
title: 'Items inside ' + invinfo.username + '\'s ' + invinfo[invid].items[0].setname + ' set' + (itemLookup.length > defs.INV_ITEMS_PER_PAGE ? (' page ( ' + page + ' of ' + Math.ceil(itemLookup.length / defs.INV_ITEMS_PER_PAGE) + ')') : ''),
description: inventoryPageInfo
}],
components: messageComponents
}
}
exports.printInventoryExpandedPage = function(invinfo, stackid, page, mode) {
if (isNaN(stackid)) {
console.log("Error: printInventoryExpandedPage stackid is undefined");
return 'You\'re trying to expand what exactly? I need a number!';
}
let invid = stackid - 1;
if (invid < 0) {
console.log("Error: printInventoryExpandedPage invid is not a correct number");
return 'That\'s not a correct item list number!\nHere are proper ones: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,... Should I continue?';
}
if (invinfo[invid].itemid == '1458') {
return printInventorySetItems(invinfo, invid, page, mode);
} else {
return printInventoryStackedItems(invinfo, invid, page, mode);
}
}
let spawnPaginationControls = function(messageComponents, page, pagesTotal, invinfo, mode) {
let pagesOptions = [];
let pageStart = Math.max(1, page - 12);
let pageEnd = Math.min(pagesTotal, pageStart + 24);
pageStart = Math.max(1, Math.min(pageStart, pageEnd - 24));
for (let i = pageStart; i <= pageEnd; i++) {
pagesOptions.push({ label: 'Page ' + i, value: i.toString(), default: i == page });
}
if (pagesOptions.length > 1) {
messageComponents.push(new MessageActionRow().addComponents(
new MessageSelectMenu().setCustomId('inventory-' + mode + '-' + invinfo.userid + '-pageselector')
.setPlaceholder('Select inventory page').addOptions(pagesOptions)
));
}
if (pagesTotal > 1) {
let pageButtons = new MessageActionRow();
pageButtons.addComponents(
new MessageButton()
.setCustomId('inventory-' + mode + '-' + invinfo.userid + '-1-')
.setLabel("First Page").setStyle('SECONDARY').setDisabled(page == 1),
new MessageButton()
.setCustomId('inventory-' + mode + '-' + invinfo.userid + '-' + (page - 1))
.setLabel("Previous Page").setStyle('PRIMARY').setDisabled(page <= 1),
new MessageButton()
.setCustomId('inventory-' + mode + '-' + invinfo.userid + '-' + (page + 1))
.setLabel("Next Page").setStyle('PRIMARY').setDisabled(page >= pagesTotal),
new MessageButton()
.setCustomId('inventory-' + mode + '-' + invinfo.userid + '-' + pagesTotal + '-')
.setLabel("Last Page").setStyle('SECONDARY').setDisabled(page == pagesTotal)
);
messageComponents.push(pageButtons);
}
}
exports.printInventoryPage = function(invinfo, mode, page) {
page = isNaN(page) ? 1 : page;
let pagesTotal = Math.ceil(invinfo.itemstotal / defs.INV_ITEMS_PER_PAGE);
if (pagesTotal == 0) {
return "This part of " + invinfo.username + '\'s inventory is empty!';
}
if (page > pagesTotal) {
console.log("error: PrintInventoryPage page exceeds totalpages");
page = pagesTotal;
//return invinfo.username + '\'s inventory doesn\'t have **that** many pages!';
}
if (page < 1) {
console.log("error: PrintInventoryPage page is less than 1");
page = 1;
//return 'are you trying to break me? page numbers can only be positive numbers, baka!';
}
let items = [];
for (let i = (page - 1) * defs.INV_ITEMS_PER_PAGE; i < page * defs.INV_ITEMS_PER_PAGE && i < invinfo.itemstotal; i++) {
let item = invinfo[i];
item.cacheid = i + 1;
items.push(item);
}
let itemsEmbed = new MessageEmbed();
itemsEmbed.setTitle(invinfo.username + '\'s inventory (page ' + page + ' of ' + pagesTotal + ')');
itemsEmbed.description = '';
let messageComponents = [];
let itemOptions = [];
items.forEach(function(item) {
let itemName = item.itemname;
let itemText = '';
if (item.itemid == 1458) {
itemName += ': ' + item.items[0].setname;
itemName += ' (' + (item.setcontents.length > 0 ? (item.setcontents.length + ' items inside') : 'Empty') + ')';
itemText = itemName;
} else {
itemText = itemName + (item.items.length > 1 ? ' **[x' + item.items.length + ']**' : '');
itemName += (item.items.length > 1) ? ' [x' + item.items.length + ']' : '';
}
itemsEmbed.description += printNumber(item.cacheid) + ': ' + itemText + '\n';
itemOptions.push({ label: item.cacheid + ': ' + itemName, value: item.cacheid + '-' + (item.count > 1 ? 'expand' : 'info') });
});
messageComponents.push(new MessageActionRow().addComponents(
new MessageSelectMenu().setCustomId('inventory-iteminfo-' + invinfo.userid + '-' + mode)
.setPlaceholder('Select item to show details').addOptions(itemOptions)
));
spawnPaginationControls(messageComponents, page, pagesTotal, invinfo, mode);
return {
embeds: [ itemsEmbed ],
components: messageComponents
}
}
let printInventorySingleItemInfo = function(item, stackid) {
let msgEmbed = new MessageEmbed();
let itemName = item.itemname;
if (item.itemid == 1458) {
itemName += ': ' + item.items[0].setname;
}
msgEmbed.addField('Item Name', itemName);
if (item.description != '') {
msgEmbed.addField('Item Description', item.description);
}
if (typeof item.image !== 'undefined' && item.image != '') {
msgEmbed.setThumbnail('https://cache.toribash.com/forum/torishop/images/items/' + item.image);
}
msgEmbed.addField('Games played', item.items[stackid].gamesplayed, true);
if (typeof item.items[stackid].flameid !== 'undefined') {
msgEmbed.addField('Flame Name', item.items[stackid].flamename, true);
msgEmbed.addField('Flame ID', item.items[stackid].flameid, true);
msgEmbed.addField('Flame For', item.items[stackid].bodypartname, true);
}
if (typeof item.items[stackid].objitem !== 'undefined') {
let extra = [];
if (typeof item.items[stackid].retexturable !== 'undefined') {
extra.push('Can be retextured');
}
if (typeof item.items[stackid].level !== 'undefined') {
extra.push('Can be upgraded');
msgEmbed.addField('Item Level', item.items[stackid].level, true);
}
if (item.items[stackid].bodypartname) {
msgEmbed.addField('Applied to', item.items[stackid].bodypartname, true);
}
if (extra.length > 0) {
msgEmbed.addField('Extra features', extra.toString(), true);
}
}
if (item.itemid == 1458) {
msgEmbed.addField('Items inside', item.setcontents.length == 0 ? 'Set is empty' : item.setcontents.length, true);
}
msgEmbed.addField('Last used', item.items[stackid].lastused, true);
return {
embeds: [ msgEmbed ]
}
}
exports.printInventoryItemInfo = function(invinfo, invid, stackid) {
let stackSet = !isNaN(stackid);
stackid = stackSet ? Math.max(1, stackid) : 1;
if (invid < 1) {
if (invid == 0) {
return 'Software engineer much? Item numbers start from 1!';
}
return 'How can one have #' + invid + ' item, huh?';
}
if (invid > invinfo.itemstotal) {
return invinfo.username + ' doesn\'t have that many items! He\'d probably be happy to do though.';
}
let item = invinfo[invid - 1];
stackid = stackid - 1;
if ((stackid >= item.items.length && stackid >= item.count) || stackid < 0) {
console.log('Stack ID has incorrect value (' + stackid + '), resetting to 0 - max ' + Math.max(item.items.length, item.count));
stackid = 0;
}
if (item.itemid == 1458 && stackSet) {
return printInventorySingleItemInfo(item.setcontents[stackid], 0);
}
return printInventorySingleItemInfo(item, stackid);
}
exports.inventoryUserNotCachedError = function() {
return {
embeds: [{
title: 'Sorry, no inventory to show for you!',
description: 'Load player\'s inventory using `/inventory [username]` command to be able to view their items.'
}]
}
}
exports.getRanking = function(type, options, reply) {
let optionsStr = '';
for (var prop in options) {
if (!options.hasOwnProperty(prop) || typeof options[prop] == 'undefined' || options[prop] == null) continue;
optionsStr += "&" + prop + "=" + options[prop];
}
request('http://forum.toribash.com/tori_api.php?action=ranking&type=' + type + optionsStr, { json: true }, (err, res, body) => {
if (err || typeof body == 'undefined' || (body.toplist.length == 0 && typeof options.mod == 'undefined')) {
reply({
embeds: [{
description: ':interrobang: **Error getting ' + type + ' ranking.**'
}]
}, true);
return;
}
if (typeof options.mod != 'undefined' && options.mod != null) {
if (options.mod.substring(options.mod.length - 4) == '.tbm') {
options.mod = options.mod.substring(0, options.mod.length - 4);
}
}
if (body.toplist.length == 0) {
reply({
embeds: [{
description: ':interrobang: **' + options.mod + ' has no ranking data yet!**'
}]
}, true);
return;
}
let typeString = type;
let resultsLegend = 'Result';
let seasonPeriodString = (type == 'elo' && options.mod != null) ? '(all time)' : '(this season)';
switch (type) {
case 'elo':
typeString = 'rank';
resultsLegend = 'Elo';
break;
case 'tc':
typeString = 'TC earned';
resultsLegend = 'TC';
break;
case 'games':
typeString = 'games played';
resultsLegend = 'Games';
break;
case 'score':
typeString = 'damage dealt to opponents';
resultsLegend = 'Damage';
break;
}
let msgEmbed = new MessageEmbed();
msgEmbed.setTitle("Top " + ((typeof options.mod == 'undefined' || options.mod == null) ? '' : (options.mod + ' ')) + "players by " + typeString + " " + (options.period == 7 ? "(past 7 days)" : seasonPeriodString));
let embedRanks = [ '#' ];
let embedMaxRankLength = 1;
let embedUsers = [ 'User' ];
let embedMaxUserLength = 4;
let embedResults = [ resultsLegend ];
let embedMaxResultLength = 6;
for (var j = 0; j < 2; j++) {
let periods = [];
for (var i = 0; i < body.toplist.length; i++) {
if (typeof options.period !== 'undefined' && body.toplist[i].period != options.period) {
if (periods.indexOf(body.toplist[i].period) === -1) {
periods.push(body.toplist[i].period);
}
continue;
}
embedRanks.push(String(body.toplist[i].rank));
embedMaxRankLength = Math.max(embedMaxRankLength, String(body.toplist[i].rank).length);
embedUsers.push(String(body.toplist[i].username));
embedMaxUserLength = Math.max(embedMaxUserLength, String(body.toplist[i].username).length);
let resultValue = shortenNumber(body.toplist[i].result);
if (type == 'elo') {
resultValue = Number(body.toplist[i].result).toFixed(2);
}
else if (resultValue == body.toplist[i].result) {
resultValue = formatter.format(resultValue);
}
else {
resultValue = formatter.format(resultValue.substring(0, resultValue.length - 1)) + resultValue.substring(resultValue.length - 1);
}
embedResults.push(resultValue);
embedMaxResultLength = Math.max(embedMaxResultLength, resultValue.length);
}
if (embedRanks.length > 1) break;
options.period = periods.slice(-1)[0];
}
let toplistString = '';
for (var i = 0; i < embedRanks.length; i++) {
toplistString += String(" ").repeat(embedMaxRankLength - embedRanks[i].length + 1) + embedRanks[i] + " | ";
toplistString += embedUsers[i] + String(" ").repeat(embedMaxUserLength - embedUsers[i].length) + " | ";
toplistString += String(" ").repeat(embedMaxResultLength - embedResults[i].length) + embedResults[i];
if (i == 0) {
toplistString += "\n" + String("=").repeat(toplistString.length + 1) + "\n";
}
else {
toplistString += "\n";
}
}
msgEmbed.setDescription("```\n" + toplistString + "\n```");
reply({ embeds: [ msgEmbed ] });
});
}
exports.getClan = function(nametag, reply) {
request('http://forum.toribash.com/tori_api.php?action=clan_info&clanname=' + escape(nametag) + "&clantag=" + escape(nametag), { json: true }, (err, res, body) => {
if (err || typeof body == 'undefined') {
reply({
embeds: [{
description: ':interrobang: **Specified clan not found.**\n..please make sure the clan you\'re looking for actually exists?'
}]
}, true);
return;
}
let clan = body.clan;
let msgEmbed = new MessageEmbed()
.setTitle(clan.tag + " " + clan.name)
.setFooter((clan.official == 1 ? (clan.legend == 1 ? "Legendary" : "Official") : "Unofficial") + " since " + clan.since + (clan.rank > 0 ? " :: Rank " + clan.rank : "") + (clan.level > 0 ? " :: Level " + clan.level : ""))
.setThumbnail(clan.logo);
let roster = body.roster;
if (roster.leaders.length > 0) {
let leaderNames = '';
for (let i = 0; i < roster.leaders.length; i++) {
leaderNames += "[" + roster.leaders[i].username + "](https://forum.toribash.com/member.php?u=" + roster.leaders[i].userid + ")\n";
}
msgEmbed.addField('Leaders', leaderNames, false);
}
console.log("Clan member count: " + roster.memberCount);
if (roster.memberCount > roster.leaders.length) {
let i = 1;
while (i < 2 || roster.members[i]) {
if (roster.members[i]) {
let memberNames = '';
let rank = roster.members[i];
for (let j = 0; j < rank.members.length; j++) {
//memberNames += "[" + rank.members[j].username + "](https://forum.toribash.com/member.php?u=" + rank.members[j].userid + ")\n";
memberNames += rank.members[j].username + "\n";
}
msgEmbed.addField(rank.rank + (rank.trial == 1 ? " (trial rank)" : ''), memberNames, true);
}
i++;
}
if (roster.members[0]) {
let memberNames = '';
let rank = roster.members[0];
for (let j = 0; j < rank.members.length; j++) {
//memberNames += "[" + rank.members[j].username + "](https://forum.toribash.com/member.php?u=" + rank.members[j].userid + ")\n";
memberNames += rank.members[j].username + "\n";
}
msgEmbed.addField("Unranked", memberNames, true);
}
}
let msgComponents = new MessageActionRow().addComponents(
new MessageButton().setLabel("Clan page").setStyle('LINK').setURL("https://forum.toribash.com/clan.php?clanid=" + clan.id)
);
if (body.clan.forumid > 0) {
msgComponents.addComponents(new MessageButton().setLabel("Board on forums").setStyle('LINK').setURL("https://forum.toribash.com/forumdisplay.php?f=" + clan.forumid));
}
else if (body.clan.postid > 0) {
msgComponents.addComponents(new MessageButton().setLabel("Thread on forums").setStyle('LINK').setURL("https://forum.toribash.com/showthread.php?p=" + clan.postid));
}
reply({
embeds: [ msgEmbed ],
components: [ msgComponents ]
});
});
}
let clanLeagueMemes = [
[ 'https://i.imgur.com/Tolb3T4.jpg', 'https://i.imgur.com/dJy92Bz.jpg', 'https://imgur.com/Bt4WHjP.gif', 'https://i.imgur.com/9z2jJIG.gif', 'https://i.imgur.com/7B8Eirm.jpg', 'https://youtu.be/IQVQWAb2ydA', 'https://youtu.be/kjww-mJGrFM', 'https://youtu.be/JrI_rdSW_-U', 'https://youtu.be/zRGYFJZDvSg', 'https://i.gyazo.com/ecf2cd291691a3182cc96330394de9db.png', 'https://i.imgur.com/NnTMsmq.jpg', 'https://i.imgur.com/J9o3JSs.jpg', 'https://i.imgur.com/E64aOsJ.jpg', 'https://i.imgur.com/hTiWMQM.png', 'https://cdn.discordapp.com/attachments/417438984357281792/610290465907933185/output-onlinejpgtools1.jpg', 'https://i.imgur.com/E64aOsJ.jpg', 'https://i.imgur.com/6vMGOft.jpeg' ],
[ 'https://i.imgflip.com/47wnzo.jpg', 'https://i.imgur.com/T9tcxP3.jpg', 'https://i.imgur.com/0VR1tKX.jpg', 'https://i.imgflip.com/47y7c1.jpg', 'https://i.imgflip.com/47y7mb.jpg', 'https://i.imgur.com/luaM2cr.jpg', 'https://i.imgur.com/A6uUjRx.jpg', 'https://i.imgur.com/iMy5KK0.jpg', 'https://youtu.be/wT1NkxSDaGY', 'https://youtu.be/91I1D9vz_ZU', 'https://cdn.discordapp.com/attachments/589594631012876291/731649806036107304/Untitled283_20200711201153.png', 'https://i.imgur.com/llnxY1K.jpg', 'https://i.imgflip.com/480xng.jpg', 'https://youtu.be/HKLDSALBKU4', 'https://i.imgur.com/GKcUHdg.png', 'https://i.imgur.com/XNTlV9o.png', 'https://cdn.discordapp.com/attachments/632244063348981761/736206142950080612/wFIgF7XQKg54AAAAABJRU5ErkJggg.png', 'https://i.imgur.com/cfZq7nS.png', 'https://i.imgur.com/Ez0YXWc.png', 'https://i.imgflip.com/49im4u.jpg', 'https://youtu.be/Q_D9mizAgwQ', 'https://i.imgur.com/g9vfn6g.png', 'https://i.imgur.com/B4nI014.png', 'https://youtu.be/vIoa3M35dmQ', 'https://www.linkpicture.com/q/49p7uu.jpg', 'https://media.discordapp.net/attachments/732134050457845810/738431162237714523/jF5lfStROkcOrAAAAAElFTkSuQmCC.png', 'https://youtu.be/xOvsLxTabJ0', 'https://i.imgur.com/0tulkR1.png', 'https://youtu.be/SOaDoKiyYYQ', 'https://youtu.be/R6xNlrIWnuE', 'https://media.discordapp.net/attachments/738816845620052051/738859852960497724/unknown.png', 'https://media.discordapp.net/attachments/738816845620052051/738861074413125753/4a1rmt.png?width=600&height=671', 'https://i.imgur.com/WFZXrfv.png', 'https://i.imgur.com/xiqGPYS.png', 'https://i.imgur.com/p86ZpXJ.gif', 'https://i.imgur.com/Dy4Dzio.png', 'https://youtu.be/pMqggOKawC0', 'https://youtu.be/LZKJDOn_sF0', 'https://i.imgur.com/1UT2Atm.jpg', 'https://media.discordapp.net/attachments/704329881160253492/751520867325968646/Dxod25rsckd0AAAAAElFTkSuQmCC.png', 'https://media.discordapp.net/attachments/704329881160253492/751519275319296010/wfVK7GLC87mZgAAAABJRU5ErkJggg.png', 'https://i.imgur.com/fmgDQjI.png', 'https://i.imgur.com/mArJihi.png', 'https://i.imgur.com/CutpVte.png', 'https://i.imgur.com/Dx00Y9j.jpg', 'https://i.imgur.com/VOvDWbX.png', 'https://cdn.discordapp.com/attachments/731474987420090368/765431597905739786/Ninja_Turtles_and_Splinter_13102020112952.jpg', 'https://i.imgur.com/DIdheIw.jpg', 'https://i.imgur.com/AWO5gE0.jpg', 'https://i.imgur.com/6kf4Caa.jpg', 'https://i.imgur.com/m4IU32y.png', 'https://i.imgur.com/3u9Qms2.png', 'https://i.imgur.com/ZG7bwgV.png', 'https://i.imgur.com/yRoDfRE.png', 'https://cdn.discordapp.com/attachments/589594631012876291/735674694090358854/Untitled292_20200722224818.png', 'https://media.discordapp.net/attachments/632244063348981761/735906405420236850/AXrVloOrMXAAAAAElFTkSuQmCC.png', 'https://cdn.discordapp.com/attachments/589594631012876291/735920378823573625/20200723_150424.png' ],
[ 'https://i.imgur.com/ABBbhwr.png', 'https://i.imgur.com/cwvXUYN.jpg', 'https://forum.toribash.com/attachment.php?attachmentid=623532&stc=1&d', 'https://i.imgur.com/uERU2vd.jpg', 'https://i.imgur.com/vgy9uU5.png', 'https://media.discordapp.net/attachments/834076847998238771/834088191728287755/j82i1Y9avmIAAAAASUVORK5CYII.png', 'http://i.imgur.com/mvNbUQ5.jpg', 'https://i.imgflip.com/56ict8.jpg', 'https://i.imgur.com/nr1m6dz.png', 'https://i.imgur.com/cbZF8Ck.jpg', 'https://i.imgur.com/baVzsLn.jpg', 'https://i.imgur.com/i1SbOQm.png', 'http://i.imgur.com/dGTccJG.jpg', 'https://youtu.be/kesAdiHZ2Og', 'https://i.imgur.com/SCQx8ku.png' ]
];
exports.getRandomClanLeagueMeme = function() {
let years = clanLeagueMemes.length;
let memes = clanLeagueMemes[Math.floor(Math.random() * years)];
return memes[Math.floor(Math.random() * memes.length)];
}
exports.printHelp = function() {
let msgEmbed = new MessageEmbed();
msgEmbed.setTitle('List of available commands');
msgEmbed.setDescription('Command arguments are listed as [arg]. Optional arguments have ? prefix.');
let commandsGeneral = '`/tc [username]` - show player\'s Toricredits balance\n';
commandsGeneral += '`/st [username]` - show player\'s Shiai Tokens balance\n';
commandsGeneral += '`/info [username]` - show general info about a player\n';
msgEmbed.addField('General info commands', commandsGeneral);
let commandsRanking = '`/ranking [?modname]` - display top players by their elo\n';
commandsRanking += '`/toplist [type] [period]` - display best players by a given criteria\n';
msgEmbed.addField('Ranking commands', commandsRanking);
let commandsInventory = '`/inventory [username]` - load player\'s inventory for viewing\n';
commandsInventory += '*Further inventory actions are available via control buttons*\n';
msgEmbed.addField('Inventory commands (will be DMed)', commandsInventory);
//msgEmbed.setFooter('Commands support shortened or longer versions. For example, ' + defs.COMMAND_PREFIX + 'inventorypage, ' + defs.COMMAND_PREFIX + 'invpage and ' + defs.COMMAND_PREFIX + 'invpg are same.');
let inviteAction = new MessageActionRow().addComponents(
new MessageButton().setLabel('Add ToriBot to your server').setStyle('LINK')
.setURL('https://discordapp.com/api/oauth2/authorize?client_id=539004489433219083&permissions=322624&scope=bo://discord.com/api/oauth2/authorize?client_id=539004489433219083&permissions=34360043584&scope=bot%20applications.commands')
);
return {
embeds: [ msgEmbed ],
components: [ inviteAction ]
}
}