forked from saacki/isacbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
isac-bot.js
1789 lines (1561 loc) · 75.2 KB
/
isac-bot.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
/******************************
Prod / Dev
*******************************/
const config = require('./config').production;
/******************************
Variables & Libs
*******************************/
const lodash = require('lodash');
const axios = require('axios');
const pool = config.getPool();
const moment = require("moment");
const Discord = require("discord.js");
const client = new Discord.Client();
const DBL = require("dblapi.js");
const dbl = new DBL(config.topGGtoken, client);
const helper = require("./helper.js");
const Hashids = require('hashids/cjs');
const scriptName = __filename.slice(__dirname.length + 1);
const useTrackerGG = true;
const embedFooter = 'via ubisoftconnect.com | repo.sachi.lk';
const embedFooterImg = 'https://repo.sachi.lk/isac/assets/img/logo.png';
// Possible commands
const commands = [
'register',
'unregister',
'autodelete',
'agent',
'dz',
'exp',
'darkzone',
'rank',
'platform',
'pve',
'weapons',
'help',
'isac',
'clan',
'donate',
'update_nicknames',
'obey'
];
// Possible parameters for !rank
const rankedData = [
'playtime',
'ecredit',
'gearscore',
'commendation',
'cxp',
'clanexp',
'cxp24h',
'clanexp24h',
'cxp7d',
'clanexp7d',
'cxp30d',
'clanexp30d'
];
// Possible parameters for !platform
const platforms = ['uplay', 'psn', 'xbl'];
const platformsMap = {
'uplay': 'PC/Uplay',
'psn': 'Playstation',
'xbl': 'Xbox'
}
/******************************
Errors
*******************************/
const UNABLE_TO_FIND_AGENT_ERR = "Error: Unable to locate Agent `%AGENT_NAME%` on platform `%SERVER_PLATFORM%`."; // 1
const AGENT_REGISTRATION_NOT_FOUND_ERR = "Error: Agent registration not found. Register with `!register agent_id`"; // 2
const INVALID_LEADERBOARD_TYPE_ERR = "Error: Please enter a valid leaderboard. \nOptions available: _" + rankedData.join(', ') + "_"; // 3
const INVALID_PLATFORM_TYPE_ERR = "Error: Please enter a valid platform. \nOptions available: _" + platforms.join(', ') + "_"; // 4
const NOT_ADMIN_PERMISSION_ERR = 'Error: This command is only valid for server admins of `%SERVER_NAME%`.'; // 5
const MISSING_PERMISSION_ERR = 'Error: The bot is missing permissions required to send a reply to the channel.'; // 6
const ROLE_NOT_FOUND_ERR = 'Error: The role `%ROLE_ARG%` does not exist.'; // 7
const INVALID_AUTO_DELETE_TYPE_ERR = "Error: Please enter a valid auto delete option. \nOptions available: _on, off_"; // 8
/******************************
Bot Auth
*******************************/
if( scriptName == 'sachi.js' ) {
client.login(config.devBotToken);
console.log("----- DEVELOPMENT BOT -----");
}
else {
client.login(config.botToken);
console.log("----- PRODUCTION BOT -----");
}
/******************************
Event Listeners
*******************************/
client.on("error", (e) => console.error(e));
client.on("warn", (e) => console.warn(e));
// client.on("debug", (e) => console.info(e));
client.on("guildCreate", async function(guild) {
helper.printStatus("Joined a new guild: " + guild.name);
});
client.on("ready", async function() {
helper.printStatus("I am ready!");
let statuses = [
'!agent',
'!weapons',
'!pve',
'!exp',
'!dz',
'!register',
'!rank',
'!help',
'!platform',
'!isac',
'!donate'
];
client.user.setPresence({ activity: { name: '!agent', type: "PLAYING"}, status: 'online'});
// random status message every 5s
client.setInterval(function(){
client.user.setPresence({ activity: { name: statuses[Math.floor(Math.random() * statuses.length)], type: "PLAYING"}, status: 'online'});
}, 5000);
});
dbl.on('posted', () => {
helper.printStatus('Server count posted to top.gg!');
});
/******************************
Message Listener
*******************************/
client.on("message", async function(message) {
if ( message.author.bot ) return; // Ignore bot messages
if ( !message.channel.guild ) return; // Ignore dm
let original_message = message.content;
message.content = message.content.replace(/“/g, '"').replace(/”/g, '"').toLowerCase();
const prefix = await getServerPrefix(message.guild.id);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
let server_platform = await getServerPlatform(message.guild.id);
let isAdmin = helper.isAdmin(message.member);
let owner = helper.owner(message.member);
let playerData = {};
message.autoDelete = await isServerAutoDelete(message.guild.id);
if( command != 'isac' && prefix != message.content.charAt(0) ) return; // ignore if prefix don't match EXCEPT for isac command
if( commands.includes(command) == false ) return; // Ignore commands not in "commands" array
if( message.autoDelete ) message.delete({ timeout: 15000 }); // Delete Author's Msg
message.logCommandID = await helper.logCommands(message); // log command to DB and return entry ID
// Output Commands Sent To Log
console.log("----------------------------------------------");
helper.printStatus( "Server: " + message.guild.name );
helper.printStatus( "Message: " + message.content );
helper.printStatus( "Author: " + message.author.username );
helper.printStatus( "Server Platform: " + server_platform );
helper.printStatus( "Is Admin: " + isAdmin );
helper.printStatus( "Auto Delete: " + message.autoDelete );
helper.printStatus( "Use Tracker GG: " + useTrackerGG );
console.log("----------------------------------------------");
updateServerInfo(message.guild.id, message.guild.name); // Create new server info and/or update last active time
let apiSearchURL = config.apiSearchBaseURL + "platform=" + server_platform + "&name=";
if( useTrackerGG ) {
apiSearchURL = config.apiSearchBaseURL_TGG + server_platform + "/";
}
/***********************************
// SERVER PREFIX
************************************/
if ( command === "isac" ) {
if( args.length > 0 ) {
if( isAdmin ) {
if( args[0] == 'prefix' ) {
if( args.length == 1 ) {
message.channel.send("The server prefix for ISAC is: " + prefix).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
else {
if( args[1].length == 1 ) {
setServerPrefix(message.guild.id, args[1]);
message.channel.send("The server's prefix for ISAC is now: " + args[1]).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
else {
message.channel.send("Error: Changing server's prefix to " + args[1] + " failed. You can only set the server's prefix to a single character. Example: !, @, #, $").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
}
}
}
}
return;
}
/***********************************
// FANCY CODE
************************************/
if ( command === "obey" ) {
if ( owner ){
message.channel.send("hi my owner! :) sachii#0001")
return;
}
else {
message.channel.send("you are not my owner!")
return;
}
}
/***********************************
// AUTO DELETE
************************************/
if ( command === "autodelete" ) {
if( args.length > 0 ) {
if( isAdmin ) {
if( args[0] == 'on' ) {
pool.query("UPDATE servers SET auto_delete = 1 WHERE server_id = ?", [message.guild.id]);
message.autoDelete = true;
message.delete({ timeout: 15000 });
message.channel.send("Auto deleting of messages is now enabled (15 seconds)").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
return;
}
else if( args[0] == 'off' ) {
pool.query("UPDATE servers SET auto_delete = 0 WHERE server_id = ?", [message.guild.id]);
message.autoDelete = false;
message.channel.send("Auto deleting of messages is now disabled");
return;
}
}
}
message.channel.send( getErrorMessage(8) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
return;
}
/*************************************************
// CHANGE NICKNAMES OF USERS TO THEIR AGENT NAMES
*************************************************/
if ( command === "update_nicknames" ) {
let members = [];
if( isAdmin ) {
await message.channel.guild.members.fetch().then(async function(guild){
// exclude server owner as bot can't change owner's nickname
members = message.guild.members.cache.filter(function(member){ return member.user.bot === false && member.user.id != member.guild.ownerID })
.map(function(member){ return {id: member.user.id, nickname: member.nickname, member: member} });
if(members.length > 0) {
let success = [];
let failure = [];
for(var i=0; i<members.length; i++) {
await pool.query("SELECT * FROM users WHERE user_id = ?", [members[i].id]).then(async function(res){
if( res.length > 0 ) {
await members[i].member.setNickname(res[0].agent_name)
.then(function(member){
console.log("Updated nickname of: " + member.displayName + " to " + res[0].agent_name);
success.push(res[0].agent_name);
})
.catch(function(err){
console.log("Unable to update nickname of: " + members[i].member.displayName);
console.log("Reason: " + err.message + "\n");
failure.push(res[0].agent_name);
});
}
});
}
if( success.length > 0 )
message.channel.send("Successfully updated nicknames in " + message.guild.name + ": `" + success.join(', ') + "`").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
});
}
return;
}
/*************************************************
// CLAN COMMANDS
*************************************************/
if ( command === "clan" ) {
if( isAdmin ) {
if( args.length > 0 ) {
if( args[0] == 'removerole' ) {
pool.query("UPDATE servers SET clan_role_id = ? WHERE server_id = ?", ['', message.guild.id]);
message.channel.send("Clan role has been removed.").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
if( args[0] == 'role' ) {
if( args.length > 1 ) {
let role_arg = original_message.slice(prefix.length).replace(command, '').replace(args[0], '').trim(); // args without lowercase and space in between
let role_search = message.guild.roles.cache.filter(function(role){ return role.name == role_arg });
if( lodash.isEmpty(role_search) == false ) {
let clan_role_id = role_search.map(function(role){ return role.id })[0];
pool.query("UPDATE servers SET clan_role_id = ? WHERE server_id = ?", [clan_role_id, message.guild.id]);
message.channel.send("Clan role has been set to " + role_arg+".").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
else {
message.channel.send( getErrorMessage(7, {role: role_arg}) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
}
else {
pool.query("SELECT * FROM servers WHERE server_id = ?", [message.guild.id]).then(function(res){
if( res.length > 0 ) {
if( res[0].clan_role_id ) {
current_clan_role = message.guild.roles.cache.filter(function(role){ return role.id == res[0].clan_role_id });
if( current_clan_role ) {
message.channel.send("The current clan role is set to " + current_clan_role.values().next().value.name + ". !rank will only display results where members are of this role or have been manually added.").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
}
else {
message.channel.send("No clan role has been set.").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
}
});
}
}
// list manually added clan agents
if( args[0] == 'list' ) {
manual_agents = await pool.query("SELECT * FROM server_agents WHERE server_id = ?", [message.guild.id]).then(function(res){
if( res.length > 0 ) {
return res.map(function(res){ return {id: res.agent_id, name: res.agent_name} });
}
else {
return [];
}
});
if( lodash.isEmpty(manual_agents) == false ) {
manual_agent_names = manual_agents.map(function(agent){ return agent.name });
let embed = new Discord.MessageEmbed()
.setTitle("Manually added agents for " + message.guild.name)
.setColor("#FF6D10")
.setFooter(embedFooter, embedFooterImg);
embed.setDescription(manual_agent_names.sort().join('\n'));
message.channel.send(embed).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
else {
message.channel.send("No agents have been manually added for this clan yet.").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
}
if( args[0] == 'add' ) {
if( args.length > 1 ) {
let agent_name_arg = original_message.slice(prefix.length).replace(command, '').replace(args[0], '').trim(); // args without lowercase and space in between
if( useTrackerGG ) {
apiSearchURL = config.apiSearchBaseURL_TGG + server_platform + "/";
}
else {
apiSearchURL = config.apiSearchBaseURL + "platform=" + server_platform + "&name=";
}
// check if agent exists first
axios.get(apiSearchURL + agent_name_arg).then(async function(response){
if( response.status === 200 ) {
// account search results
if( useTrackerGG == false && response.data.results && response.data.results.length > 0 ) {
uplay_id = response.data.results[0].pid;
agent_name = response.data.results[0].name;
await pool.query("INSERT INTO server_agents (server_id, agent_name, agent_id, type, added_by_id, added_by_username, date_added) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE added_by_id = ?, added_by_username = ?, date_added = ?", [message.guild.id, agent_name, uplay_id, 'add', message.author.id, message.author.username, moment().format('YYYY-M-D HH:mm:ss'), message.author.id, message.author.username, moment().format('YYYY-M-D HH:mm:ss')]).then(async function(res){
message.channel.send("Agent " +agent_name_arg+ " manually added to clan list.").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
})
}
else if( useTrackerGG && response.data.data ) {
uplay_id = response.data.data.platformInfo.platformUserId;
agent_name = response.data.data.platformInfo.platformUserIdentifier;
await pool.query("INSERT INTO server_agents (server_id, agent_name, agent_id, type, added_by_id, added_by_username, date_added) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE added_by_id = ?, added_by_username = ?, date_added = ?", [message.guild.id, agent_name, uplay_id, 'add', message.author.id, message.author.username, moment().format('YYYY-M-D HH:mm:ss'), message.author.id, message.author.username, moment().format('YYYY-M-D HH:mm:ss')]).then(async function(res){
message.channel.send("Agent " +agent_name_arg+ " manually added to clan list.").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
})
}
else {
message.channel.send( getErrorMessage(1, {username: agent_name_arg, server_platform: server_platform}) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
}
});
}
}
if( args[0] == 'remove' ) {
if( args.length > 1 ) {
let agent_name_arg = original_message.slice(prefix.length).replace(command, '').replace(args[0], '').trim(); // args without lowercase and space in between
pool.query("DELETE FROM server_agents WHERE server_id = ? AND agent_name = ?", [message.guild.id, agent_name_arg]).then(function(res){
if( res.affectedRows > 0 ) {
message.channel.send("Manually added clan agent " + agent_name_arg + " removed.").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
else {
message.channel.send("Error: Unable to locate manually added clan agent by the name of " +agent_name_arg+ ".").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
});
}
}
}
}
else
message.author.send( getErrorMessage(5, {server_name: message.channel.guild}) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
/*************************************************
// HELP COMMANDS
*************************************************/
if ( command === "help" || command === "commands" ) {
message.author.send(config.helpTxt);
return;
}
/*************************************************
// DONATE COMMANDS
*************************************************/
if ( command === "donate" ) {
let donationTitle = "if you've found the bot useful and would like to donate, you can do so via ko-fi. donations will be used to cover server hosting fees. thank you agent!";
message.author.send(donationTitle);
let embed = new Discord.MessageEmbed()
.setTitle("one time donation :link:")
.setDescription('help me to cover my hosting fees')
.setColor("#a897e8")
.setURL('http://ko-fi.com/saacki')
.setThumbnail('https://storage.ko-fi.com/cdn/useruploads/0e9b66b6-125a-4781-9455-a5d60a779454.png');
message.author.send( embed );
return;
}
/*************************************************
// SET DEFAULT PLATFORM FOR SERVER
*************************************************/
if( command === 'platform' ) {
if( args.length == 0 ) {
message.channel.send("This Discord server's platform is currently: " + platformsMap[server_platform]).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
return;
}
if( args.length > 0 ) {
if( isAdmin ) {
if( platforms.includes(args[0]) ) {
await pool.query("INSERT INTO platforms (server_id, platform, date_added) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE platform = ?, date_added = ?", [message.guild.id, args[0], moment().format('YYYY-M-D HH:mm:ss'), args[0], moment().format('YYYY-M-D HH:mm:ss')]).then(async function(res){
message.channel.send("This Discord server's platform has been updated to: " + platformsMap[args[0]]).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
});
}
else {
message.channel.send( getErrorMessage(4) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
}
else {
message.author.send( getErrorMessage(5, {server_name: message.channel.guild}) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
}
}
/*************************************************
// REGISTER AGENT ID TO DISCORD USER
*************************************************/
if ( command === "register" ) {
if( args.length > 0 ) {
let username = args.join(' ');
// specific platform so doesn't use default server's
if( platforms.includes( args[0] ) ) {
username = args.slice(1).join(" ");
server_platform = args[0];
if( useTrackerGG ) {
apiSearchURL = config.apiSearchBaseURL_TGG + server_platform + "/";
}
else {
apiSearchURL = config.apiSearchBaseURL + "platform=" + server_platform + "&name=";
}
}
// search accounts
axios.get(apiSearchURL + username).then(async function(response){
if( response.status === 200 ) {
// account search results
if( useTrackerGG == false && response.data.results && response.data.results.length > 0 ) {
uplay_id = response.data.results[0].pid;
agent_name = response.data.results[0].name;
await pool.query("INSERT INTO users (user_id, uplay_id, agent_name, platform, date_added) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE uplay_id = ?, agent_name = ?, platform = ?, date_added = ?", [message.author.id, uplay_id, agent_name, server_platform, moment().format('YYYY-M-D HH:mm:ss'), uplay_id, agent_name, server_platform, moment().format('YYYY-M-D HH:mm:ss')]).then(async function(res){
message.channel.send("User <-> Agent registered. Fetching Agent stats.").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
playerData = await getPlayerData(uplay_id);
printAgentStat(message, playerData);
})
}
else if( useTrackerGG && response.data.data ) {
uplay_id = response.data.data.platformInfo.platformUserId;
agent_name = response.data.data.platformInfo.platformUserIdentifier;
await pool.query("INSERT INTO users (user_id, uplay_id, agent_name, platform, date_added) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE uplay_id = ?, agent_name = ?, platform = ?, date_added = ?", [message.author.id, uplay_id, agent_name, server_platform, moment().format('YYYY-M-D HH:mm:ss'), uplay_id, agent_name, server_platform, moment().format('YYYY-M-D HH:mm:ss')]).then(async function(res){
message.channel.send("User <-> Agent registered. Fetching Agent stats.").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
playerData = await getPlayerData(uplay_id, server_platform, agent_name);
printAgentStat(message, playerData);
})
}
else {
message.channel.send( getErrorMessage(1, {username: username, server_platform: server_platform}) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
}
})
.catch(function(error){
console.log(error);
message.channel.send( getErrorMessage(1, {username: username, server_platform: server_platform}) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
});
return;
}
message.channel.send( getErrorMessage(2) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
/*************************************************
// UNREGISTER AGENT ID
*************************************************/
if ( command === "unregister" ) {
await pool.query("DELETE FROM users WHERE user_id = ?", [message.author.id]).then(async function(res){
message.channel.send("User <-> Agent link removed.").then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
return;
});
}
/*************************************************
// GET PLAYER INFO
*************************************************/
if ( ['agent', 'weapons', 'pve', 'dz', 'darkzone', 'exp'].includes(command) ) {
if( args.length == 0 ) {
// query DB and checks if user has registered aka linked discord ID to uplay ID else send message prompting to register
await pool.query("SELECT * FROM users WHERE user_id = ?", [message.author.id]).then(async function(res){
if( res.length == 0 ) {
message.channel.send( getErrorMessage(2) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
else {
uplay_id = res[0].uplay_id;
platform = res[0].platform;
username = res[0].agent_name;
playerData = await getPlayerData(uplay_id, platform, username);
}
});
}
if( args.length > 0 ) {
let username = args.join(' ');
// @mentioneduser id instead of agent name
let isMentionedUser = false;
if( message.mentions.users.first() ) {
isMentionedUser = true;
agentID = await getMentionedUserAgentID( message.mentions.users.first() );
if( agentID ) {
username = agentID;
}
else {
message.channel.send( getErrorMessage(1, {username: message.mentions.users.first(), server_platform: server_platform}) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
return;
}
}
// specific platform so doesn't use default server's
if( platforms.includes( args[0] ) ) {
server_platform = args[0];
username = isMentionedUser ? username : args.slice(1).join(" ");
if( useTrackerGG ) {
apiSearchURL = config.apiSearchBaseURL_TGG + server_platform + "/";
}
else {
apiSearchURL = config.apiSearchBaseURL + "platform=" + server_platform + "&name=";
}
}
// search accounts
if( useTrackerGG ) {
playerData = await getPlayerData('', server_platform, username);
if( lodash.isEmpty(playerData) ) {
message.channel.send( getErrorMessage(1, {username: username, server_platform: server_platform}) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
}
else {
helper.printStatus("API Call @ Search Account: " + apiSearchURL + username);
await axios.get(apiSearchURL + username).then(async function(response){
if( response.status === 200 ) {
// account search results
if( response.data.results && response.data.results.length > 0 ) {
uplay_id = response.data.results[0].pid;
playerData = await getPlayerData(uplay_id);
}
else {
message.channel.send( getErrorMessage(1, {username: username, server_platform: server_platform}) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
}
})
.catch(function(error){
console.log(error);
});
}
}
}
/*************************************************
// PRINT AGENT SUMMARY
*************************************************/
if ( command === "agent" ) {
if( lodash.isEmpty(playerData) == false ) {
printAgentStat(message, playerData);
return;
}
}
/*************************************************
// PRINT WEAPON USAGE
*************************************************/
if ( command === "weapons" ) {
if( lodash.isEmpty(playerData) == false ) {
printWeaponStat(message, playerData);
return;
}
}
/*************************************************
// PRINT PVE DATA
*************************************************/
if ( command === "pve" ) {
if( lodash.isEmpty(playerData) == false ) {
printPVEStat(message, playerData);
return;
}
}
/*************************************************
// PRINT DZ DATA
*************************************************/
if ( command === "dz" || command === "darkzone" ) {
if( lodash.isEmpty(playerData) == false ) {
printDZStat(message, playerData);
return;
}
}
/*************************************************
// PRINT EXP
*************************************************/
if ( command === "exp" ) {
if( lodash.isEmpty(playerData) == false ) {
printAgentEXP(message, playerData);
return;
}
}
/*************************************************
// PRINT SERVER'S AGENTS DATA
*************************************************/
if ( command === "rank" ) {
if( args.length > 0 ) {
if( rankedData.includes(args[0]) ) {
rankGet(message, args[0], server_platform);
return;
}
}
message.channel.send( getErrorMessage(3) ).then(function(msg){ if( message.autoDelete ) msg.delete({ timeout: 15000 }); });
}
});
// Fetches top 10 highest stat type from registered members of the discord server
async function rankGet(message, type, server_platform) {
await message.channel.guild.members.fetch().then(async function(guild){
let clan_role_id = await pool.query("SELECT * FROM servers WHERE server_id = ?", [message.guild.id]).then(function(res){
if( res.length > 0 )
return res[0].clan_role_id ? res[0].clan_role_id : null;
else
return null
})
.catch(function(error){
return null;
});
// Array of member id + username objects
let members = [];
// Clan role restriction - only show results where members are of role specified
if( clan_role_id )
members = message.guild.members.cache.filter(function(member){ return member.user.bot === false && member._roles.includes(clan_role_id) }).map(function(member){ return {id: member.user.id, username: member.user.username} });
else
members = message.guild.members.cache.filter(function(member){ return member.user.bot === false }).map(function(member){ return {id: member.user.id, username: member.user.username} });
// Manually added agents
if( useTrackerGG ) {
manual_agents = await pool.query("SELECT * FROM server_agents WHERE server_id = ?", [message.guild.id]).then(function(res){
if( res.length > 0 ) {
return res.map(function(res){ return res.agent_name });
}
else {
return [];
}
});
}
else {
manual_agents = await pool.query("SELECT * FROM server_agents WHERE server_id = ?", [message.guild.id]).then(function(res){
if( res.length > 0 ) {
return res.map(function(res){ return res.agent_id });
}
else {
return [];
}
});
}
let results = [];
if(members.length > 0) {
switch(type) {
case 'playtime':
message.channel.startTyping();
for(var i=0; i<members.length; i++) {
await pool.query("SELECT * FROM users WHERE user_id = ?", [members[i].id]).then(async function(res){
if( res.length > 0 ) {
uplay_id = res[0].uplay_id;
platform = res[0].platform;
agent_name = res[0].agent_name;
playerData = await getPlayerData(uplay_id, platform, agent_name);
if( lodash.isEmpty(playerData) == false ) {
results.push({
is_manual: false,
uplay_id: playerData.name,
user_id: members[i].id,
username: members[i].username,
ranked_value: Number(playerData.timeplayed_total),
display_value: lodash.round(playerData.timeplayed_total / 3600) + " hour" + (lodash.round(playerData.timeplayed_total / 3600) > 1 ? 's':'')
});
}
}
});
}
for(var i=0; i<manual_agents.length; i++) {
playerData = await getPlayerData(manual_agents[i], server_platform, manual_agents[i]);
if( lodash.isEmpty(playerData) == false ) {
results.push({
is_manual: true,
uplay_id: playerData.name,
user_id: 0,
username: playerData.name,
ranked_value: Number(playerData.timeplayed_total),
display_value: lodash.round(playerData.timeplayed_total / 3600) + " hour" + (lodash.round(playerData.timeplayed_total / 3600) > 1 ? 's':'')
});
}
else {
if( useTrackerGG )
pool.query("DELETE FROM server_agents WHERE agent_name = ? AND server_id = ?", [manual_agents[i], message.guild.id]);
else
pool.query("DELETE FROM server_agents WHERE agent_name = ? AND server_id = ?", [manual_agents[i], message.guild.id]);
}
}
message.channel.stopTyping();
if( results.length > 0 ) {
printRankedResult(message, results, 'desc', 'Playtime');
}
break;
case 'ecredit':
message.channel.startTyping();
for(var i=0; i<members.length; i++) {
await pool.query("SELECT * FROM users WHERE user_id = ?", [members[i].id]).then(async function(res){
if( res.length > 0 ) {
uplay_id = res[0].uplay_id;
platform = res[0].platform;
agent_name = res[0].agent_name;
playerData = await getPlayerData(uplay_id, platform, agent_name);
if( lodash.isEmpty(playerData) == false ) {
results.push({
is_manual: false,
uplay_id: playerData.name,
user_id: members[i].id,
username: members[i].username,
ranked_value: Number(playerData.ecredits),
display_value: playerData.ecredits.toLocaleString()
});
}
}
});
}
for(var i=0; i<manual_agents.length; i++) {
playerData = await getPlayerData(manual_agents[i], server_platform, manual_agents[i]);
if( lodash.isEmpty(playerData) == false ) {
results.push({
is_manual: true,
uplay_id: playerData.name,
user_id: 0,
username: playerData.name,
ranked_value: Number(playerData.ecredits),
display_value: playerData.ecredits.toLocaleString()
});
}
else {
if( useTrackerGG )
pool.query("DELETE FROM server_agents WHERE agent_name = ? AND server_id = ?", [manual_agents[i], message.guild.id]);
else
pool.query("DELETE FROM server_agents WHERE agent_name = ? AND server_id = ?", [manual_agents[i], message.guild.id]);
}
}
message.channel.stopTyping();
if( results.length > 0 ) {
printRankedResult(message, results, 'desc', 'E-Credit Balance');
}
break;
case 'gearscore':
message.channel.startTyping();
for(var i=0; i<members.length; i++) {
await pool.query("SELECT * FROM users WHERE user_id = ?", [members[i].id]).then(async function(res){
if( res.length > 0 ) {
uplay_id = res[0].uplay_id;
platform = res[0].platform;
agent_name = res[0].agent_name;
playerData = await getPlayerData(uplay_id, platform, agent_name);
if( lodash.isEmpty(playerData) == false ) {
results.push({
is_manual: false,
uplay_id: playerData.name,
user_id: members[i].id,
username: members[i].username,
ranked_value: Number(playerData.gearscore),
display_value: playerData.gearscore
});
}
}
});
}
for(var i=0; i<manual_agents.length; i++) {
playerData = await getPlayerData(manual_agents[i], server_platform, manual_agents[i]);
if( lodash.isEmpty(playerData) == false ) {
results.push({
is_manual: true,
uplay_id: playerData.name,
user_id: 0,
username: playerData.name,
ranked_value: Number(playerData.gearscore),
display_value: playerData.gearscore
});
}
else {
if( useTrackerGG )
pool.query("DELETE FROM server_agents WHERE agent_name = ? AND server_id = ?", [manual_agents[i], message.guild.id]);
else
pool.query("DELETE FROM server_agents WHERE agent_name = ? AND server_id = ?", [manual_agents[i], message.guild.id]);
}
}
message.channel.stopTyping();
if( results.length > 0 ) {
printRankedResult(message, results, 'desc', 'Gear Score');
}
break;
case 'commendation':
message.channel.startTyping();
for(var i=0; i<members.length; i++) {
await pool.query("SELECT * FROM users WHERE user_id = ?", [members[i].id]).then(async function(res){
if( res.length > 0 ) {
uplay_id = res[0].uplay_id;
platform = res[0].platform;
agent_name = res[0].agent_name;
playerData = await getPlayerData(uplay_id, platform, agent_name);
if( lodash.isEmpty(playerData) == false ) {
results.push({
is_manual: false,
uplay_id: playerData.name,
user_id: members[i].id,
username: members[i].username,
ranked_value: Number(playerData.commendations),
display_value: playerData.commendations.toLocaleString()
});
}
}
});
}
for(var i=0; i<manual_agents.length; i++) {
playerData = await getPlayerData(manual_agents[i], server_platform, manual_agents[i]);
if( lodash.isEmpty(playerData) == false ) {
results.push({
is_manual: true,
uplay_id: playerData.name,
user_id: 0,
username: playerData.name,
ranked_value: Number(playerData.commendations),
display_value: playerData.commendations.toLocaleString()
});
}
else {
if( useTrackerGG )
pool.query("DELETE FROM server_agents WHERE agent_name = ? AND server_id = ?", [manual_agents[i], message.guild.id]);
else
pool.query("DELETE FROM server_agents WHERE agent_name = ? AND server_id = ?", [manual_agents[i], message.guild.id]);
}
}
message.channel.stopTyping();
if( results.length > 0 ) {
printRankedResult(message, results, 'desc', 'Commendations');
}
break;
case 'clanexp':
case 'cxp':
message.channel.startTyping();
for(var i=0; i<members.length; i++) {
await pool.query("SELECT * FROM users WHERE user_id = ?", [members[i].id]).then(async function(res){
if( res.length > 0 ) {
uplay_id = res[0].uplay_id;
platform = res[0].platform;
agent_name = res[0].agent_name;
playerData = await getPlayerData(uplay_id, platform, agent_name);
if( lodash.isEmpty(playerData) == false ) {
results.push({
is_manual: false,
uplay_id: playerData.name,
user_id: members[i].id,
username: members[i].username,
ranked_value: Number(playerData.xp_clan),
display_value: playerData.xp_clan.toLocaleString()
});
}
}
});
}
for(var i=0; i<manual_agents.length; i++) {
playerData = await getPlayerData(manual_agents[i], server_platform, manual_agents[i]);
if( lodash.isEmpty(playerData) == false ) {
results.push({
is_manual: true,
uplay_id: playerData.name,
user_id: 0,
username: playerData.name,
ranked_value: Number(playerData.xp_clan),
display_value: playerData.xp_clan.toLocaleString()
});
}
else {
if( useTrackerGG )
pool.query("DELETE FROM server_agents WHERE agent_name = ? AND server_id = ?", [manual_agents[i], message.guild.id]);
else
pool.query("DELETE FROM server_agents WHERE agent_name = ? AND server_id = ?", [manual_agents[i], message.guild.id]);
}
}
message.channel.stopTyping();
if( results.length > 0 ) {
printRankedResult(message, results, 'desc', 'Clan EXP');
}
break;
case 'clanexp24h':
case 'cxp24h':