-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwerewolves.js
1308 lines (1240 loc) · 61.8 KB
/
werewolves.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
/* Discord */
const { Client, Intents, Options, GatewayIntentBits, ChannelType, MessageType, OverwriteType, PermissionsBitField } = require('discord.js');
global.client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildWebhooks, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.DirectMessages, GatewayIntentBits.DirectMessageReactions],
sweepers: {
...Options.DefaultSweeperSettings,
messages: {
interval: 86400, // Every 24 hours...
lifetime: 86400, // Remove messages older than 24 hours.
}
}
});
require("./discord.js")();
/**
Libraries
**/
const { exec } = require('node:child_process')
config = require("./config.json");
/* V1 Modules */
require("./stats.js")();
require("./confirm.js")();
require("./players.js")();
require("./ccs.js")();
require("./whispers.js")();
require("./theme.js")();
require("./temp.js")();
// V2 Modules
require("./paths.js")();
require("./roles/roles.js")();
require("./game/game.js")();
require("./utility/utility.js")();
require("./abilities/abilities.js")();
require("./attributes/attributes.js")();
require("./players/players.js")();
var botLoaded = false;
/* Setup */
client.on("ready", async () => {
setMainGuild();
sqlSetup();
getStats();
createActionQueueChecker();
setTimeout(function() {
getIDs();
cacheRoleInfo();
cacheLocations();
cachePolls();
cacheTeams();
getSCCats();
getCCs();
getPRoles();
getCCCats();
getPublicCat();
cacheIconLUT();
cacheColorsLUT();
cacheActiveCustomAttributes();
cacheDR();
cachePollMessages();
cachePacks();
global.client.guilds.fetch(stats.log_guild).then(guild => {
guild.members.fetch().then((members) => {
//members.forEach(el => console.log(el.user.id));
//console.log(members.map(el => el.user.id));
});
});
log("Bot > Caching completed, Bot is ready!")
}, 3000);
//logDMs();
setTimeout(function() {
botLoaded = true;
}, 4000);
});
async function forceReload(channel) {
try { sqlSetup(); channel.send("✅ Setup DB connection."); } catch (err) { logO(err); channel.send("⛔ Failed to setup DB connection."); } await sleep(1000);
try { getStats(); channel.send("✅ Loaded stats."); } catch (err) { logO(err); channel.send("⛔ Failed to load stats."); } await sleep(1000);
try { getIDs(); channel.send("✅ Loaded ids."); } catch (err) { logO(err); channel.send("⛔ Failed to load ids."); } await sleep(1000);
try { cacheRoleInfo(); channel.send("✅ Cached role info."); } catch (err) { logO(err); channel.send("⛔ Failed to cache role info."); } await sleep(1000);
try { getSCCats(); channel.send("✅ Cached sc cats."); } catch (err) { logO(err); channel.send("⛔ Failed to sc cats."); } await sleep(1000);
try { getCCs(); channel.send("✅ Cached cc cats."); } catch (err) { logO(err); channel.send("⛔ Failed to cache cc cats."); } await sleep(1000);
try { getPublicCat(); channel.send("✅ Cached public cat."); } catch (err) { logO(err); channel.send("⛔ Failed to cache public cat."); } await sleep(1000);
try { loadPollValues(); channel.send("✅ Cached poll values."); } catch (err) { logO(err); channel.send("⛔ Failed to cache poll values."); } await sleep(1000);
try { cacheIconLUT(); channel.send("✅ Loaded icon lut."); } catch (err) { logO(err); channel.send("⛔ Failed to load icon lut."); } await sleep(1000);
try { global.client.guilds.fetch(stats.log_guild).then(guild => {guild.members.fetch().then((members) => {})}); channel.send("✅ Loaded users."); } catch (err) { logO(err); channel.send("⛔ Failed to load users."); } await sleep(1000);
}
async function logDMs() {
// test
//let ids = [];
let ids = ["242983689921888256"];
for(let i = 0; i < ids.length; i++) {
console.log("Checking dms with: " + ids[i]);
await logDM(ids[i]);
}
}
async function logDM(id) {
await global.client.users.fetch(id).then(async u => {
await u.createDM().then(async dm => {
await dm.messages.fetch({limit: 100}).then(async msgs => {
await sleep(1000);
await msgs.forEach(async m => {
await sleep(1000);
log("To: " + u.username + "\nBy: " + m.author.username + "\nAt: " + timeConverter(m.createdTimestamp) + "\n```" + m.content + "```");
});
});
});
});
}
function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = date + ' ' + month + ' ' + year + ' ' + (hour<=9?"0"+hour:hour) + ':' + (min<=9?"0"+min:min) + ':' + (sec<=9?"0"+sec:sec);
return time;
}
function uncacheMessage(message) {
if(!isParticipant(message.member)) {
message.channel.messages.cache.delete(message.id);
}
}
var sqlChannel = null;
function restartSQL(channel) {
sqlChannel = channel;
sqlChannel.send("RELOADING");
exec('sudo service mysql restart', (err, output) => {
// once the command has completed, the callback function is called
if (err) {
// log and return if we encounter an error
console.error("could not execute command: ", err)
sqlChannel.send("could not execute command: " + err);
sqlChannel.send("FAILURE");
return;
}
// log the output received from the command
console.log("Output: \n", output)
sqlChannel.send("Output: \n" + output);
sqlChannel.send("SUCCESS");
forceReload(sqlChannel);
})
}
var automationBusy = false;
var lastChatter = null;
var lastChatterCharacters = 0;
var srcRefSaved = null;
var srcNameSaved = null;
/* New Message */
client.on("messageCreate", async message => {
if(!message) return;
try {
await message.fetch();
} catch (err) {
console.log("UNKNOWN MESSAGE");
//console.log(err);
return;
}
if(!botLoaded && !message.author.bot) {
message.channel.send("🕐 Bot is loading. Please wait.");
return;
}
if(!message.author.bot && message.reference && message.mentions.repliedUser === null && message.type === 0) {
cmdWebhook(message.channel, message.member, ["**Forwarded Message**","\n*<@" + message.author.id + "> You're not allowed to forward messages during the game!*"]);
message.delete();
}
// Check if message is a prompt reply
if(
!message.author.bot // not from bot
&& message.mentions && message.mentions.repliedUser && message.mentions.repliedUser == client.user.id // check if replied to bot
&& message.reference && message.reference.messageId && (await isPrompt(message.reference.messageId)) // check if replied to message is a prompt
) {
if(!automationBusy) { // make sure only one action runs at a time
automationBusy = true;
await handlePromptReply(message); // handle the prompt
automationBusy = false;
} else { // in my testing i was unable to reply fast enough to trigger this, but theoretically it should be possible
abilityLog(`🕐 **Bot Busy:** <@${message.author.id}> tried to reply to a prompt while bot was busy.`);
message.reply("🕐 Bot is busy. Please retry.");
}
return; // dont do further steps for prompts
}
/* Fetch Channel */
if(isParticipant(message.member)) {
message.channel.messages.fetch({ limit: 50 });
}
/* Connected Channels */ // Copies messages from one channel to another and applies disguises if one is set
connectionExecute(message);
/* Counts messages */
if(stats.gamephase == gp.INGAME && message.content.slice(stats.prefix.length).indexOf(stats.prefix) !== 0 && !message.author.bot && isParticipant(message.member)) {
if(isCC(message.channel) || isSC(message.channel)) { // private message
sql("UPDATE players SET private_msgs=private_msgs+1 WHERE id = " + connection.escape(message.member.id), () => {}, () => {
log("MSG Count > Failed to count private message for " + message.author + "!")
});
} else if(isPublic(message.channel)) { // public message
sql("UPDATE players SET public_msgs=public_msgs+1 WHERE id = " + connection.escape(message.member.id), () => {}, () => {
log("MSG Count > Failed to count private message for " + message.author + "!")
});
}
}
/* Counts messages, again **/
if(!message.author.bot && message.content.indexOf(stats.prefix) !== 0) {
let countActivity = false;
// check if treshold is hit
let ACTIVITY_TRESHHOLD = 25;
// let x = [0,10], diff = 0; for(let i = 0; i < 99; i++) x.push(x[x.length - 1] + (diff+=10)); console.log(""+x);
let LEVELS = [0,10,20,40,70,110,160,220,290,370,460,560,670,790,920,1060,1210,1370,1540,1720,1910,2110,2320,2540,2770,3010,3260,3520,3790,4070,4360,4660,4970,5290,5620,5960,6310,6670,7040,7420,7810,8210,8620,9040,9470,9910,10360,10820,11290,11770,12260,12760,13270,13790,14320,14860,15410,15970,16540,17120,17710,18310,18920,19540,20170,20810,21460,22120,22790,23470,24160,24860,25570,26290,27020,27760,28510,29270,30040,30820,31610,32410,33220,34040,34870,35710,36560,37420,38290,39170,40060,40960,41870,42790,43720,44660,45610,46570,47540,48520,49510];
if(lastChatter === message.author.id) {
lastChatterCharacters += message.content.toLowerCase().replace(/[^a-z]/g,"").replace(/(.)\1\1{1,}/g,"$1$1").length;
if(lastChatterCharacters >= ACTIVITY_TRESHHOLD) countActivity = true;
} else {
lastChatter = message.author.id;
lastChatterCharacters = message.content.toLowerCase().replace(/[^a-z]/g,"").replace(/(.)\1\1{1,}/g,"$1$1").length;
if(lastChatterCharacters >= ACTIVITY_TRESHHOLD) countActivity = true;
}
// count activity
if(countActivity) {
let curTime = xpGetTime(); // current time in 5m intervals
let activity = await sqlPromEsc("SELECT * FROM activity WHERE player=", message.author.id);
if(activity && activity.length > 0) {
if(activity[0].timestamp < curTime) {
await sqlPromEsc("UPDATE activity SET count=count+1,timestamp=" + curTime + " WHERE player=", message.author.id);
let newLevel = (+activity[0].level) + 1;
let reqXpLevelup = LEVELS[newLevel];
let randChance = Math.random();
if(reqXpLevelup && reqXpLevelup <= ((+activity[0].count) + 1) && randChance < 0.25 && !((isParticipant(message.member) || isHost(message.member)) && stats.gamephase == gp.INGAME)) {
console.log(`Level Up for ${message.member.displayName} to Level ${newLevel}!`);
await sleep(30000); // delay level up by 30s
await sqlPromEsc("UPDATE activity SET level=level+1 WHERE player=", message.author.id);
let coinsReward = newLevel * 5;
await modifyCoins(message.author.id, coinsReward);
let embed = { title: "Level up!", description: `Congratulations, <@${message.author.id}>! You have leveled up to **Level ${newLevel}**!\n\nAs a reward you have received \`${coinsReward}\` coins. Use \`${stats.prefix}coins\` to check how many coins you have.`, color: 9483375};
embed.thumbnail = { url: iconRepoBaseUrl + "Extras/Ascension.png" };
// Level Up Reward
let newLevelString = newLevel + "";
if(newLevel % 5 === 0) {
let boxRewards = [null, null, null, [0], [0,1], null, [0,2], [0,1,2], [0,1,3], [0,1,2,3], null, [0,3], [0,2,3], [1], [1,2], null, [1,3], [1,2,3], [2], [2,3], [3]];
let re = boxRewards[Math.floor(newLevel / 5)];
// Standard Box Reward
if(newLevel === 100) {
embed.description += `\n\nAdditionally, you get a free loot box with a guaranteed platinum tier reward.`;
embed.description += `\n\nAdditionally, you may select any lootbox prize that will be unlocked for you.`;
message.channel.send({ embeds: [ embed ] });
await openBox(message.channel, message.author.id, null, re);
await inventoryModifyItem(message.author.id, "SPEC:Any", 1);
} else if(re) {
let boxName = re.map(el => tierNames[el].toLowerCase()).join(" or ");
embed.description += `\n\nAdditionally, you get a free loot box with a guaranteed ${boxName} tier reward.`;
message.channel.send({ embeds: [ embed ] });
await openBox(message.channel, message.author.id, null, re);
} else {
switch(newLevel) {
case 5:
let verified = message.guild.roles.cache.find(role => role.name == "Verified");
if(verified) {
message.member.roles.add(verified);
embed.description += `\n\nAdditionally, you got the \`Verified\` role, which grants a few additional permissions.`;
}
break;
case 10:
embed.description += `\n\nAdditionally, you may now transfer rewards to others using \`${stats.prefix}inventory transfer\`.`;
await inventoryModifyItem(message.author.id, "BOT:invtransfer", 1);
break;
case 15:
embed.description += `\n\nAdditionally, you may now recycle rewards into coins using \`${stats.prefix}recycle\`.`;
await inventoryModifyItem(message.author.id, "BOT:recycle", 1);
break;
case 20:
embed.description += `\n\nAdditionally, you may now update your nickname while out of game \`${stats.prefix}nickname\`.`;
await inventoryModifyItem(message.author.id, "BOT:nick", 1);
break;
case 25:
embed.description += `\n\nAdditionally, you may select an icon (that is available as loot) that will be unlocked for you.`;
await inventoryModifyItem(message.author.id, "SPEC:AnyIcon", 1);
break;
case 50:
embed.description += `\n\nAdditionally, you may select a skinpack (that is available as loot) that will be unlocked for you.`;
await inventoryModifyItem(message.author.id, "SPEC:AnySkinpack", 1);
break;
case 75:
embed.description += `\n\nAdditionally, you may select a guarantor (that is available as loot) that will be unlocked for you.`;
await inventoryModifyItem(message.author.id, "SPEC:AnyGuarantor", 1);
break;
}
message.channel.send({ embeds: [ embed ] });
}
} else if(newLevelString.length === 2 && newLevelString[0] === newLevelString[1]) {
let boxRewards = [[0], [0,1], [0,2], [0,1,3], [0,1,2,3], [1,2], [1,3], [2,3], [3]];
let re = boxRewards[(+ newLevelString[0]) - 1];
// Standard Box Reward
if(re) {
let boxName = re.map(el => tierNames[el].toLowerCase()).join(" or ");
embed.description += `\n\nAdditionally, you get a free loot box with a guaranteed ${boxName} tier reward.`;
message.channel.send({ embeds: [ embed ] });
await openBox(message.channel, message.author.id, null, re);
} else {
message.channel.send({ embeds: [ embed ] });
}
} else {
if(newLevel === 1) embed.description += `\n\nYou can check your XP and Level using \`${stats.prefix}xp\` and see a leaderboard using \`${stats.prefix}xp list\`.`;
message.channel.send({ embeds: [ embed ] });
}
}
}
} else {
await sqlProm("INSERT INTO activity (player, count, timestamp) VALUES (" + connection.escape(lastChatter) + ", 1, " + connection.escape(curTime) + ")");
}
}
}
// Ban annoying player behaivors
if(message.author.id === "689942180323786954") {
let txt = message.content.toLowerCase();
if(txt.includes("parrot") || txt.includes("parot") || txt.includes("bird") || txt.includes("🦜") || txt.includes("birb") || txt.includes("🦅") || txt.includes("eagle") || txt.includes("🌭 ") || txt.includes("🐦") || txt.includes("🐤") || txt.includes("🐣") || txt.includes("🐥") || txt.includes("🪿") || txt.includes("🦆") || txt.includes("🐦") || txt.includes("⬛") || txt.includes("🦉") || txt.includes("🦇") || txt.includes("🐓") || txt.includes("rooster") || txt.includes("chicken")) {
message.delete();
if(isPublic(message.channel)) { // public message
sql("UPDATE players SET public_msgs=public_msgs-5 WHERE id = " + connection.escape(message.member.id), () => {}, () => {
});
sql("UPDATE players SET private_msgs=private_msgs-5 WHERE id = " + connection.escape(message.member.id), () => {}, () => {
});
}
}
}
if(message.author.id === "151204089219252224") {
let txt = message.content.toLowerCase();
if(txt.includes("||") || txt.includes("#")) {
message.delete();
if(isPublic(message.channel)) { // public message
sql("UPDATE players SET public_msgs=public_msgs-5 WHERE id = " + connection.escape(message.member.id), () => {}, () => {
});
sql("UPDATE players SET private_msgs=private_msgs-5 WHERE id = " + connection.escape(message.member.id), () => {}, () => {
});
}
}
}
/* Gif Check */
if(!message.author.bot && isParticipant(message.member) && message.content.search("http") >= 0 && stats.ping.length > 0 && stats.gamephase == gp.INGAME) {
urlHandle(message, !!message.member.roles.cache.get(stats.gamemaster_ingame));
}
/* Host Ping Checker */
if(message.mentions.has(stats.host) && message.channel.id != stats.log_channel && stats.host_log && stats.host_log != "false" && !message.author.bot) {
if(stats.log_guild && stats.log_channel) {
let channel = message.guild.channels.cache.get(stats.host_log);
let embed = { "title": `In <#${message.channel.id}>`, "description": `${message.content}`, "color": 15220992, "url": `${message.url}`, "timestamp": new Date().toISOString(), "author": { "name": `${message.author.username}`, "url": `${message.url}`, "icon_url": `${message.member.displayAvatarURL()}` } };
channel.send({ embeds: [ embed ] }).then(m => {
m.react(client.emojis.cache.get(stats.yes_emoji));
});
}
};
/* Find Command & Parameters */
// Not a command
if(message.channel.type === ChannelType.DM) return;
if(message.content.slice(stats.prefix.length).indexOf(stats.prefix) == 0) return;
if(message.content.indexOf(stats.prefix) !== 0 && message.content[0] == ".") {
let msg = message.content.trim().substr(1).trim();
let msgRole = msg.match(/(".*?")|(\S+)/g) ? msg.match(/(".*?")|(\S+)/g).map(el => el.replace(/"/g, "").toLowerCase()) : "";
//console.log(msg + " => " + msgRole);
if(msg.match(/^[a-zA-Z ]*$/)) cmdInfoIndirectSimplified(message.channel, message.author.id, msgRole);
if(msgRole && stats.fancy_mode && verifyRole(msgRole.join(" "))) message.delete();
uncacheMessage(message);
return;
}
if(message.content.indexOf(stats.prefix) !== 0 && message.content[0] == ";") {
let msg = message.content.trim().substr(1).trim();
let msgRole = msg.match(/(".*?")|(\S+)/g) ? msg.match(/(".*?")|(\S+)/g).map(el => el.replace(/"/g, "").toLowerCase()) : "";
//console.log(msg + " => " + msgRole);
if(msg.match(/^[a-zA-Z ]*$/)) cmdInfoIndirect(message.channel, message.author.id, msgRole, false, true, false);
if(msgRole && stats.fancy_mode && verifyRole(msgRole.join(" "))) message.delete();
uncacheMessage(message);
return;
}
if(message.content.indexOf(stats.prefix) !== 0 && message.content[0] == "~") {
let msg = message.content.trim().substr(1).trim();
let msgRole = msg.match(/(".*?")|(\S+)/g) ? msg.match(/(".*?")|(\S+)/g).map(el => el.replace(/"/g, "").toLowerCase()) : "";
//console.log(msg + " => " + msgRole);
if(msg.match(/^[a-zA-Z ]*$/)) cmdInfoIndirectTechnical(message.channel, message.author.id, msgRole, false, true, false, false, false, false, true);
if(msgRole && stats.fancy_mode && verifyRole(msgRole.join(" "))) message.delete();
uncacheMessage(message);
return;
}
if(message.content.indexOf(stats.prefix) !== 0 && message.content[0] == "&") {
let msg = message.content.trim().substr(1).trim();
let msgRole = msg.match(/(".*?")|(\S+)/g) ? msg.match(/(".*?")|(\S+)/g).map(el => el.replace(/"/g, "").toLowerCase()) : "";
console.log(msg + " => " + msgRole);
if(msg.match(/^[a-zA-Z ]*$/)) cmdGetCard(message.channel, msgRole.join(" "));
if(msgRole && stats.fancy_mode && verifyRole(msgRole.join(" "))) message.delete();
uncacheMessage(message);
return;
}
if(message.content.indexOf(stats.prefix) !== 0) {
if(message.embeds.length <= 0 && !message.author.bot) uncacheMessage(message);
return;
}
// Replace contents
if(message.member && !message.author.bot) message.content = message.content.replace(/%s/, message.member.id)
if(message.channel && !message.author.bot) message.content = message.content.replace(/%c/, message.channel.id);
// Get default arguments / default command / unmodified arguments / unmodified commands
const args = message.content.slice(stats.prefix.length).trim().match(/(".*?")|(\S+)/g) ? message.content.slice(stats.prefix.length).trim().match(/(".*?")|(\S+)/g).map(el => el.replace(/"/g, "").toLowerCase()) : [];
const command = parseAlias(args.shift());
const argsX = message.content.slice(stats.prefix.length).trim().replace(/\r?\n/g,"~").match(/(".*?")|(\S+)/g) ? message.content.slice(stats.prefix.length).trim().replace(/~/g,"</>").replace(/\r?\n/g,"~").match(/(".*?")|(\S+)/g).map(el => el.replace(/"/g, "")) : [];
const commandX = argsX.shift();
if(message.content.search("@everyone") >= 0) {
return;
}
/* Ping */ // Generic test command / returns the ping
switch(command) {
case "ping":
cmdPing(message);
break;
case "drag": // drags players to townsquare VC MWR
if(checkGM(message)) {
sql("SELECT id FROM players WHERE alive = 1 AND type='player'", result => {
result.forEach(p => {
let member = message.channel.guild.members.cache.get(p.id);
member.voice.setChannel("1075234996329136138");
});
});
let member = message.channel.guild.members.cache.get("242983689921888256");
member.voice.setChannel("1075234996329136138");
}
break;
case "drag_dead": // drags players to dead VC MWR
if(checkGM(message)) {
sql("SELECT id FROM players WHERE alive = 1 AND type='player'", result => {
result.forEach(p => {
let member = message.channel.guild.members.cache.get(p.id);
member.voice.setChannel("1075235455123083264");
});
});
let member = message.channel.guild.members.cache.get("242983689921888256");
member.voice.setChannel("1075235455123083264");
}
break;
case "image": // displays an image
cmdGetImg(message.channel, args.join(" "), message.author);
break;
case "card": // displays a card
cmdGetCard(message.channel, args.join(" "));
break;
case "embed": // generates an embed
if(checkGMHelper(message)) {
let embed = message.content.split(" ");
embed.shift();
embed = JSON.parse(embed.join(" ").replace(/'/g,'"'));
if(embed.embed) embed = embed.embed;
message.channel.send({embeds:[ embed ]});
}
break;
case "force_reload": // reloads db and caches
if(checkGM(message)) forceReload(message.channel);
break;
case "sql_reload": // reloads db and caches
let aid = message.author.id;
let admins = ["242983689921888256","458727748504911884","277156693765390337"];
let sgm = ["331803222064758786","544125116640919557","334066065112039425","234474456624529410"];
if(admins.includes(aid) || sgm.includes(aid) || checkGM(message)) restartSQL(message.channel);
break;
case "emit": // emits a trigger
if(checkGM(message)) cmdEmit(message.channel, argsX);
break;
case "execute": // executes an ability
if(checkGM(message)) cmdExecute(message.channel, message.content.substr(8 + stats.prefix.length), "player:" + message.author.id, "role:host");
break;
case "execute_as_set": // set an executor for execute_as
if(checkGM(message)) {
srcRefSaved = args[0];
srcNameSaved = args[1];
message.channel.send(`Executing as ${srcRefSaved} (${srcNameSaved}) for \`${stats.prefix}execute_as\``);
}
break;
case "execute_as": // executes an ability
if(checkGM(message)) cmdExecute(message.channel, message.content.substr(11 + stats.prefix.length), srcRefSaved, srcNameSaved);
break;
case "grant": // execute - grant add
if(checkGM(message)) cmdGrant(message, args);
break;
case "whisper": // execute - whispering
if(checkGM(message)) cmdWhisper(message, args);
break;
case "parse": // parses a game element
if(checkGM(message)) cmdParse(message.channel, args);
break;
case "phase": // executes an ability
if(checkGM(message)) cmdPhase(message, args);
break;
case "edit":
if(checkGMHelper(message)) cmdEdit(message.channel, args, argsX);
break;
/* Split */
case "say":
if(checkGMHelper(message)) message.channel.send(argsX.join(" ").replace(/~/g,"\n"));
break;
case "modify":
if(checkGMHelper(message)) cmdModify(message, args, argsX);
break;
case "split":
if(checkGM(message)) args.join(" ").replace(/'/g,'"').split(";").forEach(el => message.channel.send(stats.prefix + el));
break;
/* Gamephase */ // Commands related to the gamephase
case "gamephase":
if(checkGM(message)) cmdGamephase(message, args);
break;
/* Connection */ // Manages connections between channels
case "connection":
if(checkGMHelper(message)) cmdConnection(message, args);
break;
/* Roles */ // Modify role information for commands such as 'info'
case "roles":
if(checkGM(message)) cmdRoles(message, args, argsX);
break;
/* Alias */ // Modify alias information for commands such as 'info'
case "alias":
if(checkGM(message)) cmdAlias(message, args, argsX);
break;
/* Infomanage */ // Modify info information for commands such as 'info'
case "infomanage":
if(checkGM(message)) cmdInfomanage(message, args, argsX);
break;
/* Displays */ // Manages displays
case "displays":
if(checkGM(message)) cmdDisplays(message, args, argsX);
break;
/* groups */ // Command for groups
case "groups":
if(checkGM(message)) cmdGroups(message, args, argsX);
break;
/* attributes */ // Command for attribute
case "attributes":
if(checkGM(message)) cmdAttributes(message, args, argsX);
break;
/* sets */ // Command for sets
case "sets":
if(checkGM(message)) cmdSets(message, args, argsX);
break;
/* locations */ // Command for locations (undocumentated)
case "locations":
if(checkGM(message)) cmdLocations(message, args);
break;
/* polls */ // Command for locations (undocumentated)
case "polls":
if(checkGM(message)) cmdPolls(message, args);
break;
/* teams */ // Command for locations (undocumentated)
case "teams":
if(checkGM(message)) cmdTeams(message, args);
break;
/* Update */ // Updates all github linked data
case "update":
if(checkGM(message)) cmdUpdate(message.channel);
break;
/* Role Info */ // Returns the info for a role set by the roles command (simplified)
case "info":
cmdInfo(message.channel, message.author.id, args, false, false, true);
break;
/* Role Info */ // Returns the info for a role set by the roles command (basics/details)
// NOT DOCUMENTED
case "details":
cmdInfo(message.channel, message.author.id, args);
break;
/* Role Info */ // Returns the info for a role set by the roles command
case "info_technical":
cmdInfoTechnical(message.channel, message.author.id, args);
break;
/* Role Info + Pin */ // Returns the info for a role set by the roles command & pins the message
case "infopin":
if(checkGM(message)) cmdInfopin(message.channel, message.author.id, args);
break;
/* Role Info */ // Returns the info for a role set by the roles command
case "infoedit": // WIP: READD this command
//if(checkGM(message)) cmdInfoEdit(message.channel, args, argsX);
break;
/* Role Info (Add) */ // Returns the info for a role set by the roles command, but with additions
case "infoadd": // WIP: READD this command
//if(checkGM(message)) cmdInfoFancy(message.channel, [args[0]], false, false, false, false, ["", argsX[1].replace(/~/g, "\n").replace(/<\/>/g,"~")]);
break;
break;
/* Options */ // Modify options such as role ids and prefix
case "options":
if(checkGM(message)) cmdOptions(message, argsX);
break;
/* Signup */ // Signs a player up with an emoji
case "j":
if(!args[0]) {
// find emoji
let em = idEmojis.filter(el => el[0] == message.author.id);
if(em[0]) cmdSignup(message.channel, message.member, [em[0][1]], true);
else cmdSignup(message.channel, message.member, args, true);
// for gm demote
if(isGameMaster(message.member)) cmdDemote(message.channel, message.member);
} else { // if arg specified
cmdSignup(message.channel, message.member, args, true);
}
break;
case "signup":
cmdSignup(message.channel, message.member, args, true);
break;
/* List Signedup */ // Lists all signedup players
case "list_signedup":
cmdListSignedup(message.channel);
break;
/* List Signedup (alphabetical) */ // Lists all signedup players (alphabetically)
case "list_alphabetical":
cmdListSignedupAlphabetical(message.channel);
break;
/* List Alive */ // Lists all alive players
case "list_alive":
cmdListAlive(message.channel);
break;
/* List Dead */ // Lists all dead players
case "list_dead":
cmdListDead(message.channel);
break;
/* List Substitutes */ // Lists all substitute players
case "list_substitutes":
cmdListSubs(message.channel);
break;
/* Bulk Delete */ // Deletes a lot of messages
case "bulkdelete":
if(checkGMHelper(message)) cmdConfirm(message, "bulkdelete");
break;
/* Delete */ // Deletes a couple of messages
case "delete":
if(checkGMHelper(message)) cmdDelete(message.channel, args);
break;
/* Delay */ // Executes a command with delay
case "delay":
if(checkGMHelper(message)) cmdDelay(message.channel, args);
break;
/* Start */ // Starts the game
case "start":
if(checkSafe(message)) cmdConfirm(message, "start");
break;
/* Check Start */ // Checks if the game can be started
case "check_start":
if(checkSafe(message)) cmdCheckStart(message.channel);
break;
/* Start */ // Starts a debug game
case "start_debug":
if(checkSafe(message)) cmdStart(message.channel, true);
break;
/* Restart */ // Debug restart
case "reset_debug":
if(checkSafe(message)) cmdReset(message.channel, true);
break;
/* Reset */ // Resets a game
case "reset":
if(checkSafe(message)) cmdConfirm(message, "reset");
break;
/* End */ // Ends a game
case "end":
if(args[0] == "poll") {
removeRoleRecursive(message.member, message.channel, stats.host, "host");
removeRoleRecursive(message.member, message.channel, stats.gamemaster, "gamemaster");
removeRoleRecursive(message.member, message.channel, stats.senior_gamemaster, "senior gamemaster");
message.channel.send("⛔ Command execution blocked. This is not the command you're looking for.");
message.member.createDM().then(dm => dm.send("You have been automatically demoted due to incompetence 🙂 ❤️"));
break;
}
if(checkSafe(message)) cmdConfirm(message, "end");
break;
/* Sheet */ // Simplifies game managment via sheet
case "sheet":
if(checkSafe(message)) cmdSheet(message, args);
break;
/* Kill Q */
case "killq":
if(checkSafe(message)) cmdKillq(message, args);
break;
/* Kill Q */
case "kqak":
if(checkSafe(message)) {
cmdKillq(message, ["add" ,...args]);
cmdKillq(message, ["killall" ,...args]);
}
break;
/* Players */
case "players":
if(checkGM(message)) cmdPlayers(message, args);
break;
case "pg":
if(checkGM(message)) cmdPlayers(message, ["get", ...args]);
break;
case "ps":
if(checkGM(message)) cmdPlayers(message, ["set", ...args]);
break;
case "pr":
if(checkGM(message)) cmdPlayers(message, ["resurrect", ...args]);
break;
case "roll":
cmdRoll(message, args);
break;
/* CCs */
case "cc":
cmdCC(message, args, argsX);
break;
case "sc":
if(checkGM(message)) cmdSC(message, args);
break;
case "impersonate":
if(checkGMHelper(message)) cmdImpersonate(message, argsX);
break;
/* Help */
case "help":
cmdHelp(message.channel, message.member, args);
break;
/* Emoji */
case "emojis":
cmdEmojis(message.channel);
break;
/* Promote */
case "promote":
cmdPromote(message.channel, message.member);
break;
/* Promote */
case "demote":
cmdDemote(message.channel, message.member);
break;
/* Force Demote All */
case "force_demote_all":
if(checkAdmin(message)) {
cmdForceDemote(message.channel, true);
}
break;
/* Force Demote Signed Up */
case "force_demote_signedup":
if(checkGM(message)) {
cmdForceDemote(message.channel, false);
}
break;
/* Host */
case "host":
cmdHost(message.channel, message.member);
break;
/* Unhost */
case "unhost":
cmdUnhost(message.channel, message.member);
break;
/* Promote Host */
case "promote_host":
cmdPromoteHost(message.channel, message.member);
break;
/* Demote Unhost */
case "demote_unhost":
cmdDemoteUnhost(message.channel, message.member);
break;
/* Theme */
case "theme":
if(checkGMHelper(message)) cmdTheme(message, args);
break;
/* New Game Ping */
case "gameping":
if(checkGM(message)) cmdGamePing(message.channel, message.member);
break;
/* Open Signups */
case "open":
if(checkGM(message)) cmdOpen(message);
break;
/* Close Signups */
case "close":
if(args[0] == "poll") {
removeRoleRecursive(message.member, message.channel, stats.host, "host");
removeRoleRecursive(message.member, message.channel, stats.gamemaster, "gamemaster");
removeRoleRecursive(message.member, message.channel, stats.senior_gamemaster, "senior gamemaster");
message.channel.send("⛔ Command execution blocked. This is not the command you're looking for.");
message.member.createDM().then(dm => dm.send("You have been automatically demoted due to incompetence 🙂 ❤️"));
break;
}
if(checkGM(message)) cmdClose(message);
break;
/* Spectate */
case "spectate":
cmdSpectate(message.channel, message.member);
break;
/* Substitute */
case "substitute":
cmdSubstitute(message.channel, message.member, args);
break;
/* Confirm */
case "confirm":
confirmActionExecute(args.join(" "), message, false);
break;
/* Modrole */
case "modrole":
/** DISABLED
if(message.author.id == client.user.id || checkAdmin(message)) cmdModrole(message, args);
**/
break;
/* Elect */
case "elect":
if(checkGM(message)) cmdElect(message.channel, args);
break;
/* Discord Role */
case "dr":
if(checkGM(message)) cmdDR(message.channel, args);
break;
/* Host Information */
case "host_information":
if(checkGM(message)) cmdHostInformation(message.channel, args);
break;
/* Host Information */
case "packs":
cmdPacks(message, args);
break;
case "temp":
let tempPerms = await inventoryGetItem(message.author.id, "bot:temp");
if(tempPerms === 0) {
message.channel.send(`⛔ You have not unlocked the ${stats.prefix}temp command.`);
break;
}
cmdTemp(message, args);
break;
case "reverseme":
cmdReverseme(message);
break;
case "newship":
cmdNewship(message);
break;
case "newhate":
cmdNewhate(message);
break;
case "flip":
cmdFlip(message);
break;
case "fortune":
cmdFortune(message, args);
break;
case "time":
cmdTime(message.channel, args);
break;
case "chooser":
if(checkGM(message)) cmdChooser(message, args);
break;
case "loot":
cmdLoot(message);
break;
case "loot_force":
if(checkGM(message)) cmdLootForce(message, args);
break;
case "xp":
if(isParticipant(message.member) && stats.gamephase != gp.POSTGAME) {
message.channel.send(`⛔ You cannot use this command while ingame.`);
break;
}
cmdXP(message, args);
break;
case "coins":
cmdCoins(message, args);
break;
case "inventory":
if((isSignedUp(message.member) || isParticipant(message.member)) && stats.gamephase != gp.POSTGAME) {
message.channel.send(`⛔ You cannot use this command while signed up or ingame.`);
break;
}
cmdInventory(message, args);
break;
case "icon":
if(isParticipant(message.member) && stats.gamephase != gp.POSTGAME) {
message.channel.send(`⛔ You cannot use this command while ingame.`);
break;
}
cmdIcon(message, args);
break;
case "death_message":
cmdDeathMessage(message, args);
break;
case "recycle":
cmdRecycle(message, args);
break;
case "nickname":
cmdNickname(message, argsX);
break;
/* Invalid Command */
default:
message.channel.send("⛔ Syntax error. Unknown command `" + command + "`!");
break;
}
/* Delete Message */
message.delete();
});
client.on('messageDelete', async message => {
message = JSON.parse(JSON.stringify(message)); // WHY IS THIS LINE OF CODE NECESSARY????????
// retrieve channel and author
let channel = client.guilds.cache.get(message.guildId).channels.cache.get(message.channelId);
let log = client.guilds.cache.get(stats.log_guild).channels.cache.get(stats.log_channel);
let author = client.guilds.cache.get(message.guildId).members.cache.get(message.authorId);
if((message.content[0] != config.prefix && message.content[0] != "§" && message.content[0] != "$" && message.content[0] != "." && message.content[0] != ";" && message.content[0] != "~") && (isParticipant(author) || isDeadParticipant(author)) && message.content.search("http") == -1) {
cmdWebhook(log, author, ["**Deleted Message**", "\n*Deleted message by <@" + message.authorId + "> in <#" + message.channelId + ">!*","\n> ", message.content.split("\n").join("\n> "),"\n","\n" + stats.ping ]);
cmdWebhook(channel, author, ["**Deleted Message**","\n*<@" + message.authorId + "> You're not allowed to delete messages during the game!*"]);
}
});
client.on('messageUpdate', async (oldMessage, newMessage) => {
try {
await newMessage.fetch();
} catch (err) {
return; // the message that got edited doesnt exist
}
oldMessage = JSON.parse(JSON.stringify(oldMessage));
newMessage = JSON.parse(JSON.stringify(newMessage));
// retrieve channel and author
let msgGuild = client.guilds.cache.get(oldMessage.guildId);
if(!msgGuild) return;
let channel = msgGuild.channels.cache.get(oldMessage.channelId);
let log = client.guilds.cache.get(stats.log_guild).channels.cache.get(stats.log_channel);
let author = msgGuild.members.cache.get(oldMessage.authorId);
if(isParticipant(author) && (Math.abs(oldMessage.content.length - newMessage.content.length) > (oldMessage.content.length/5))) {
//cmdWebhook(log, author, ["**Updated Message**", "\n*Updated message by <@" + oldMessage.authorId + "> in <#" + oldMessage.channelId + ">!*","\n__Old:__\n> ", oldMessage.content.split("\n").join("\n> "),"\n","\n__New:__\n> ", newMessage.content.split("\n").join("\n> "),"\n","\n" + stats.ping ]);
cmdWebhook(log, author, ["**Updated Message**", "\n*Updated message by <@" + oldMessage.authorId + "> in <#" + oldMessage.channelId + ">!*","\n__Old:__\n> ", oldMessage.content.split("\n").join("\n> "),"\n","\n__New:__\n> ", newMessage.content.split("\n").join("\n> "),"\n","\n" ]);
}
});
/* Reactions Add*/
client.on("messageReactionAdd", async (reaction, user) => {
try {
await reaction.fetch();
await reaction.message.fetch();
await user.fetch();
} catch (err) {
return; // the reaction doenst exist
}
if(user.bot) return;
// Handle confirmation messages
else if(reaction.emoji.name === "✅" && isGameMaster(reaction.message.guild.members.cache.get(user.id))) {
sql("SELECT time,action FROM confirm_msg WHERE id = " + connection.escape(reaction.message.id), result => {
if(result.length > 0) confirmAction(result[0], reaction.message);
}, () => {
reaction.message.edit("⛔ Database error. Failed to handle confirmation message!");
});
// Handle reaction ingame
} else if(stats.gamephase == gp.INGAME) {
// Remove unallowed reactions
if(isSpectator(reaction.message.guild.members.cache.get(user.id)) || isDeadParticipant(reaction.message.guild.members.cache.get(user.id))) {
if(reaction.emoji == client.emojis.cache.get(stats.no_emoji) || reaction.emoji == client.emojis.cache.get(stats.yes_emoji) || reaction.emoji.name == "🇦" || reaction.emoji.name == "🇧" || reaction.emoji.name == "🇨" || reaction.emoji.name == "🇩" || reaction.emoji.name == "🇪" || reaction.emoji.name == "🇫") return;
reaction.users.remove(user);
// Automatic pinning
} else if(reaction.emoji.name === "📌" && isParticipant(reaction.message.guild.members.cache.get(user.id)) && (isCC(reaction.message.channel) || isSC(reaction.message.channel))) {
reaction.message.pin();
} else if((isGameMaster(reaction.message.guild.members.cache.get(user.id)) || reaction.message.guild.members.cache.get(user.id).roles.cache.get(stats.gamemaster_ingame)) && reaction.emoji == client.emojis.cache.get(stats.yes_emoji)) {
if(reaction.message.content.split("||").length == 3) { // link approval
reaction.message.edit(Buffer.from(reaction.message.content.split("||")[1], 'base64').toString('ascii'));
reaction.message.reactions.removeAll();
} else if(reaction.message.embeds && reaction.message.embeds[0] && reaction.message.embeds[0].color && reaction.message.embeds[0].color == 15220992) { // confirm host log message
let embed = { author: reaction.message.embeds[0].author, title: reaction.message.embeds[0].title, url: reaction.message.embeds[0].url };
embed.color = 1900288;
embed.description = `**Resolved by ${user}!**`;
reaction.message.edit({ embeds: [ embed ] });
reaction.message.reactions.removeAll();
}
} else if(isGameMaster(reaction.message.guild.members.cache.get(user.id)) && !isParticipant(reaction.message.guild.members.cache.get(user.id)) && reaction.emoji == client.emojis.cache.get(stats.no_emoji)) {
reaction.message.delete();
} else if(stats.gamephase == gp.INGAME && isParticipant(reaction.message.guild.members.cache.get(user.id))) {
let poll = await getPoll(reaction.message.id);
if(poll) {
let emojiText = reaction.emoji.id ? `<:${reaction.emoji.name.toLowerCase()}:${reaction.emoji.id}>` : reaction.emoji.name;
let emojiPlayer = emojiToID(emojiText);
let emojiName = pollEmojiToName(emojiText);
let reacText = emojiText;
if(emojiPlayer) reacText += ` (<@${emojiPlayer}>)`;
if(emojiName) reacText += ` (${emojiName})`;