-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1043 lines (1007 loc) · 50.7 KB
/
index.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
require('dotenv').config()
const Discord = require('discord.js')
const admin = require('firebase-admin')
const fs = require('fs')
const request = require('request')
const cheerio = require('cheerio')
const client = new Discord.Client()
var serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT)
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://rankbot-1ada2.firebaseio.com"
})
const db = admin.firestore()
var FieldValue = admin.firestore.FieldValue;
function overallRank(player_name, playersData, leagueData, msg) {
if (player_name.toLowerCase() in playersData) {
let total_players = leagueData.total_players
let player = playersData[player_name.toLowerCase()]
let rank = player.rank
if (rank != undefined) {
if (player.active) {
msg.reply("`" + player.name + "` is rank " + rank + " of "+total_players+".")
} else {
msg.reply("`" + player.name + "` is rank " + rank + " of "+total_players+" overall, but is currently inactive.")
}
} else {
msg.reply("`" + player.name + "'s` rank has not been updated.")
}
} else {
msg.reply("player `" + player_name + "` is not recognized.")
}
}
function exposePlayer(player_name, playersData, leagueData, msg) {
if (player_name.toLowerCase() in playersData) {
let player = playersData[player_name.toLowerCase()]
getInsult(player.name).then(function(insult) {
if(player.active){
let randomNumber = Math.floor(Math.random() * Math.floor(100))
if(randomNumber < 15){
overallRank(player_name, playersData, leagueData, msg)
}
else{
msg.channel.send(insult)
}
}
else{
let randomNumber = Math.floor(Math.random() * Math.floor(100))
if(randomNumber < 15){
msg.channel.send(player_name + " isn't even active... psssh.")
}
else{
msg.channel.send(insult)
}
}
})
} else {
msg.reply("player `" + player_name + "` is not recognized.")
}
}
function getInsult(player_name) {
return new Promise((resolve, reject) => {
if(player_name.toLowerCase() === 'socktastic'){
let randomNumber = Math.floor(Math.random() * Math.floor(100))
if(randomNumber < 25){
resolve("https://www.youtube.com/watch?v=JOGCsnDbQUk")
return
}
}
let url = encodeURI("https://insult.mattbas.org/api/insult.json?template=" + player_name + " is <adjective>");
request(url, { json: true }, (err, res, body) => {
if (err) {
resolve(player_name + " smells... good!")
} else {
resolve(body.insult)
}
})
})
}
function newTagRole(member_id, guild, league_id, membersID, playersID) {
//max_points, ranks, playersData
let membersDB = db.collection('members').doc(membersID)
let playersDB = db.collection('players').doc(playersID)
let leagueDB = db.collection('leagues').doc(league_id)
Promise.all([membersDB.get(), playersDB.get(), leagueDB.get()]).then(function (values) {
let membersDoc = values[0]
let playersDoc = values[1]
let leagueDoc = values[2]
if (membersDoc.exists && playersDoc.exists && leagueDoc.exists) {
let ranks = leagueDoc.data().ranks
let max_points = leagueDoc.data().max_points
let membersData = membersDoc.data()
let playersData = playersDoc.data()
if (member_id in membersData) {
let player_name = membersData[member_id]
let guildMember = guild.members.find(gMember => gMember.id == member_id)
if (guildMember != null) {
let player = {
active: false,
points: 0
}
let new_role = null
if (player_name in playersData) {
player = playersData[player_name]
}
for (rank in ranks) {
let currentRank = ranks[rank]
if (currentRank.active_required) {
if (player.active && player.points >= currentRank.percentile * max_points) {
new_role = currentRank.role
}
} else if (player.points >= currentRank.percentile * max_points) {
new_role = currentRank.role
}
}
if (new_role != null) {
let roleToAdd = guild.roles.find(role => role.name.toLowerCase() === new_role)
if(roleToAdd != null){
guildMember.addRole(roleToAdd).then(() => {
guildMember.removeRoles(guild.roles.filter(role => role.name.toLowerCase() != new_role && ranks.map(rank => rank.role).includes(role.name.toLowerCase()))).catch(console.log)
}).catch(console.log)
}
}
}
}
}
})
}
function updateRoles(guild, league_id, membersID, playersID) {
let membersDB = db.collection('members').doc(membersID)
let playersDB = db.collection('players').doc(playersID)
let leagueDB = db.collection('leagues').doc(league_id)
Promise.all([membersDB.get(), playersDB.get(), leagueDB.get()]).then(function (values) {
let membersDoc = values[0]
let playersDoc = values[1]
let leagueDoc = values[2]
if (membersDoc.exists && playersDoc.exists && leagueDoc.exists) {
let ranks = leagueDoc.data().ranks
let max_points = leagueDoc.data().max_points
let membersData = membersDoc.data()
let playersData = playersDoc.data()
for (member_id in membersData) {
let player_name = membersData[member_id]
let guildMember = guild.members.find(gMember => gMember.id == member_id)
if (guildMember != null) {
let player = {
active: false,
points: 0
}
let new_role = null
if (player_name in playersData) {
player = playersData[player_name]
}
for (rank in ranks) {
let currentRank = ranks[rank]
if (currentRank.active_required) {
if (player.active && player.points >= currentRank.percentile * max_points) {
new_role = currentRank.role
}
} else if (player.points >= currentRank.percentile * max_points) {
new_role = currentRank.role
}
}
if (new_role != null) {
let roleToAdd = guild.roles.find(role => role.name.toLowerCase() === new_role)
if(roleToAdd != null){
guildMember.addRole(roleToAdd).then(() => {
guildMember.removeRoles(guild.roles.filter(role => role.name.toLowerCase() != new_role && ranks.map(rank => rank.role).includes(role.name.toLowerCase()))).catch(console.log)
}).catch(console.log)
}
}
}
}
}
})
}
function updateBraacketPlayer(player) {
return new Promise((resolve, reject) => {
if (!player.updated) {
request(player.url, {
json: false
}, (err, res, body) => {
if (!err) {
const $ = cheerio.load(body)
let dashboard_values = $("div.panel-body").find("div.my-dashboard-values-sub")
let dashboard_rankings = $("div.panel-body").find("div.my-dashboard-values-main:contains('out of')")
let check_not_avaliable = $("div.panel-body:contains('Not available.')")
if (dashboard_values.length > 0 && dashboard_rankings.length > 0) {
player.rank = parseInt(dashboard_rankings.text().trim().match(new RegExp('[0-9]+'))[0])
dashboard_values.each(function (i, elem) {
if ($(this).find("div:contains('Points')").length > 0) {
player.points = parseInt($(this).children('div').eq(1).text().trim())
}
if ($(this).find("div:contains('Activity requirement')").length > 0) {
player.active = $(this).find("span").length <= 0
}
})
player.updated = true
resolve({
player: player,
not_avaliable: false
})
}
else{
reject({
player: player,
not_avaliable: check_not_avaliable.length > 0
})
}
}
else{
reject({
player: player,
not_avaliable: false
})
}
})
} else {
resolve({
player: player,
not_avaliable: false
})
}
}).catch(function(p_err){
return p_err
})
}
function updatePlayerData(service, playersID, leagueID, timeout, temp_players, callback) {
if (service === 'braacket') {
timoutPromise(timeout, function (resolve, reject, endTime) {
Promise.all(Object.values(temp_players).map(updateBraacketPlayer)).then(function (values) {
values = values.filter(v => !v.not_avaliable)
temp_players = {}
values.forEach((v) => {
temp_players[v.player.id] = v.player
})
if(values.filter(v => !v.player.updated).length > 0){
reject(endTime - (new Date()).getTime())
}
else{
resolve()
}
}).catch(function (err) {
reject(endTime - (new Date()).getTime())
})
}).then(function () {
let playersDB = db.collection('players').doc(playersID)
let leagueDB = db.collection('leagues').doc(leagueID)
playersDB.set(temp_players)
let max_points = 0
for (p in temp_players) {
if (temp_players[p].points > max_points) {
max_points = temp_players[p].points
}
}
leagueDB.update({
max_points: max_points,
total_players: Object.keys(temp_players).length
})
callback(true)
}).catch(function (remainingTime) {
if (remainingTime > 0) {
updatePlayerData(service, playersID, leagueID, remainingTime, temp_players, callback)
} else {
callback(false)
}
})
} else {
callback(false)
}
}
function braacketGetPlayers(params) {
return new Promise((resolve, reject) => {
request('https://braacket.com/league/' + params.id + '/player?rows=' + params.rows + '&page=' + params.page, {
json: false
}, (err, res, body) => {
const $ = cheerio.load(body)
let player_fields = $('table.table.table-hover.my-table-checkbox')
if (err || player_fields.length <= 0) {
reject({})
} else {
let values = {}
player_fields.find('tbody').find('a:not(.badge)').each(function (i, elem) {
let id = $(this).text().trim().toLowerCase()
if(!(id in values)){
values[id] = {
"id": id,
"name": $(this).text().trim(),
"points": undefined,
"rank": undefined,
"active": false,
"url": "https://braacket.com" + $(this).attr('href'),
"updated": false
}
}
})
resolve(values)
}
})
}).catch(function(err){
return err;
})
}
function braacketGetPages(current_pages, id, rows) {
return new Promise((resolve, reject) => {
if(current_pages != null){
resolve({pages:current_pages})
} else{
request('https://braacket.com/league/' + id + '/player?rows=' + rows, { json: false }, (err, res, body) => {
const $ = cheerio.load(body)
let displaying_field = $("div.input-group-addon.my-input-group-addon:contains('Rows')")
if (err || displaying_field.length <= 0) {
if(err){
reject({pages:0})
}
else{
reject({pages:-1})
}
} else {
let total = parseInt(displaying_field.text().match(new RegExp('of [0-9]+'))[0].split(" ")[1])
let pages = Math.ceil(total / rows)
resolve({
pages:pages
})
}
})
}
})
}
function updatePlayers(service, id, playersID, leagueID, timeout, current_updated, current_players, current_pages, callback) {
if (service === 'braacket') {
timoutPromise(timeout, function (resolve, reject, endTime) {
braacketGetPages(current_pages, id, 500).then(function (values) {
let pages = values.pages
let params = []
for (i = 1; i <= pages; i++) {
if(current_updated == null || !current_updated.includes(i)){
params.push({
page: i,
rows: 500,
id: id
})
}
}
Promise.all(params.map(braacketGetPlayers)).then(function (values) {
let temp_players = {}
let updated = []
let all_updated = true
for (v in values) {
let page = values[v]
if (Object.keys(page).length <= 0){
all_updated = false
}
else{
updated.push(v)
Object.keys(page).forEach(function (key) {
temp_players[key] = page[key]
})
}
}
if(all_updated){
resolve({
pages: pages,
updated: updated,
temp_players: temp_players,
remainingTime: endTime - (new Date()).getTime()
})
}
else{
reject({
pages: pages,
updated: updated,
temp_players: temp_players,
remainingTime: endTime - (new Date()).getTime()
})
}
}).catch(function (err) {
reject({
pages: pages,
updated: null,
temp_players: null,
remainingTime: endTime - (new Date()).getTime()
})
})
}).catch(function (err) {
if(err.pages >= 0){
reject({
pages: null,
updated: null,
temp_players:null,
remainingTime: endTime - (new Date()).getTime()
})
}
else{
reject({
pages: null,
updated: null,
temp_players:null,
remainingTime: 0
})
}
})
}).then(function (values) {
if(current_players != null){
for(p in values.temp_players){
current_players[p] = values.temp_players[p]
}
}
else{
current_players = values.temp_players
}
updatePlayerData(service, playersID, leagueID, values.remainingTime, current_players, callback)
}).catch(function (err) {
if(err.temp_players != null && err.remainingTime > 0){
//some players were updated and theres time left.
//need to update current players
if(current_players != null){
for(p in err.temp_players){
current_players[p] = err.temp_players[p]
}
}
else{
current_players = err.temp_players
}
if(current_updated != null){
for(p in err.updated){
current_updated.push(err.updated[p])
}
}
else{
current_updated = err.updated
}
updatePlayers(service, id, playersID, leagueID, err.remainingTime, current_updated, current_players, err.pages, callback)
} else if (err.remainingTime > 0) {
updatePlayers(service, id, playersID, leagueID, err.remainingTime, current_updated, current_players, err.pages, callback)
} else {
callback(false)
}
})
} else {
callback(false)
}
}
function timoutPromise(ms, callback) {
return new Promise(function (resolve, reject) {
let currentTime = (new Date()).getTime()
callback(resolve, reject, currentTime + ms)
setTimeout(function () {
reject(0)
}, ms)
})
}
function playerTagTaken(tag, memberData, id) {
for (member in memberData) {
if (memberData[member].toLowerCase() === tag.toLowerCase()) {
if (member != id) {
return true
}
return false
}
}
return false
}
function hasModPermission(member, guild) {
let guildMember = guild.members.find(gMember => gMember.id == member)
if (guildMember != null) {
if (guildMember.hasPermission('ADMINISTRATOR')) {
return true
}
let highestRole = guildMember.highestRole
let botRole = guild.roles.find(r => r.name == 'rankBot')
if (botRole != null && highestRole.position > botRole.position) {
return true
}
}
return false
}
function tag_command(msg, message_parts) {
let member = msg.author.id
let guild = msg.guild
if (guild != null) {
let guild_id = guild.id
let guildDB = db.collection('guilds').doc(guild_id)
guildDB.get().then((guildDoc) => {
if (guildDoc.exists) {
let league_id = guildDoc.data().league_id
let membersID = guildDoc.data().members
let membersDB = db.collection('members').doc(membersID)
membersDB.get().then((membersDoc) => {
let leagueDB = db.collection('leagues').doc(league_id)
leagueDB.get().then((leagueDoc) => {
let playersID = null
if (leagueDoc.exists) {
playersID = leagueDoc.data().players
}
if (message_parts.length > 1) {
if (message_parts[1] === 'unlink') {
if (message_parts.length > 2) {
//unlink a player_name
let tag = message_parts.slice(2, message_parts.length).join(" ")
if (hasModPermission(member, guild)) {
if(membersDoc.exists){
let memberData = membersDoc.data()
let removed = []
for (m in memberData) {
if (memberData[m] === tag) {
memberData[m] = FieldValue.delete()
removed.push(m)
}
}
membersDB.update(memberData).then(function () {
if (playersID != null) {
for (r in removed) {
newTagRole(removed[r], guild, league_id, membersID, playersID)
}
}
msg.reply("tag unlinked!")
})
}
else{
msg.reply("tag unlinked!")
}
} else {
msg.reply("you do not have permission to use this command!")
}
} else {
//unlink self
if(membersDoc.exist){
let memberData = {}
memberData[member] = FieldValue.delete()
membersDB.update(memberData).then(function () {
msg.reply("tag unlinked!")
if (playersID != null) {
newTagRole(member, guild, league_id, membersID, playersID)
}
})
}
else{
msg.reply("tag unlinked!")
}
}
} else {
let tag = message_parts.slice(1, message_parts.length).join(" ").toLowerCase()
if (!playerTagTaken(tag, membersDoc.data(), member)) {
let memberData = {}
memberData[member] = tag
if(membersDoc.exists){
membersDB.update(memberData).then(function () {
msg.reply("tag set!")
if (playersID != null) {
newTagRole(member, guild, league_id, membersID, playersID)
}
})
}
else{
membersDB.set(memberData).then(function() {
msg.reply("tag set!")
if (playersID != null) {
newTagRole(member, guild, league_id, membersID, playersID)
}
})
}
} else {
msg.reply("tag `" + tag + "` already linked to another account!\n\nUse `!tag unlink` to unlink your tag.")
}
}
} else {
let memberData = membersDoc.data()
if (member in memberData) {
msg.reply("your tag is currently set to `" + memberData[member] + "`.")
} else {
msg.reply("your tag is not currently set!\n\nUse `!tag <player>` to associate your account with your player name!")
}
}
})
})
} else {
msg.reply("your server is not initialized with a league!\n\nUse `!league set` to get started!")
}
})
} else {
msg.reply("please use this command in a server!")
}
}
function league_command(msg, message_parts) {
let member = msg.author.id
let guild = msg.guild
if (guild != null) {
let guild_id = guild.id
let guildDB = db.collection('guilds').doc(guild_id)
guildDB.get().then((guildDoc) => {
if (message_parts.length > 1 && message_parts[1] === 'set') {
if (message_parts.length > 2) {
if (message_parts.length == 3) {
if (hasModPermission(member, guild)) {
let league_id = message_parts.slice(2, message_parts.length).join(" ")
let leagueDB = db.collection('leagues').doc(league_id)
if (!guildDoc.exists) {
let membersDB = db.collection('members').doc()
guildDB.set({
league_id: league_id,
members: membersDB.id
})
} else {
guildDB.update({
league_id: league_id
})
}
leagueDB.get().then((doc) => {
if (!doc.exists) {
let playersDB = db.collection('players').doc()
leagueDB.set({
owner: member,
mod: [],
private: false,
max_points: 0,
total_players: 0,
service: "",
players: playersDB.id,
id: "",
ranks: []
})
}
})
msg.reply("league set!")
} else {
msg.reply("you do not have permission to use that command!")
}
} else {
msg.reply("a league id cannot include spaces.")
}
} else {
msg.reply("please provide a league_id.")
}
} else if (!guildDoc.exists) {
msg.reply("your server is not initialized with a league!\n\nUse `!league set` to get started!")
} else {
let league_id = guildDoc.data().league_id
let leagueDB = db.collection('leagues').doc(league_id)
leagueDB.get().then((leagueDoc) => {
if (!leagueDoc.exists) {
msg.reply("the league associated with this server cannot be found.")
} else {
if (message_parts.length > 1) {
if (message_parts[1] === 'update' && message_parts.length == 2) {
let currentMods = leagueDoc.data().mod
let ownerID = leagueDoc.data().owner
if (member == ownerID || currentMods.includes(member)) {
update_command(msg, guild, msg.channel, guildDoc, leagueDoc)
} else {
msg.reply("you do not have permission to use this command!")
}
} else if (message_parts[1] === 'delete') {
if (message_parts.length == 2) {
let ownerID = leagueDoc.data().owner
let playersID = leagueDoc.data().players
let playersDB = db.collection('players').doc(playersID)
if (member == ownerID) {
leagueDB.delete().then(function () {
playersDB.delete().then(function () {
msg.reply("league deleted.")
})
})
} else {
msg.reply("you do not have permission to use this command!")
}
} else {
msg.reply("this command does not take any arguments.")
}
} else if (message_parts[1] === 'mod') {
if (message_parts.length == 4) {
if (message_parts[2] === 'add') {
let guildMember = msg.mentions.members.first()
if (guildMember != null) {
let currentMods = leagueDoc.data().mod
let ownerID = leagueDoc.data().owner
if (member == ownerID || currentMods.includes(member)) {
let newMod_id = guildMember.id
if (newMod_id != ownerID && !currentMods.includes(newMod_id)) {
currentMods.push(newMod_id)
leagueDB.update({
mod: currentMods
})
}
msg.reply("mod added!")
} else {
msg.reply("you don't have permission to use this command!")
}
} else {
msg.reply("argument 2 must be a member!")
}
} else if (message_parts[2] === 'remove') {
let guildMember = msg.mentions.members.first()
if (guildMember != null) {
let currentMods = leagueDoc.data().mod
let ownerID = leagueDoc.data().owner
if (member == ownerID || currentMods.includes(member)) {
let mod_id = guildMember.id
if (mod_id != ownerID) {
if (currentMods.includes(mod_id)) {
leagueDB.update({
mod: currentMods.filter(mod => mod != mod_id)
})
}
msg.reply("mod removed!")
} else {
msg.reply("you cannot unmod the league owner!")
}
} else {
msg.reply("you don't have permission to use this command!")
}
} else {
msg.reply("argument 2 must be a member!")
}
} else {
msg.reply("argument 1 must be `add` or `remove`!")
}
} else {
msg.reply("this command requires 2 arguments.")
}
} else if (message_parts[1] === 'service') {
if (message_parts.length == 4) {
let currentMods = leagueDoc.data().mod
let ownerID = leagueDoc.data().owner
if (member == ownerID || currentMods.includes(member)) {
let new_service = message_parts[2]
let new_service_id = message_parts[3]
leagueDB.update({
service: new_service,
id: new_service_id
})
msg.reply("league service set!")
} else {
msg.reply("you do not have permission to use this command!")
}
} else {
msg.reply("this command requires 2 arguments.")
}
} else if (message_parts[1] === 'ranks') {
if (message_parts.length > 2) {
if (message_parts[2] === 'add') {
if (message_parts.length >= 6) {
let currentMods = leagueDoc.data().mod
let ownerID = leagueDoc.data().owner
if (member == ownerID || currentMods.includes(member)) {
let active_arg = message_parts[message_parts.length - 1].toLowerCase()
let active_required = null
if (active_arg === 'true' || active_arg === 'false') {
active_required = (active_arg === 'true')
} else {
msg.reply("activity requirement must be true or false!")
}
let name = message_parts.slice(3, message_parts.length - 2).join(" ").toLowerCase()
let percentile = parseFloat(message_parts[message_parts.length - 2])
if (isNaN(percentile)) {
msg.reply("percentile must be a number!")
}
if (name != null && percentile != null && !isNaN(percentile) && active_required != null) {
let currentRanks = leagueDoc.data().ranks
if (currentRanks.filter(rank => rank.role === name).length > 0) {
msg.reply("this rank already exists!\n\nUse `!league ranks remove <name>` to remove a rank!")
} else {
if (percentile < 0) {
msg.reply("percentile must be positive.")
} else {
currentRanks.push({
role: name,
percentile: percentile,
active_required: active_required
})
currentRanks.sort(function (a, b) {
if (a.percentile > b.percentile || (a.active_required && !b.active_required))
return 1
if (b.percentile > a.percentile || (b.active_required && !a.active_required))
return -1
return 0
})
leagueDB.update({
ranks: currentRanks
})
msg.reply("rank added!")
}
}
}
} else {
msg.reply("you do not have permission to use this command!")
}
} else {
msg.reply("this command requires 3 arguments.")
}
} else if (message_parts[2] === 'remove') {
if (message_parts.length >= 4) {
let currentMods = leagueDoc.data().mod
let ownerID = leagueDoc.data().owner
if (member == ownerID || currentMods.includes(member)) {
if (message_parts[3] == 'all' && message_parts.length == 4) {
leagueDB.update({
ranks: []
})
msg.reply("all ranks removed.")
} else {
let name = message_parts.slice(3, message_parts.length).join(" ").toLowerCase()
let currentRanks = leagueDoc.data().ranks
let nameMatches = currentRanks.filter(rank => rank.role === name)
if (nameMatches.length > 0) {
leagueDB.update({
ranks: currentRanks.filter(rank => rank.role != name)
})
}
msg.reply("rank removed.")
}
} else {
msg.reply("you do not have permission to use that command!")
}
} else {
msg.reply("please provide a rank name.")
}
} else if (message_parts[2] === 'update') {
if (hasModPermission(member, guild)){
let playersID = leagueDoc.data().players
let membersID = guildDoc.data().members
updateRoles(guild, league_id, membersID, playersID)
msg.reply("member ranks updated.")
}
else{
msg.reply("you do not have permission to use this command!")
}
}
} else {
let currentRanks = leagueDoc.data().ranks
if (currentRanks.length > 0) {
msg.reply("the current ranks are " + currentRanks.map(function (rank) {
return rank.role
}).join(", "))
} else {
msg.reply("there are no ranks associated with `" + league_id + "`\n\nUse `!league ranks add <name> <percentile> <active requirement>` to add new ranks")
}
}
}
} else {
msg.reply("this server is associated with `" + league_id + "`")
}
}
})
}
})
} else {
msg.reply("please use this command in a server!")
}
}
function update_command(msg, guild, channel, guildDoc, leagueDoc) {
let guild_id = guild.id
if (!guildDoc.exists) {
msg.reply("your server is not initialized with a league!\n\nUse `!league set` to get started!")
} else {
let league_id = guildDoc.data().league_id
let membersID = guildDoc.data().members
if (!leagueDoc.exists) {
msg.reply("the league associated with this server cannot be found.")
} else {
let playersID = leagueDoc.data().players
let id = leagueDoc.data().id
let service = leagueDoc.data().service
if (id != '' && service != '') {
channel.startTyping()
updatePlayers(service, id, playersID, league_id, 300000, null, null, null, (all_updated) => {
if (all_updated) {
channel.stopTyping()
msg.reply("data updated.")
updateRoles(guild, league_id, membersID, playersID)
} else {
channel.stopTyping()
msg.reply("unable to update service data.")
}
})
} else {
msg.reply("the league associated with this server has not been configured to retrieve data.\n\nUse `!league service <service_name> <id>`")
}
}
}
}
function rank_command(msg, message_parts) {
let member = msg.author.id
let guild = msg.guild
if (guild != null) {
let guild_id = guild.id
let guildDB = db.collection('guilds').doc(guild_id)
guildDB.get().then((guildDoc) => {
if (!guildDoc.exists) {
msg.reply("your server is not initialized with a league!\n\nUse `!league set` to get started!")
} else {
let league_id = guildDoc.data().league_id
let leagueDB = db.collection('leagues').doc(league_id)
leagueDB.get().then((leagueDoc) => {
if (!leagueDoc.exists) {
msg.reply("the league associated with this server cannot be found.")
} else {
let membersID = guildDoc.data().members
let membersDB = db.collection('members').doc(membersID)
membersDB.get().then((membersDoc) => {
let playersID = leagueDoc.data().players
let playersDB = db.collection('players').doc(playersID)
playersDB.get().then((playersDoc) => {
if(playersDoc.exists){
if (message_parts.length > 1) {
if(message_parts[1] === 'update'){
if (playersID != null) {
newTagRole(member, guild, league_id, membersID, playersID)
msg.reply("rank updated!")
}
}
else{
//active rank for playername
let player_name = message_parts.slice(1, message_parts.length).join(" ")
overallRank(player_name, playersDoc.data(), leagueDoc.data(), msg)
}
} else {
//active rank for caller
if (membersDoc.exists && member in membersDoc.data()) {
let player_name = membersDoc.data()[member]
overallRank(player_name, playersDoc.data(), leagueDoc.data(), msg)
} else {
msg.reply("your tag is not currently set!\n\nUse `!tag <player>` to associate your account with your player name!")
}
}
}
else{
msg.reply("There are no players in your league!\n\nUse `!league update` to pull data.")
}
})
})
}
})
}
})
} else {
msg.reply("please use this command in a server!")
}
}
function expose_command(msg, message_parts) {
let member = msg.author.id
let guild = msg.guild
if (guild != null) {
let guild_id = guild.id
let guildDB = db.collection('guilds').doc(guild_id)
guildDB.get().then((guildDoc) => {
if (!guildDoc.exists) {
msg.reply("your server is not initialized with a league!\n\nUse `!league set` to get started!")
} else {
let league_id = guildDoc.data().league_id
let leagueDB = db.collection('leagues').doc(league_id)
leagueDB.get().then((leagueDoc) => {
if (!leagueDoc.exists) {
msg.reply("the league associated with this server cannot be found.")
} else {
let membersID = guildDoc.data().members
let membersDB = db.collection('members').doc(membersID)
membersDB.get().then((membersDoc) => {
let playersID = leagueDoc.data().players
let playersDB = db.collection('players').doc(playersID)
playersDB.get().then((playersDoc) => {
if(playersDoc.exists){
if (message_parts.length > 1) {
//active rank for playername
let player_name = message_parts.slice(1, message_parts.length).join(" ")
exposePlayer(player_name, playersDoc.data(), leagueDoc.data(), msg)
} else {
//active rank for caller
if (membersDoc.exists && member in membersDoc.data()) {
let player_name = membersDoc.data()[member]
exposePlayer(player_name, playersDoc.data(), leagueDoc.data(), msg)
} else {
msg.reply("your tag is not currently set!\n\nUse `!tag <player>` to associate your account with your player name!")