forked from Kneckter/DiscordRoleBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adminBot.js
1598 lines (1547 loc) · 89.7 KB
/
adminBot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const Discord = require('discord.js');
const bot = new Discord.Client();
const config = require('./config.json');
const schedule = require('node-schedule');
const express = require('express');
const helmet = require('helmet');
const app = express();
const sqlite3 = require('sqlite3');
const sql = new sqlite3.Database('./dataBase.sqlite');
const mysql = require('mysql');
const request = require('request');
const wait = async ms => new Promise(done => setTimeout(done, ms));
const dateMultiplier = 86400000;
// log our bot in
bot.login(config.token);
bot.on('ready', () => {
console.info(GetTimestamp() + '-- DISCORD ROLE BOT IS READY --');
// Create/Check DB tables
SQLConnect().then(x => {
InitDB();
}).catch(err => {console.error(GetTimestamp()+err);});
});
(async () => {
if (config.donations.enabled != "yes" ) {
return;
}
// Basic security protection middleware
app.use(helmet());
// Body parsing middleware
app.use(express.json({ limit: '10kb' }));
// Parsing routes
app.get('/', (req, res) => res.send('Listening...'));
app.post('/', (req, res) => {
const body = req.body;
console.log(GetTimestamp()+'[Webhook Test] Received webhook payload: ', body);
res.send('OK');
});
app.get('/paypal', (req, res) => {
if (req.headers['x-forwarded-for'] || req.headers['x-real-ip']){
var clientip = req.headers['x-forwarded-for'].split(', ')[0] || req.headers['x-real-ip'].split(', ')[0];
}
else {
var clientip = 'unknown'
}
console.log(GetTimestamp()+'[PayPalGet] Someone stopped by from: ', clientip);
res.send('Listening...');
});
app.post('/paypal', async (req, res) => {
if (req.headers['x-forwarded-for'] || req.headers['x-real-ip']){
var clientip = req.headers['x-forwarded-for'].split(', ')[0] || req.headers['x-real-ip'].split(', ')[0];
}
else {
var clientip = 'unknown'
}
console.log(GetTimestamp()+'[PayPalPost] Incoming POST from: '+clientip+'. Body: '+JSON.stringify(req.body));
await handlePayPalData(req, res);
});
app.get('/stripe', (req, res) => {
if (req.headers['x-forwarded-for'] || req.headers['x-real-ip']){
var clientip = req.headers['x-forwarded-for'].split(', ')[0] || req.headers['x-real-ip'].split(', ')[0];
}
else {
var clientip = 'unknown'
}
console.log(GetTimestamp()+'[StripeGet] Someone stopped by from: ', clientip);
res.send('Listening...');
});
app.post('/stripe', async (req, res) => {
if (req.headers['x-forwarded-for'] || req.headers['x-real-ip']){
var clientip = req.headers['x-forwarded-for'].split(', ')[0] || req.headers['x-real-ip'].split(', ')[0];
}
else {
var clientip = 'unknown'
}
console.log(GetTimestamp()+'[StripePost] Incoming POST from: ', clientip);
await handleStripeData(req, res);
});
app.listen(config.donations.port, config.donations.server, () => console.log(GetTimestamp()+`Listening on ${config.donations.server}:${config.donations.port}...`));
})();
// ##########################################################################
// ############################# SERVER LISTENER ############################
// ##########################################################################
// DATABASE TIMER FOR TEMPORARY ROLES
setInterval(async function() {
// Process any outstanding donations before checking roles
await query(`SELECT * FROM paypal_info WHERE fulfilled=0 AND rejection=0`)
.then(async rows => {
if(!rows[0]) {
return;
}
// Get a bearer token so we can pull some data from PayPal
let bearerToken = await getBearerToken();
if (!bearerToken) {
return;
}
for(rowNumber = "0"; rowNumber < rows.length; rowNumber++) {
// Get the JSON and pull out the href to download the order info
let orderID = rows[rowNumber].order_id;
// Get the order details directly from PayPal so it is up-to-date
let orderJSON = await getJSONData(bearerToken, `https://api.paypal.com/v2/checkout/orders/${orderID}`);
if (!orderJSON) {
continue;
}
// Save some variables and write to the table
processPayPalOrder(orderJSON, "RECHECK");
}
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute late payment query 1: (${err})`);
process.exit(-1);
});
// Check everyone for expired time
let timeNow = new Date().getTime();
let dbTime = 0;
let daysLeft = 0;
let notify = 0;
await query(`SELECT * FROM temporary_roles`)
.then(async rows => {
if(!rows[0]) {
console.info(GetTimestamp() + "No one is in the DataBase");
return;
}
for(rowNumber = "0"; rowNumber < rows.length; rowNumber++) {
dbTime = parseInt(rows[rowNumber].endDate) * 1000;
notify = rows[rowNumber].notified;
daysLeft = dbTime - timeNow;
let leftServer = rows[rowNumber].leftServer;
let rName = bot.guilds.cache.get(config.serverID).roles.cache.find(rName => rName.name === rows[rowNumber].temporaryRole);
let member = await getMember(rows[rowNumber].userID);
// Check if we pulled the member's information correctly or if they left the server.
if(!member && !leftServer) {
continue;
}
// Update usernames for legacy data
if(!rows[rowNumber].username && !leftServer) {
let name = member.user.username.replace(/[^a-zA-Z0-9]/g, '');
await query(`UPDATE temporary_roles SET username="${name}" WHERE userID="${member.id}"`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute role check query 4: (${err})`);
});
console.log(GetTimestamp() + "Updated the username for "+member.id+" to "+name);
}
// CHECK IF THEIR ACCESS HAS EXPIRED
if(daysLeft < 1) {
// If they left the server, remove the entry without attempting the role removal
if(leftServer) {
await query(`DELETE FROM temporary_roles WHERE userID='${rows[rowNumber].userID}' AND temporaryRole='${rName.name}'`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute role check query 5: (${err})`);
process.exit(-1);
});
bot.channels.cache.get(config.mainChannelID).send("⚠ " + rows[rowNumber].username + " has **left** the server and **lost** their role of: **" +
rName.name + "** - their **temporary** access has __EXPIRED__ 😭 ").catch(err => {console.error(GetTimestamp()+err);});
console.log(GetTimestamp() + "[ADMIN] [TEMPORARY-ROLE] \"" + rows[rowNumber].username + "\" (" + rows[rowNumber].userID +
") has left the server and lost their role: " + rName.name + "... time EXPIRED");
continue;
}
// REMOVE ROLE FROM MEMBER IN GUILD
member.roles.remove(rName).then(async member => {
bot.channels.cache.get(config.mainChannelID).send("⚠ " + member.user.username + " has **lost** their role of: **" +
rName.name + "** - their **temporary** access has __EXPIRED__ 😭 ").catch(err => {console.error(GetTimestamp()+err);});
// REMOVE DATABASE ENTRY
await query(`DELETE FROM temporary_roles WHERE userID='${member.id}' AND temporaryRole='${rName.name}'`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute role check query 2: (${err})`);
process.exit(-1);
});
console.log(GetTimestamp() + "[ADMIN] [TEMPORARY-ROLE] \"" + member.user.username + "\" (" + member.id +
") have lost their role: " + rName.name + "... time EXPIRED");
}).catch(error => {
console.error(GetTimestamp() + error.message);
bot.channels.cache.get(config.mainChannelID).send("**⚠ Could not remove the " +
rName.name + " role from " + member.user.username + "!**").catch(err => {console.error(GetTimestamp()+err);});
});
}
// CHECK IF THERE ARE ONLY HAVE 5 DAYS LEFT
if(daysLeft < 432000000 && notify == "0" && !leftServer) {
let endDateVal = new Date();
endDateVal.setTime(dbTime);
let finalDate = await formatTimeString(endDateVal);
// NOTIFY THE USER IN DM THAT THEY WILL EXPIRE
if(config.paypal.enabled == "yes") {
member.send("Hello " + member.user.username + "! Your role of **" + rows[rowNumber].temporaryRole + "** on " +
bot.guilds.cache.get(config.serverID).name + " will be removed in less than 5 days on \`" + finalDate +
"\`. If you would like to keep the role, please send a donation to <" + config.paypal.url +
">. If you need help, please notify an admin.")
.catch(error => {
console.error(GetTimestamp() + "Failed to send a DM to user: " + member.id);
});
}
else {
member.send("Hello " + member.user.username + "! Your role of **" + rows[rowNumber].temporaryRole + "** on " +
bot.guilds.cache.get(config.serverID).name + " will be removed in less than 5 days on \`" + finalDate +
"\`. If you would like to keep the role, please notify an admin.")
.catch(error => {
console.error(GetTimestamp() + "Failed to send a DM to user: " + member.id);
});
}
// NOTIFY THE ADMINS OF THE PENDING EXPIRY
bot.channels.cache.get(config.mainChannelID).send("⚠ " + member.user.username + " will lose their role of: **" +
rName.name + "** in less than 5 days on \`" + finalDate+"\`.").catch(err => {console.error(GetTimestamp()+err);});
// UPDATE THE DB TO REMEMBER THAT THEY WERE NOTIFIED
let name = member.user.username.replace(/[^a-zA-Z0-9]/g, '');
await query(`UPDATE temporary_roles SET notified=1, username="${name}" WHERE userID="${member.id}" AND temporaryRole="${rName.name}"`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute role check query 3: (${err})`);
process.exit(-1);
});
console.log(GetTimestamp() + "[ADMIN] [TEMPORARY-ROLE] \"" + member.user.username + "\" (" + member.id +
") has been notified that they will lose their role (" + rName.name + ") in less than 5 days on " + finalDate);
}
}
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute role check query 1: (${err})`);
process.exit(-1);
});
}, 600000);
// 86400000 = 1day
// 3600000 = 1hr
// 60000 = 1min
// ##########################################################################
// ############################## TEXT MESSAGE ##############################
// ##########################################################################
bot.on('message', async message => {
// MAKE SURE ITS A COMMAND
if(!message.content.startsWith(config.cmdPrefix)) {
return
}
//STOP SCRIPT IF DM/PM
if(message.channel.type == "dm") {
return
}
// GET CHANNEL INFO
let g = message.guild;
let c = message.channel;
let m = message.member;
let msg = message.content;
msg = msg.toLowerCase();
// GET TAGGED USER
let mentioned = "";
if(message.mentions.users.first()) {
mentioned = message.mentions.users.first();
}
// REMOVE LETTER CASE (MAKE ALL LOWERCASE)
let command = msg.toLowerCase();
command = command.split(" ")[0];
command = command.slice(config.cmdPrefix.length);
// GET ARGUMENTS
let args = msg.split(" ").slice(1);
// GET ROLES FROM CONFIG
let AdminR = g.roles.cache.find(role => role.name === config.adminRoleName);
if(!AdminR) {
AdminR = {
"id": "111111111111111111"
};
console.info(GetTimestamp() + "[ERROR] [CONFIG] I could not find admin role: " + config.adminRoleName);
}
let ModR = g.roles.cache.find(role => role.name === config.modRoleName);
if(!ModR) {
ModR = {
"id": "111111111111111111"
};
console.info(GetTimestamp() + "[ERROR] [CONFIG] I could not find mod role: " + config.modRoleName);
}
// ############################################################################
// ################################ COMMANDS ##################################
// ############################################################################
// ############################# COMMANDS/HELP ################################
if(command === "commands" || command === "help") {
message.delete();
if(args[0] === "mods") {
if(m.roles.cache.has(ModR.id) || m.roles.cache.has(AdminR.id)) {
cmds = "`" + config.cmdPrefix + "temprole @mention <DAYS> <ROLE-NAME>` \\\u00BB to assign a temporary roles\n" +
"`" + config.cmdPrefix + "temprole check @mention <ROLE-NAME>` \\\u00BB to check the time left on a temporary role assignment\n" +
"`" + config.cmdPrefix + "temprole remove @mention <ROLE-NAME>` \\\u00BB to remove a temporary role assignment\n" +
"`" + config.cmdPrefix + "temprole add @mention <ROLE-NAME> <DAYS>` \\\u00BB to add more time to a temporary role assignment\n" +
"`" + config.cmdPrefix + "message <min-seconds> <max-seconds>` \\\u00BB to bulk delete messages. min and max are optional\n" +
"`" + config.cmdPrefix + "restart` \\\u00BB to manually restart the bot\n"
}
else {
message.reply("You are **NOT** allowed to use this command! \ntry using: `" + config.cmdPrefix + "commands`").then((message) => {
message.delete({
timeout: 10000
});
}).catch(err => {console.error(GetTimestamp()+err);});
return;
}
}
if(!args[0]) {
cmds = "`" + config.cmdPrefix + "check` \\\u00BB to check the time left on your subscription\n"
if(config.mapMain.enabled == "yes") {
cmds += "`" + config.cmdPrefix + "map` \\\u00BB a link to our web map\n"
}
if(config.paypal.enabled == "yes") {
cmds += "`" + config.cmdPrefix + "paypal` \\\u00BB for a link to our PayPal\n"
}
}
c.send(cmds).then((message) => {
message.delete({
timeout: 10000
});
}).catch(err => {console.error(GetTimestamp()+err);});
return;
}
// ######################### PAYPAL/SUBSCRIBE ########################
if(command === "paypal") {
if(config.paypal.enabled != "yes") {
return;
}
let embedMSG = {
'color': 0xFF0000,
'title': 'Please visit PayPal to donate',
'url': config.paypal.url,
'thumbnail': {
'url': config.paypal.img
},
'description': 'Thank you! \nYour support is greatly appreciated.'
};
message.delete();
m.send({ embed: embedMSG }).catch(err => {console.error(GetTimestamp()+err);});
return;
}
// ############################## TEMPORARY ROLES ##############################
if(command === "tr" || command === "temprole") {
// ROLES ARE CASE SENSITIVE TO RESET MESSAGE AND ARGUMENTS
msg = message.content;
args = msg.split(" ").slice(1);
if(m.roles.cache.has(ModR.id) || m.roles.cache.has(AdminR.id) || m.id === config.ownerID) {
if(!args[0]) {
message.reply("syntax:\n `" + config.cmdPrefix + "temprole @mention <DAYS> <ROLE-NAME>`,\n or `" + config.cmdPrefix + "temprole remove @mention role`\n or `" + config.cmdPrefix + "temprole check @mention role`");
return;
}
else if(!mentioned) {
message.reply("please `@mention` a person you want me to check/add/remove a role for");
return;
}
else if(!args[2]) {
message.reply("incomplete data, please try: \n `" + config.cmdPrefix + "temprole @mention <DAYS> <ROLE-NAME>`,\n `" + config.cmdPrefix + "temprole remove @mention role`\n `" + config.cmdPrefix + "temprole check @mention role`\n `" + config.cmdPrefix + "temprole add @mention role 2`");
return;
}
else {
// ROLES WITH SPACES
let daRole = "";
let days = 0;
if(args[0] === "add") {
// Count args and the last is the days then 2-x are roles
for(var x = 2; x < args.length - 1; x++) {
daRole += args[x] + " ";
}
daRole = daRole.slice(0, -1);
days = args[args.length - 1]
}
else {
for(var x = 2; x < args.length; x++) {
daRole += args[x] + " ";
}
daRole = daRole.slice(0, -1);
}
// CHECK ROLE EXIST
let rName = g.roles.cache.find(rName => rName.name === daRole);
if(!rName) {
message.reply("I couldn't find such role, please check the spelling and try again.");
return;
}
// CHECK DATABASE FOR ROLES
if(args[0] === "check") {
await query(`SELECT * FROM temporary_roles WHERE userID="${mentioned.id}" AND temporaryRole="${daRole}"`)
.then(async row => {
if(!row[0]) {
message.reply("⚠ [ERROR] " + mentioned.username + " is __NOT__ in the database for the role " + daRole);
return;
}
let startDateVal = new Date();
startDateVal.setTime(row[0].startDate * 1000);
let startDateTime = await formatTimeString(startDateVal);
let endDateVal = new Date();
endDateVal.setTime(row[0].endDate * 1000);
let finalDate = await formatTimeString(endDateVal);
c.send("✅ " + mentioned.username + " will lose the role: **" + row[0].temporaryRole +
"** on: `" + finalDate + "`! They were added on: `" + startDateTime + "`");
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query 9: (${err})`);
return;
});
return;
}
// REMOVE MEMBER FROM DATABASE
else if(args[0] === "remove") {
mentioned = message.mentions.members.first(); // Changed mentioned here because we need the members object
await query(`SELECT * FROM temporary_roles WHERE userID="${mentioned.id}" AND temporaryRole="${daRole}"`)
.then(async row => {
if(!row[0]) {
c.send("⚠ [ERROR] " + mentioned.user.username + " is __NOT__ in the database for the role " + daRole);
return;
}
let theirRole = g.roles.cache.find(theirRole => theirRole.name === row[0].temporaryRole);
mentioned.roles.remove(theirRole).catch(err => {console.error(GetTimestamp()+err);});
await query(`DELETE FROM temporary_roles WHERE userID="${mentioned.id}" AND temporaryRole="${daRole}"`)
.then(async result => {
console.log(GetTimestamp() + "[ADMIN] [TEMPORARY-ROLE] " + m.user.username + " (" + m.id + ")" + " removed the \"" + daRole + "\" role from \"" + mentioned.user.username + "\" (" + mentioned.id + ")");
c.send("⚠ " + mentioned.user.username + " has **lost** their role of: **" + theirRole.name + "** and has been removed from the database");
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query 11: (${err})`);
return;
});
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query 10: (${err})`);
return;
});
return;
}
// ADD TIME TO A USER
else if(args[0] === "add") {
if(!daRole) {
message.reply("What role do you want to add time to?");
return;
}
if(!Number(days)) {
message.reply("Error: The third value after the command has to be **X** number of days: `" + config.cmdPrefix + "tr add @" + mentioned.username + " Role 30`");
return;
}
await query(`SELECT * FROM temporary_roles WHERE userID="${mentioned.id}" AND temporaryRole="${daRole}"`)
.then(async row => {
if(!row[0]) {
c.send("⚠ [ERROR] " + mentioned.username + " is __NOT__ in the database for the role " + daRole);
return;
}
let startDateVal = new Date();
startDateVal.setTime(row[0].startDate * 1000);
let startDateTime = await formatTimeString(startDateVal);
let finalDate = Number(row[0].endDate * 1000) + Number(days * dateMultiplier);
let name = mentioned.username.replace(/[^a-zA-Z0-9]/g, '');
await query(`UPDATE temporary_roles SET endDate="${Math.round(finalDate / 1000)}", notified=0, username="${name}" WHERE userID="${mentioned.id}" AND temporaryRole="${daRole}"`)
.then(async result => {
let endDateVal = new Date();
endDateVal.setTime(finalDate);
finalDate = await formatTimeString(endDateVal);
console.log(GetTimestamp() + "[ADMIN] [TEMPORARY-ROLE] \"" + mentioned.username + "\" (" + mentioned.id + ") was given " + days + " days by: " + m.user.username + " (" + m.id + ") for the role: "+daRole);
c.send("✅ " + mentioned.username + " has had time added until: `" + finalDate + "`! They were added on: `" + startDateTime + "`");
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query 14: (${err})`);
return;
});
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query 13: (${err})`);
return;
});
return;
}
else {
if(!Number(args[1])) {
message.reply("Error: Second value after the command has to be **X** number of days, IE:\n`" + config.cmdPrefix + command + " @" + mentioned.username + " 90 Role`");
return;
}
// ADD MEMBER TO DATASE, AND ADD THE ROLE TO MEMBER
await query(`SELECT * FROM temporary_roles WHERE userID="${mentioned.id}" AND temporaryRole="${daRole}"`)
.then(async row => {
mentioned = message.mentions.members.first();
if(!row[0]) {
let curDate = new Date().getTime();
let finalDateDisplay = new Date();
let finalDate = curDate + (Number(args[1]) * dateMultiplier);
finalDateDisplay.setTime(finalDate);
finalDateDisplay = await formatTimeString(finalDateDisplay);
let name = mentioned.user.username.replace(/[^a-zA-Z0-9]/g, '');
let values = mentioned.user.id+',\''
+daRole+'\','
+Math.round(curDate/1000)+','
+Math.round(finalDate/1000)+','
+m.id
+', 0'+',\''
+name+'\', 0';
await query(`INSERT INTO temporary_roles VALUES(${values});`)
.then(async result => {
let theirRole = g.roles.cache.find(theirRole => theirRole.name === daRole);
mentioned.roles.add(theirRole).catch(err => {console.error(GetTimestamp()+err);});
console.log(GetTimestamp() + "[ADMIN] [TEMPORARY-ROLE] \"" + mentioned.user.username + "\" (" +
mentioned.user.id + ") was given the \"" + daRole + "\" role by " + m.user.username + " (" + m.id + ")");
c.send("🎉 " + mentioned.user.username + " has been given a **temporary** role of: **" + daRole +
"**, enjoy! They will lose this role on: `" + finalDateDisplay + "`");
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query 16: (${err})`);
return;
});
}
else {
message.reply("This user already has the role **" + daRole + "** try using `" + config.cmdPrefix + "temprole remove @" + mentioned.user.username + " " + daRole + "` if you want to reset their role.");
}
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query 15: (${err})`);
return;
});
}
}
}
else {
message.delete();
message.reply("You are **NOT** allowed to use this command!").then((message) => {
message.delete({
timeout: 10000
});
}).catch(err => {console.error(GetTimestamp()+err);});
return;
}
}
// ############################## Delete Messages ##############################
if(command === "message" || command === "messages") {
msg = message.content;
args = msg.split(" ").slice(1);
if(m.roles.cache.has(ModR.id) || m.roles.cache.has(AdminR.id) || m.id === config.ownerID) {
/*let channels = bot.channels.array();
for (const channel of channels.values())
{
console.log(channel.guild + "," + channel.parent + "," + channel.name + "," + channel.id);
}*/
let MinSeconds = 0;
let MaxSeconds = 999999999;
if(args[0]) {
MinSeconds = args[0];
}
if(args[1]) {
MaxSeconds = args[1];
}
message.delete();
DeleteBulkMessages(c, MinSeconds, MaxSeconds);
}
else {
message.delete();
message.reply("You are **NOT** allowed to use this command!").then((message) => {
message.delete({
timeout: 10000
});
}).catch(err => {console.error(GetTimestamp()+err);});
return;
}
}
// ############################## Restart Bot ##############################
if(command === "restart") {
if(m.roles.cache.has(ModR.id) || m.roles.cache.has(AdminR.id) || m.id === config.ownerID) {
RestartBot("manual");
}
else {
message.delete();
message.reply("You are **NOT** allowed to use this command!").then((message) => {
message.delete({
timeout: 10000
});
}).catch(err => {console.error(GetTimestamp()+err);});
return;
}
}
// ############################## CHECK ##############################
if(command === "check") {
let dateMultiplier = 86400000;
msg = message.content;
args = msg.split(" ").slice(1);
if(!args[0]) {
message.delete();
m.send("Please enter the role you want to check like `" + config.cmdPrefix + "check Trainer`");
return;
}
// ROLES WITH SPACES
let daRole = "";
for(var x = 0; x < args.length; x++) {
daRole += args[x] + " ";
}
daRole = daRole.slice(0, -1);
// CHECK ROLE EXIST
let rName = g.roles.cache.find(rName => rName.name === daRole);
if(!rName) {
message.reply("I couldn't find such role, please check the spelling and try again.");
return;
}
// CHECK DATABASE FOR ROLES
await query(`SELECT * FROM temporary_roles WHERE userID="${m.id}" AND temporaryRole="${daRole}"`)
.then(async row => {
if(!row[0]) {
message.delete();
m.send("⚠ [ERROR] " + m.user.username + " is __NOT__ in the database for the role " + daRole);
return;
}
let startDateVal = new Date();
startDateVal.setTime(row[0].startDate*1000);
let startDateTime = await formatTimeString(startDateVal);
let endDateVal = new Date();
endDateVal.setTime(row[0].endDate*1000);
let finalDate = await formatTimeString(endDateVal);
message.delete();
m.send("✅ You will lose the role: **" + row[0].temporaryRole + "** on: `" + finalDate + "`! The role was added on: `" + startDateTime + "`");
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query 8: (${err})`);
return;
});
return;
}
// ######################### MAP ###################################
if(command === "map") {
if(config.mapMain.enabled != "yes") {
return;
}
message.delete();
m.send("Our official webmap: \n<" + config.mapMain.url + ">").catch(err => {console.error(GetTimestamp()+err);});
return;
}
});
// Check for bot events other than messages
bot.on('guildMemberRemove', async member => {
// Used to note database entries when users leave the server.
let guild = member.guild.id;
if(guild != config.serverID) {
return;
}
// Check if the user had any temp roles
await query(`SELECT * FROM temporary_roles WHERE userID="${member.id}"`)
.then(async rows => {
// Update all entries from the database
if (rows[0]) {
await query(`UPDATE temporary_roles SET leftServer = 1 WHERE userID="${member.id}"`)
.then(async result => {
let name = member.user.username.replace(/[^a-zA-Z0-9]/g, '');
console.log(GetTimestamp() + "[ADMIN] [TEMPORARY-ROLE] \"" + name + "\" (" + member.id + ") has left the server. All temp role assignments have been marked in the database.");
bot.channels.cache.get(config.mainChannelID).send(":exclamation: " + name + " has left the server. All temp role assignments have been marked in the database.");
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query in guildMemberRemove 2: (${err})`);
return;
});
}
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query in guildMemberRemove 1: (${err})`);
return;
});
});
bot.on('guildMemberAdd', async member => {
// Add the role from the DB if they rejoin the server
if (config.restoreRoleOnJoin != "yes") {
return;
}
let guild = member.guild.id;
if(guild != config.serverID) {
return;
}
// Check the DB is the user has any entries
await query(`SELECT * FROM temporary_roles WHERE userID="${member.id}"`)
.then(async rows => {
if(!rows[0]) {
// No entries found so no temp roles to assign
return;
}
// Iterate the rows and add the appropriate role to the user
for(let rowNumber = "0"; rowNumber < rows.length; rowNumber++) {
let rName = bot.guilds.cache.get(config.serverID).roles.cache.find(rName => rName.name === rows[rowNumber].temporaryRole);
member.roles.add(rName).then(async member => {
let name = member.user.username.replace(/[^a-zA-Z0-9]/g, '');
console.log(GetTimestamp() + "[ADMIN] [TEMPORARY-ROLE] \"" + name + "\" (" + member.id + ") has rejoined the server. The " + rName.name + " temp role has been readded.");
bot.channels.cache.get(config.mainChannelID).send(":white_check_mark: " + name + " has rejoined the server. The " + rName.name + " temp role has been readded.");
// Update the database in case they were marked as leftServer
await query(`UPDATE temporary_roles SET leftServer = 0 WHERE userID='${member.id}' AND temporaryRole='${rName.name}'`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query in guildMemberAdd 2: (${err})`);
process.exit(-1);
});
}).catch(error => {
console.error(GetTimestamp() + error.message);
bot.channels.cache.get(config.mainChannelID).send("**⚠ Could not add the " + rName.name + " role to " + member.user.username + "!**")
.catch(err => {console.error(GetTimestamp()+err);});
});
}
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query in guildMemberAdd 1: (${err})`);
return;
});
});
bot.on('guildMemberUpdate', async (oldMember, newMember) => {
// Used to stop users from adding roles without a database entry
if (config.blockManualRoles != "yes") {
return;
}
let guild = newMember.guild.id;
if(guild != config.serverID) {
return;
}
if(JSON.stringify(oldMember._roles) != JSON.stringify(newMember._roles)) {
// If the arrays are different, check what role was added
for(let num = "0"; num < newMember._roles.length; num++) {
if (!oldMember._roles.includes(newMember._roles[num])) {
if (config.blockTheseRoles[0]) {
if (!config.blockTheseRoles.includes(newMember._roles[num])) {
continue;
}
}
// If the role is not on the block list or there isn't a block list, check the database
let rName = bot.guilds.cache.get(config.serverID).roles.cache.find(rName => rName.id === newMember._roles[num]);
await wait(1 * 1000);
await query(`SELECT * FROM temporary_roles WHERE userID="${newMember.user.id}" and temporaryRole="${rName.name}" LIMIT 1`)
.then(async rows => {
if(!rows[0]) {
// No entry so remove the role from the user
newMember.roles.remove(rName).then(async member => {
bot.channels.cache.get(config.mainChannelID).send("⚠ " + member.user.username + " has **lost** their role of: **" +
rName.name + "** - it was manually added when that wasn't allowed").catch(err => {console.error(GetTimestamp()+err);});
console.log(GetTimestamp() + "[ADMIN] [TEMPORARY-ROLE] \"" + member.user.username + "\" (" + member.id +
") have lost their role: " + rName.name + "... it was manually added when that wasn't allowed");
}).catch(error => {
console.error(GetTimestamp() + error.message);
bot.channels.cache.get(config.mainChannelID).send("**⚠ Could not remove the " +
rName.name + " role from " + newMember.user.username + "!**").catch(err => {console.error(GetTimestamp()+err);});
});
}
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute query in guildMemberUpdate 1: (${err})`);
return;
});
}
}
}
});
bot.on('error', function(err) {
if(typeof err == 'object') {
err = JSON.stringify(err);
}
console.error(GetTimestamp() + 'Uncaught exception (error): ' + err);
RestartBot();
return;
});
bot.on('disconnect', function(closed) {
console.error(GetTimestamp() + 'Disconnected from Discord');
return;
});
function GetTimestamp() {
let now = new Date();
return "[" + now.toLocaleString() + "] ";
}
function RestartBot(type) {
if(type == 'manual') {
process.exit(1);
}
else {
console.error(GetTimestamp() + "Unexpected error, bot stopping, likely websocket");
process.exit(1);
}
return;
}
async function InitDB() {
// Create MySQL tabels
let currVersion = 5;
let dbVersion = 0;
await query(`CREATE TABLE IF NOT EXISTS metadata (
\`key\` VARCHAR(50) PRIMARY KEY NOT NULL,
\`value\` VARCHAR(50) DEFAULT NULL);`)
.then(async x => {
await query(`SELECT \`value\` FROM metadata WHERE \`key\` = "DB_VERSION" LIMIT 1;`)
.then(async result => {
//Save the DB version if one is returned
if (result.length > 0) {
dbVersion = parseInt(result[0].value);
}
console.log(GetTimestamp()+`[InitDB] DB version: ${dbVersion}, Latest: ${currVersion}`);
if (dbVersion < currVersion) {
for (dbVersion; dbVersion < currVersion; dbVersion++) {
if (dbVersion == 0) {
// Setup the temp roles table
console.log(GetTimestamp()+'[InitDB] Creating the initial tables');
await query(`CREATE TABLE IF NOT EXISTS temporary_roles (
userID bigint(19) unsigned NOT NULL,
temporaryRole varchar(35) NOT NULL,
startDate int(11) unsigned NOT NULL,
endDate int(11) unsigned NOT NULL,
addedBy bigint(19) unsigned NOT NULL,
notified tinyint(1) unsigned DEFAULT 0)`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}b: (${err})`);
process.exit(-1);
});
// Migrate the old sqlite entries into the table
sql.all(`SELECT * FROM temporary_roles`, (err, rows) => {
if (err) {
console.error(GetTimestamp() + err.message);
}
else if (rows) {
for(rowNumber = 0; rowNumber < rows.length; rowNumber++) {
let values = rows[rowNumber].userID+',\''
+rows[rowNumber].temporaryRole+'\','
+Math.round(rows[rowNumber].startDate/1000)+','
+Math.round(rows[rowNumber].endDate/1000)+','
+rows[rowNumber].addedBy+','
+rows[rowNumber].notified;
query(`INSERT INTO temporary_roles VALUES(${values});`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}c: (${err})`);
process.exit(-1);
});
}
}
});
await query(`INSERT INTO metadata (\`key\`, \`value\`) VALUES("DB_VERSION", ${dbVersion+1}) ON DUPLICATE KEY UPDATE \`value\` = ${dbVersion+1};`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}a: (${err})`);
process.exit(-1);
});
console.log(GetTimestamp()+'[InitDB] Migration #1 complete.');
}
else if (dbVersion == 1) {
// Wait 30 seconds and let user know we are about to migrate the database and for them to make a backup until we handle backups and rollbacks.
console.log(GetTimestamp()+'[InitDB] MIGRATION IS ABOUT TO START IN 30 SECONDS, PLEASE MAKE SURE YOU HAVE A BACKUP!!!');
await wait(30 * 1000);
await query(`ALTER TABLE temporary_roles
ADD COLUMN username varchar(35) DEFAULT NULL;`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}b: (${err})`);
process.exit(-1);
});
await query(`ALTER TABLE \`temporary_roles\` COLLATE='utf8mb4_general_ci', CONVERT TO CHARSET utf8mb4;`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}c: (${err})`);
process.exit(-1);
});
await query(`ALTER TABLE \`metadata\` COLLATE='utf8mb4_general_ci', CONVERT TO CHARSET utf8mb4;`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}d: (${err})`);
process.exit(-1);
});
await query(`INSERT INTO metadata (\`key\`, \`value\`) VALUES("DB_VERSION", ${dbVersion+1}) ON DUPLICATE KEY UPDATE \`value\` = ${dbVersion+1};`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}a: (${err})`);
process.exit(-1);
});
console.log(GetTimestamp()+'[InitDB] Migration #2 complete.');
}
else if (dbVersion == 2) {
// Wait 30 seconds and let user know we are about to migrate the database and for them to make a backup until we handle backups and rollbacks.
console.log(GetTimestamp()+'[InitDB] MIGRATION IS ABOUT TO START IN 30 SECONDS, PLEASE MAKE SURE YOU HAVE A BACKUP!!!');
await wait(30 * 1000);
await query(`CREATE TABLE IF NOT EXISTS paypal_info (
invoice varchar(32) NOT NULL,
userID bigint(19) unsigned NOT NULL,
orderDate int(11) unsigned NOT NULL,
temporaryRole varchar(35) DEFAULT NULL,
days tinyint(3) unsigned DEFAULT NULL,
order_id varchar(20) NOT NULL,
order_json longtext DEFAULT NULL,
order_verified tinyint(1) unsigned NOT NULL DEFAULT 0,
payment_verified tinyint(1) unsigned NOT NULL DEFAULT 0,
fulfilled tinyint(1) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (\`invoice\`))`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}b: (${err})`);
process.exit(-1);
});
await query(`ALTER TABLE \`temporary_roles\` ADD PRIMARY KEY (\`userID\`, \`temporaryRole\`);`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}c: (${err})`);
process.exit(-1);
});
await query(`ALTER TABLE \`metadata\` COLLATE='utf8mb4_general_ci', CONVERT TO CHARSET utf8mb4;`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}d: (${err})`);
process.exit(-1);
});
await query(`INSERT INTO metadata (\`key\`, \`value\`) VALUES("DB_VERSION", ${dbVersion+1}) ON DUPLICATE KEY UPDATE \`value\` = ${dbVersion+1};`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}a: (${err})`);
process.exit(-1);
});
console.log(GetTimestamp()+'[InitDB] Migration #3 complete.');
}
else if (dbVersion == 3) {
// Wait 30 seconds and let user know we are about to migrate the database and for them to make a backup until we handle backups and rollbacks.
console.log(GetTimestamp()+'[InitDB] MIGRATION IS ABOUT TO START IN 30 SECONDS, PLEASE MAKE SURE YOU HAVE A BACKUP!!!');
await wait(30 * 1000);
await query(`ALTER TABLE \`temporary_roles\` ADD COLUMN leftServer tinyint(1) unsigned DEFAULT 0;`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}b: (${err})`);
process.exit(-1);
});
await query(`INSERT INTO metadata (\`key\`, \`value\`) VALUES("DB_VERSION", ${dbVersion+1}) ON DUPLICATE KEY UPDATE \`value\` = ${dbVersion+1};`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}a: (${err})`);
process.exit(-1);
});
console.log(GetTimestamp()+'[InitDB] Migration #4 complete.');
}
else if (dbVersion == 4) {
// Wait 30 seconds and let user know we are about to migrate the database and for them to make a backup until we handle backups and rollbacks.
console.log(GetTimestamp()+'[InitDB] MIGRATION IS ABOUT TO START IN 30 SECONDS, PLEASE MAKE SURE YOU HAVE A BACKUP!!!');
await wait(30 * 1000);
await query(`ALTER TABLE \`paypal_info\` ADD COLUMN rejection tinyint(1) unsigned DEFAULT 0;`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}b: (${err})`);
process.exit(-1);
});
await query(`INSERT INTO metadata (\`key\`, \`value\`) VALUES("DB_VERSION", ${dbVersion+1}) ON DUPLICATE KEY UPDATE \`value\` = ${dbVersion+1};`)
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to execute migration query ${dbVersion}a: (${err})`);
process.exit(-1);
});
console.log(GetTimestamp()+'[InitDB] Migration #5 complete.');
}
}
console.log(GetTimestamp()+'[InitDB] Migration process done.');
}
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to get version info: (${err})`);
process.exit(-1);
});
})
.catch(err => {
console.error(GetTimestamp()+`[InitDB] Failed to create metadata table: (${err})`);
process.exit(-1);
});
}
async function DeleteBulkMessages(channel, MinSeconds, MaxSeconds = 999999999) {
let MinFlake = GetSnowFlake(MinSeconds);
let MaxFlake = GetSnowFlake(MaxSeconds);
let TwoWeeks = GetSnowFlake(1209600);
if(MaxFlake < 0) {
MaxFlake = 0
}
if(!channel) {
console.error(GetTimestamp() + "Could not find a channel");
return;
}
channel.messages.fetch({
limit: 99,
after: MaxFlake,
before: MinFlake
}).then(async messages => {
let filterMessages = []
for(const message of messages.values()) {
if(message.id > TwoWeeks && message.id < MinFlake && !message.deleted) {
filterMessages.push(message)
}
}
// Check if the messages between the min/max are in the 2-week range
if(filterMessages.length > 0) {
channel.bulkDelete(filterMessages).then(async deleted => {
await wait(4000);
DeleteBulkMessages(channel, MinSeconds, MaxSeconds);
}).catch(async error => {
console.error(GetTimestamp() + "Failed to bulk delete messages in " + channel.name + ". Trying single message delete.");
await wait(4000);
DeleteSingleMessages(channel, MinSeconds, MaxSeconds);
return;
});
}
// Check if there are still messages left in the fetch
else if(filterMessages.length == 0 && messages.size > 0) {
await wait(4000);
DeleteSingleMessages(channel, MinSeconds, MaxSeconds);
}
}).catch(error => {
console.error(GetTimestamp() + "Failed to bulk delete messages in " + channel.name + ". Trying single message delete.");
DeleteSingleMessages(channel, MinSeconds, MaxSeconds);
return;
});
}
async function DeleteSingleMessages(channel, MinSeconds, MaxSeconds = 999999999) {
let MinFlake = GetSnowFlake(MinSeconds);
let MaxFlake = GetSnowFlake(MaxSeconds);
if(MaxFlake < 0) {
MaxFlake = 0
}
channel.messages.fetch({
limit: 99,