forked from jon12156/ShockBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
1758 lines (1670 loc) · 78.8 KB
/
app.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 botSettings = require("./botsettings.json")
var Discord = require('discord.js');
const fs = require('fs');
var bot = new Discord.Client({autoReconnect:true});
//var matchmakingTextChannel;
var streamAlertsChannel;
var surveysTextChannel;
//var messageForMatchmakingRoles;
var messageForSkillSurvey;
var matchmaker;
var lastMatchmakingActivity
// the current lists of MatchSeeks, Matches
//IDs
const textChannelIDForWelcome = botSettings.textChannelIDForWelcome
const textChannelIDForSetupHelp = botSettings.textChannelIDForSetupHelp
const textChannelIDForSkillVerification = botSettings.textChannelIDForSkillVerification
const channelIDStreamAlerts = botSettings.channelIDStreamAlerts
const roleIDNewMember = botSettings.roleIDNewMember
const roleIDInactive = botSettings.roleIDInactive
const reactionIdentLock = botSettings.reactionIdentLock //:lock:
const reactionIdentUnlock = botSettings.reactionIdentUnlock //:unlock:
const unicodeLock = botSettings.unicodeLock //🔒
const unicodeUnlock = botSettings.unicodeUnlock //🔓
const reactionIdentGetMatchChannelPermissions = botSettings.reactionIdentGetMatchChannelPermissions //:microphone:
const unicodeGetMatchChannelPermissions = botSettings.unicodeGetMatchChannelPermissions //🎙
const unicodeBoot = botSettings.unicodeBoot // "unicodeBoot": "👢",
const reactionIdentBronze = botSettings.reactionIdentBronze //:one:
const reactionIdentSilver = botSettings.reactionIdentSilver //:two:
const reactionIdentGold = botSettings.reactionIdentGold //:three:
const reactionIdentPlatinum = botSettings.reactionIdentPlatinum //:four:
const reactionIdentDiamond = botSettings.reactionIdentDiamond //:five:
const reactionIdentMaster = botSettings.reactionIdentMaster //:six:
const validSkillRoleStrings = ['Master', 'Diamond', 'Platinum', 'Gold', 'Silver', 'Bronze', 'Master (pending verification)', 'Diamond (pending verification)', 'Platinum (pending verification)']
const textChannelIDForSurveys = botSettings.textChannelIDForSurveys
const skillSurveyMessageContent = '__**Skill Survey**__\n\nPlease estimate your own skill at the game. I\'ve put together a scale from Bronze to Master.\n\nTo answer, just click a reaction button corresponding to the number next to the skill level you think most closely matches your current skill.\n\nPlease answer as accurately as possible. We\'d appreciate it if you don\'t joke and rank yourself way higher or way lower than your actual approximate skill.\n\n:one: **Bronze**\n-Very little or no experience with the game\n-mostly goes for 4 combos if anything.\n-prefers difficulty level 1\n\n:two: **Silver**\n-understands how to lower the stack (get rid of towers and fill holes)\n-looks for 5-6 combos\n-sets up x2 chains (not so many skill chains)\n-comfortable on levels 2-4\n\n:three: **Gold**\n-comfortable on level 5\n-can do some skill chains, usually just in the nick of time.\n-great at chaining off of transforming garbage\n\n:four: **Platinum**\n-Comfortable on level 8.\n-good at recognizing patterns and building long skill chains.\n\n:five: **Diamond**\n-comfortable on level 10\n-strategizes on what kinds of garbage to send and when, and when to stop a chain.\n-sees chains many links ahead, and can quickly send exactly the garbage he wants.\n\n:six: **Master**\n-great at incorporating lots of medium-large combos while chaining, which produces very high garbage output.\n-often takes advantage of time lag chains, and can often work on two chains at once.\n-deep game sense, knowing when to do certain things that will give him/her an advantage, like always knowing just how much garbage is required to top out the opponent.'
const messageIDForSkillSurvey = botSettings.messageIDForSkillSurvey
//skill IDs
const roleIDMaster = botSettings.roleIDMaster
const roleIDDiamond = botSettings.roleIDDiamond
const roleIDPlatinum = botSettings.roleIDPlatinum
const roleIDGold = botSettings.roleIDGold
const roleIDSilver = botSettings.roleIDSilver
const roleIDBronze = botSettings.roleIDBronze
const roleIDMasterPending = botSettings.roleIDMasterPending
const roleIDDiamondPending = botSettings.roleIDDiamondPending
const roleIDPlatinumPending = botSettings.roleIDPlatinumPending
const channelIDMaster = botSettings.channelIDMaster
const channelIDDiamond = botSettings.channelIDDiamond
const channelIDPlatinum = botSettings.channelIDPlatinum
const channelIDGold = botSettings.channelIDGold
const channelIDSilver = botSettings.channelIDSilver
const channelIDBronze = botSettings.channelIDBronze
const cordeliasPrefix = botSettings.cordeliasPrefix
const reactionIdentChallenge = botSettings.reactionIdentChallenge // :crossed_swords:
const reactionIdentAcceptChallenge = botSettings.reactionIdentAcceptChallenge //:OK:
const reactionIdentLogMatchSeeks = botSettings.reactionIdentLogMatchSeeks //:wrench:
const reactionIdentNoMike = botSettings.reactionIdentNoMike //:keyboard:
const delayInSecBeforeNonPlayersCanJoinChat = botSettings.delayInSecBeforeNonPlayersCanJoinChat //in seconds (NOT MILLISECONDS) i.e. 10 for 10 seconds
var maintenanceIntervalInMin = botSettings.maintenanceIntervalInMin
if (isNaN(maintenanceIntervalInMin)){
log(`Error: botSettings file does not contain a valid maintenanceIntervalInMin. Using 10 minutes`)
maintenanceIntervalInMin = 10
}
var inactivityActions
if (botSettings.hasOwnProperty('inactivityActions')) {
inactivityActions = botSettings.inactivityActions
}else{
log(`Error: No inactivityActions specified in botSettings.json. We will not change matchmaking roles for inactivity.`)
inactivityActions = []
}
var matchmakingPlatforms
if (botSettings.hasOwnProperty('matchmakingPlatforms')) {
matchmakingPlatforms = botSettings.matchmakingPlatforms
}else{
log(`Fatal Error: No matchmakingPlatforms specified in botSettings.json. `)
matchmakingPlatforms = []
throw ''; //exit the program
}
// Functions
// pauses running of code for duration passed in (in milliseconds)
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
function getDateTime() {
var date = new Date();
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
var sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
var day = date.getDate();
day = (day < 10 ? "0" : "") + day;
return year + ":" + month + ":" + day + " " + hour + ":" + min + ":" + sec;
}
function log(message){
console.log(`${getDateTime()} ${message}`)
}
function getSkillRoleString(member){
// we'll return an empty string if the member doesn't have a skill role.
let skillRoleString = ''
validSkillRoleStrings.forEach(s => {
if (member.roles.cache.some(x => x.name === s)){
// return the first valid Skill Role as a string
log('skill role found')
skillRoleString = s
return
}
})
if (skillRoleString === '') log('skill role not found')
return skillRoleString
}
class Matchmaker{
constructor(){
log('starting new matchmaker');
this.matchSeekSet = new Set();
this.matchSet = new Set();
log('created new matchmaker');
//log('matchmaker\'s matchSeekSet:\n' + this.matchSeekSet)
}
async addMatchSeek(matchSeek){
let messageContent = `${matchSeek.seeker}`
let skillRoleString = getSkillRoleString(matchSeek.seeker);
if (skillRoleString !== '') messageContent += ` (${skillRoleString})`
messageContent += ' **is looking for an opponent!**';
if (matchSeek.pingAllowed) messageContent += `\n\n<@&${matchmakingPlatforms[matchSeek.platformIndex].roleIDLookingForOpponent}> <@&${matchmakingPlatforms[matchSeek.platformIndex].roleIDPotentiallyAvailable}>`;
let message;
try {
message = await matchSeek.textChannel.send(messageContent);
matchSeek.message = message;
matchSeek.coreMessageContent = messageContent
message.react(reactionIdentChallenge);
log('we are around line 130');
this.matchSeekSet.add(matchSeek);
if (skillRoleString === '')
matchSeek.seeker.send('Please note: I\'m not able to let everyone in #matchmaking know what your skill level is because you haven\'t answered the **Skill Survey** in #surveys yet. Please take a second to have a look at that.\n\nIf you can\'t get it to work, please message @Jon_12156 and include your skill level. \n\nThanks')
/*log('entire matchSeekSet:')
this.matchSeekSet.forEach(function(matchSeekToPrint){
log(matchSeekToPrint)
})*/
log(`New MatchSeek created:\nseeker: ${matchSeek.seeker.user.username}\ntextChannel: ${matchSeek.textChannel.name}\n`);
return true;
} catch (err) {
log('MatchSeek creation failed');
log(err);
return false;
}
}
updateMatchSeekMessage(matchSeek, customMessage){
try{
matchSeek.customMessage = customMessage
log(`updating custom message for ${matchSeek.seeker}`)
log(`Custom Message: \"${matchSeek.customMessage}\"`)
matchSeek.message.edit(`${matchSeek.coreMessageContent}\n\n\"${matchSeek.customMessage}\"`)
}
catch(err){
log('error updating custom message')
log(err)
}
}
removeMatchSeek(member){
//remove any official matchSeeks (from this bot)
sleep(1).then(() => {
this.matchSeekSet.forEach(matchSeek =>{
if (matchSeek.seeker === member){
matchSeek.challenges.forEach(challenge => {
matchmaker.removeMatchSeek
matchSeek.removeChallenge(challenge)
})
this.matchSeekSet.delete(matchSeek)
matchSeek.message.delete()
.then(log('deleted message of official matchseek for ' + member.user.username))
.catch(function(err){
log(`failed to delete message for official match for ${member.user.username}. Maybe it is already deleted.`)
log(err)
})
}
})
}).then(() =>{
matchmakingPlatforms.forEach(platform =>
{
// also remove any other messages saying the member "is looking", perhaps sent by cordelia
platform.matchmakingTextChannel.messages.fetch().then(function(messageCollection){
messageCollection.forEach(function(message, id){
let msg = message.content.toUpperCase()
//exceptions:
// don't delete the messageForMatchmakingRoles
if(id !== platform.messageIDForMatchmakingRoles){
//delete messages that say the member is looking
if(msg.includes(member.id) && msg.includes('IS LOOKING')){
log('deleting message: id:' + id + ' Message Content:' + message)
message.delete()
.then(log('deleted matchSeek message'))
.catch(() => undefined);
}else{
//used to log which messages were not being deleted here.
//log('not deleting: id:' + id + ' Message Content:' + message)
}
}
})
})
})
})
}
removeChallenge(challenge){
challenge.matchSeek.removeChallenge(challenge);
}
removeChallengesForMember(member){
//log(this.matchSeekSet)
log('matchSeeks before deletions:')
matchmaker.matchSeekSet.forEach(function(matchSeek){
log('matchSeek seeker: ' + matchSeek.seeker.user.username)
log('challenges: ')
matchSeek.challenges.forEach(function(challenge){
log('challenger: ' + challenge.challenger.user.username)
})
})
log('deleting any challenges where challenger = ' + member.user.username)
this.matchSeekSet.forEach(matchSeek =>{
matchSeek.challenges.forEach(challenge =>{
log('challenger: ' + challenge.challenger)
log('member having challenges removed: ' + member)
if (challenge.challenger === member){
log(challenge)
matchSeek.removeChallenge(challenge)
.then(log('deleted challenge message'))
.catch(console.error())
}
})
})
}
memberIsInAMatch(member){
log(`Checking whether ${member.user.username} is in a match`)
var memberFoundInMatch = false
matchmaker.matchSet.forEach(match => {
if (match.player1 === member || match.player2 === member){
log(`They are.`)
memberFoundInMatch = true
return
}
})
if (memberFoundInMatch) log(`They are.`)
else log(`They aren't`)
return memberFoundInMatch
}
removeLookingMessages(member, platformIndex){
// removes from all platforms if platform not specified
// remove any other messages saying the member "is looking", perhaps sent by cordelia
matchmakingPlatforms.forEach(platform =>{
if (typeof platformIndex == "undefined" || platformIndex === -1 || platform.platformName === matchmakingPlatforms[platformIndex].platformName){
platform.matchmakingTextChannel.messages.fetch().then(function(messageCollection){
messageCollection.forEach(function(message, id){
let msg = message.content.toUpperCase()
//exceptions:
// don't delete the messageForMatchmakingRoles
if(id !== platform.messageIDForMatchmakingRoles){
//delete messages that say the member is looking
if(msg.includes(member.id) && msg.includes('IS LOOKING')){
log('deleting message: id:' + id + ' Message Content:' + message)
message.delete()
.then(log('deleted matchSeek message'))
.catch(() => undefined);
}else{
//used to log which messages were not being deleted here.
//log('not deleting: id:' + id + ' Message Content:' + message)
}
}
})
})
}
})
}
async addMatch(match){
log('beginning of matchmaker addMatch method')
matchmaker.removeLookingMessages(match.player1, match.platformIndex)
matchmaker.removeLookingMessages(match.player2, match.platformIndex)
matchmaker.endMatch(match.player1);
matchmaker.endMatch(match.player2);
sleep(500).then(() => {
changeMatchmakingRole(match.player1, matchmakingPlatforms[match.platformIndex].roleIDInGame)
changeMatchmakingRole(match.player2, matchmakingPlatforms[match.platformIndex].roleIDInGame)
match.createVoiceChannel()
match.createTextChannel()
.then(sleep(1000)).then(() =>{
this.matchSet.add(match);
this.checkAndUpdateStreamsForMatch(match)
})
.catch(err => {
log(`couldn't update streams`)
})
});
}
checkAndUpdateStreamsForMatch(match){
let linkAddedToMatch = null
log(`match.player1StreamURL = ${match.player1StreamURL}`)
log(`match.player2StreamURL = ${match.player2StreamURL}`)
linkAddedToMatch = match.checkAndUpdateStreams()
log(`linkAddedToMatch = ${linkAddedToMatch}`)
if(linkAddedToMatch){
streamAlertsChannel.send(`${match.player1.user.username} vs ${match.player2.user.username}\n<${linkAddedToMatch}>`)
log('sent a message in the stream alerts channel')
}
else{
log('no stream was added')
}
log(`match.player1StreamURL = ${match.player1StreamURL}`)
log(`match.player2StreamURL = ${match.player2StreamURL}`)
//and then also announce a new stream in a separate channel
}
async createVoiceChannel(match){
await match.createVoiceChannel();
try{
log('Moving players to Voice Channel (if they were in another voice channel in this server)')
match.player1.voice.setChannel(match.voiceChannel)
match.player2.voice.setChannel(match.voiceChannel)
log('players should have been moved to voice channel')
}
catch(err){
log('Error moving players into the Voice Channel')
log(err)
}
}
cancelSeeksAndChallenges(member){
this.removeChallengesForMember(member)
this.removeMatchSeek(member)
}
//end a match where the member was a player
endMatch(member){
this.matchSet.forEach(match =>{
if (match.player1 === member || match.player2 === member){
try{
if (match.textChannel){
log('deleting TextChannel: ' + match.textChannel.name)
match.textChannel.delete()
}
}
catch(err){
log('error deleting textChannel')
log(err)
}
try{
if (match.voiceChannel){
log('deleting VoiceChannel: ' + match.voiceChannel.name)
match.voiceChannel.delete()
}
}
catch (err){
log('error deleting VoiceChannel')
log(err)
}
this.matchSet.delete(match)
// Remove the opponent's IN-GAME role.
// set the opponent as POTENTIALLY AVAILABLE if they aren't already LOOKING for another opponent.
if (match.player1 === member ){
if (match.player2.roles.cache.has(matchmakingPlatforms[match.platformIndex].roleIDLookingForOpponent)
&& match.player2.roles.cache.has(matchmakingPlatforms[match.platformIndex].roleIDInGame)){
match.player2.roles.remove(member.guild.roles.cache.get(matchmakingPlatforms[match.platformIndex].roleIDInGame))
}
else{
changeMatchmakingRole(match.player2, matchmakingPlatforms[match.platformIndex].roleIDPotentiallyAvailable)
}
}
if (match.player2 === member ){
if (match.player1.roles.cache.has(matchmakingPlatforms[match.platformIndex].roleIDLookingForOpponent)
&& match.player1.roles.cache.has(matchmakingPlatforms[match.platformIndex].roleIDInGame)){
match.player1.roles.remove(member.guild.roles.cache.get(matchmakingPlatforms[match.platformIndex].roleIDInGame))
}
else{
changeMatchmakingRole(match.player1, matchmakingPlatforms[match.platformIndex].roleIDPotentiallyAvailable)
}
}
if (match.matchAnnouncement !== null) {
log(`matchAnnouncement to delete: ${match.matchAnnouncement.content}`)
match.matchAnnouncement.delete();
log('deleted matchAnnouncement')
}
}
})
}
memberIsSeeking(member){
let isSeeking = false
this.matchSeekSet.forEach(matchSeek =>{
if (matchSeek.seeker === member) isSeeking = true
})
return isSeeking
}
//returns a matchSeek object if there is a current matchSeek where the member is the seeker
getMatchSeek(member){
let toReturn = null
this.matchSeekSet.forEach(matchSeek =>{
if (matchSeek.seeker === member){
toReturn = matchSeek
}
})
return toReturn
}
async disconnectMemberFromVoice(member){
log(`Attempting to disconnect ${member.user.username} from voice chat`)
if (member.voice.channel){
let tempChannelName = `booting-${member.user.username}`
//remove special characters from the channel name
tempChannelName = format_channel_name(tempChannelName)
log(`Trying to create temporary voice channel with name: ${tempChannelName}`)
await member.guild.channels.create(tempChannelName, {
type: 'voice',
permissionOverwrites: [{
type: 'role',
id:member.guild.id,
deny:0x400 //'VIEW_CHANNEL'
},{
type: 'member',
id:member.id,
allow:0x400 //'VIEW_CHANNEL'
},{
type: 'member',
id:member.guild.me.id, //add's permission for this bot's user to view the channel
allow:0x400 //'VIEW_CHANNEL'
}],
reason: `temp channel to remove ${member.user.username} from voice chat`})
.then(channel =>{
log(`Created Temporary channel to move ${member.user.username} to...`)
member.voice.setChannel(channel)
.then(() => {
log('Moved them. Now deleting the temporary channel')
channel.delete()
.then(() => {
log(`SUCCESS. ${member.user.username} has been disconnected from voice chat.`)
}).catch(err =>{
log(`Failed to delete the temporary Channel`)
})
}).catch(err =>{
log(`Failed to move them to the temporary channel`)
})
}).catch(err => {
log(`Failed to create temporary channel and so cannot disconnect ${member.user.username} from voice chat}`)
log(err)
})
}
else {
log(`${member.user.username} is not connected to voice`)
}
}
}
function format_channel_name(stringIn){
var arr = stringIn.split('')
var stringOut = []
for(var i = 0; i < arr.length; i++){
if (arr[i].match(/[A-Za-z0-9-_]/)){
stringOut.push(arr[i])
}
}
return stringOut.join('')
}
class Spectator{
constructor(member, match){
this.member = member
this.match = match
this.spectatorAnnouncement = null
}
createSpectatorAnnouncement(){
this.match.textChannel.send(`${this.member} has joined the chat`).then(message => {
this.spectatorAnnouncement = message
message.react(unicodeBoot)
}).catch(err=> {
log(err)
})
}
}
class Match{
constructor(matchID , player1, player2, announceChannel) {
this.id = matchID
this.player1 = player1
this.player2 = player2
this.player1StreamURL = ''
this.player2StreamURL = ''
this.textChannel = null
this.platformIndex = findIndexOfRelatedPlatform(announceChannel)
this.announceChannel = announceChannel // the channel where it is announced the match has started. may or may not use this
this.matchAnnouncement = null
this.voiceChannel = null
this.voiceChatInvite = null
this.controlPanelMessage = null
this.locked = false
this.allowOthersToJoinDelayDone = false
this.spectators = new Set()
this.coreAnnouncementMessage = ''
}
addMemberAsSpectator(memberToAdd){
log(this.textChannel.name)
if (this.memberIsAPlayerInMatch(memberToAdd) || this.memberIsASpectatorInMatch(memberToAdd)){
log(`${memberToAdd.user.username} is already in the match`)
memberToAdd.user.send(`This reaction grants you access to a match. You were already in this match. You should be able to see its channels at to top of the list.`)
}
else {
this.textChannel.createOverwrite(memberToAdd.user, {VIEW_CHANNEL: true})
this.voiceChannel.createOverwrite(memberToAdd.user, {VIEW_CHANNEL: true})
log(`applying read permission for a match's channels for ${memberToAdd.user.username}`)
let spectator = new Spectator(memberToAdd, this)
this.spectators.add(spectator)
spectator.createSpectatorAnnouncement()
}
}
removeMemberAsSpectator(memberToRemove){
let success = false
this.spectators.forEach(spectator => {
if (spectator.member.id === memberToRemove.id){
this.textChannel.createOverwrite(memberToRemove.user, {VIEW_CHANNEL: false})
this.voiceChannel.createOverwrite(memberToRemove.user, {VIEW_CHANNEL: false})
matchmaker.disconnectMemberFromVoice(spectator.member)
log(`removing read permission for a match's channels for ${memberToRemove.user.username}`)
this.spectators.delete(spectator)
success = true
}
if (!success){
log(`Failed to remove member from match because they aren't in the match as a spectator`)
}
})
}
//returns the member that is a player in a match that was not the member passed in, or null if the passed member is not a player.
otherPlayer(member){
let answer = null
if (this.player1 === member){
answer = this.player2
}else if (this.player2 === member){
answer = this.player1
}
return answer
}
memberIsAPlayerInMatch(member){
if (this.player1 === member) return true
if (this.player2 === member) return true
return false
}
memberIsASpectatorInMatch(member){
let answer = false
this.spectators.forEach(spectator => {
if (spectator.member.id === member.id) answer = true
})
return answer
}
//the following method also returns a promise of the match having been announced.
createTextChannel(){
return new Promise((resolve, reject) => {
//create Text Channel
let channelName = this.player1.user.username + '-vs-' + this.player2.user.username
let matchAnnounced = false
//remove special characters from the channel name
channelName = format_channel_name(channelName)
let channelName2 = channelName;
log(`channelName2 = ${channelName2}`)
log(`Trying to create text channel with name: ${channelName}`)
this.player1.guild.channels.create(channelName,
{
type: 'text',
permissionOverwrites:[{
type: 'role',
id:this.player1.guild.id,
deny:0x400 //'VIEW_CHANNEL'
},{
type: 'member',
id:this.player1.id,
allow:0x400 //'VIEW_CHANNEL'
},{
type: 'member',
id:this.player2.id,
allow:0x400 //'VIEW_CHANNEL'
},{
type: 'member',
id:this.player1.guild.me.id, //add's permission for this bot's user to view the channel
allow:0x400 //'VIEW_CHANNEL'
}],
reason: "match text channel"
})
.then(channel =>{
this.textChannel = channel
// TO DO: limit this.textChannel permissions
this.coreAnnouncementMessage = `${channelName} is now in progress, <@&${matchmakingPlatforms[this.platformIndex].roleIDSpectators}>!\nPlayers, please proceed to ${channel} to chat with your opponent.`
//let msg = 'CHALLENGE ACCEPTED! \nPlease proceed to ' + channel
this.announceChannel.send(this.coreAnnouncementMessage)
.then(messageSentSuccessfully => {
this.matchAnnouncement = messageSentSuccessfully
log('announced message for ' + channel.name)
matchAnnounced = true
resolve(this.matchAnnouncement)
}).catch(err => {
log('failed to announce ' + channel.name)
matchAnnounced = false
reject(err)
})
log(this.coreAnnouncementMessage)
let controlPanelMessageContent = `${this.player1} vs ${this.player2}\n\n**Match Control Panel**\n:unlock: (Default) Allow other people to join chat (text/voice)\n:lock: Do not allow other people to join chat\n:white_check_mark: Look for a new opponent\n:bell: Leave match and change me to Potentially Available\n:no_bell: Leave match and change me to Do Not Notify`
this.textChannel.send(controlPanelMessageContent)
.then(async controlPanelMessage =>{
this.controlPanelMessage = controlPanelMessage
await this.controlPanelMessage.react(reactionIdentUnlock)
await this.controlPanelMessage.react(reactionIdentLock)
await this.controlPanelMessage.react(matchmakingPlatforms[this.platformIndex].reactionIdentLookingForOpponent)
await this.controlPanelMessage.react(matchmakingPlatforms[this.platformIndex].reactionIdentPotentiallyAvailable)
await this.controlPanelMessage.react(matchmakingPlatforms[this.platformIndex].reactionIdentDND)
})
.catch(err =>{
log(`Match channel creation failed. Here's the error:`)
log(err)
let errmsg = `MATCH ACCEPTED! ${this.player1} vs ${this.player2}\n Match channel creation failed. Please DM eachother`
//let errmsg = 'CHALLENGE ACCEPTED!\n Match channel creation failed. Please DM eachother'
this.announceChannel.send(errmsg)
})
.then(() => {
//wait 10 seconds before adding a button for other users to join chat
//this is to allow time for a player to lock the chat before a non-player jumps in.
//granted, this is imperfect because the user could react themselves before the bot adds the reaction.
sleep(delayInSecBeforeNonPlayersCanJoinChat*1000).then(async ()=>{
//if the match chat isn't locked already
log('It is now 10 seconds after the match start')
if(!this.locked && !this.allowOthersToJoinDelayDone){
log('Conditions met for adding reactions to the announcement')
try{
await this.matchAnnouncement.react(reactionIdentUnlock)
await this.matchAnnouncement.react(reactionIdentGetMatchChannelPermissions)
this.allowOthersToJoinDelayDone = true
}
catch (err) {
log('Did not add room-join reactions to the match announcement')
log('Perhaps the room has already been closed? Here\'s the error:')
log(err)
}
}else{
log('Conditions not met for adding reactions to the announcement')
}
})
})
//maybe not here, but TO DO: remove any messages from the matchSeek.
})
})
}
checkAndUpdateStreams(){
let linkAdded = null
//log(`(this.player1StreamURL === '') is ${this.player1StreamURL === ''}`)
//log(`this.player1StreamURL is: ${this.player1StreamURL}`)
if (this.player1.presence.activities && this.player1.presence.activities.some(activity => activity.type === 'STREAMING') && this.player1StreamURL === ''){
this.player1StreamURL = this.player1.presence.activities.find(activity => activity.type === 'STREAMING').url
linkAdded = this.player1StreamURL
}
//log(`streamAdded for p1 is: ${streamAdded}`)
//log(`now, this.player1StreamURL is: ${this.player1StreamURL}`)
if (this.player2.presence.activities && this.player2.presence.activities.some(activity => activity.type === 'STREAMING') && this.player2StreamURL === ''){
this.player2StreamURL = this.player2.presence.activities.find(activity => activity.type === 'STREAMING').url
linkAdded = this.player2StreamURL
}
if (linkAdded){
this.refreshMatchAnnouncementMessage()
}
return linkAdded
}
refreshMatchAnnouncementMessage(){
let newMessageContent = ''
newMessageContent = this.coreAnnouncementMessage
if (this.player1StreamURL !== ''){
newMessageContent += `\n${this.player1.user.username}'s stream: <${this.player1StreamURL}>`
}
if (this.player2StreamURL !== ''){
newMessageContent += `\n${this.player2.user.username}'s stream: <${this.player2StreamURL}>`
}
this.matchAnnouncement.edit(newMessageContent)
}
updateMatchAnnouncementMessage(newMessage){
this.matchAnnouncement.edit(newMessage)
}
appendToMatchAnnouncementMessage(stringToAppend){
this.matchAnnouncement.edit(`${this.matchAnnouncement.content}\n${stringToAppend}`)
}
async createVoiceChannel(){
let channelName = `voice-${this.player1.user.username}-vs-${this.player2.user.username}`
//remove special characters from the channel name
channelName = format_channel_name(channelName)
let channelName2 = channelName;
log(`channelName2 = ${channelName2}`)
log(`Trying to create channel with name: ${channelName}`)
await this.player1.guild.channels.create(channelName,
{
type: 'voice',
permissionOverwrites:
[{
type: 'role',
id:this.player1.guild.id,
deny:0x400 //'VIEW_CHANNEL'
},{
type: 'member',
id:this.player1.id,
allow:0x400 //'VIEW_CHANNEL'
},{
type: 'member',
id:this.player2.id,
allow:0x400 //'VIEW_CHANNEL'
},{
type: 'member',
id:this.player1.guild.me.id, //add's permission for this bot's user to view the channel
allow:0x400 //'VIEW_CHANNEL'
}],
reason: 'match voice channel'
})
.then(channel =>{
log('assigning voiceChannel property')
this.voiceChannel = channel
log('done assigning voiceChannel')
log(this.voiceChannel)
})
}
lockChat(){
this.locked = true
this.allowOthersToJoinDelayDone = true
//change the permissions of this.textChannel and this.voiceChannel such that they no longer have permissions for Everyone to view them.
}
unlockChat(){
this.locked = false
this.allowOthersToJoinDelayDone = true
//change the permissions of this.textChannel and this.voiceChannel such that they do have permissions for Everyone to view them.
}
}
class MatchSeek {
constructor(seeker, textChannel, pingAllowed) {
this.seeker = seeker;
this.textChannel = textChannel;
this.platformIndex = findIndexOfRelatedPlatform(textChannel)
this.challenges = new Set();
this.pingAllowed = pingAllowed;
this.message = null;
this.coreMessageContent = ''
this.customMessage = ''
this.controlPanelMessage = null
this.allowOthersToJoinDelayDone = false
}
addChallenge(challenge){
this.challenges.add(challenge)
}
removeChallenge(challenge){
this.challenges.delete(challenge)
challenge.message.delete()
}
/*async sendMessage() {
}*/
}
class Challenge {
constructor(challenger, matchSeek) {
this.challenger = challenger; //the member who is challenging somebody
this.matchSeek = matchSeek;
this.message = null;
this.pingAllowed = true; // whether the message sent will ping the match seeker, alllowed by default
}
allowPing(pingAllowed){
if (typeof pingAllowed == 'boolean'){
this.pingAllowed = pingAllowed;
}
}
async challengeMatchSeek() {
let messageContent = this.challenger.toString()
let skillRoleString = getSkillRoleString(this.challenger);
if (skillRoleString !== '') messageContent += ` (${skillRoleString})`
messageContent += ' offers to play with ';
if (this.pingAllowed){
messageContent += this.matchSeek.seeker.toString();
}
else{
messageContent += this.matchSeek.seeker.user.username;
}
let message;
try {
message = await this.matchSeek.textChannel.send(messageContent);
await this.matchSeek.addChallenge(this);
this.message = message;
await this.message.react(reactionIdentAcceptChallenge);
log(this.challenger.user.username + ' offers to play with ' + this.matchSeek.seeker.user.username);
return true
} catch (err) {
log('Challenge creation failed');
log(err);
return false;
}
//log(this)
//log(`New Challenge created:\nseeker: ${this.matchSeek.seeker.username}\nchallenger: ${this.challenger.username}\ntextChannel: ${this.message.textChannel}\n`);
//log('New Challenge created:\nseeker: ' + this.matchSeek.seeker.username + '}\nchallenger: ' + this.challenger.username)
}
}
//determine which platform uses the newRoleID
function findIndexOfRelatedPlatform(searchTerm){
return matchmakingPlatforms.findIndex(function(platform){
return Object.keys(platform).findIndex(key => platform[key] === searchTerm) !== -1
})
//returns -1 if platform isn't found
}
function findPlatformHavingName(name){
return matchmakingPlatforms.find(platform => platform.platformName === name)
}
async function changeMatchmakingRole(member, newRoleID) {
//if the member is a bot, don't do anything
if (member.bot) return;
//determine which platform uses the newRoleID
var platformIndex
var platform = null
await (platformIndex = findIndexOfRelatedPlatform(newRoleID))
if (platformIndex === -1) {
log(`Error: platform not found with given newRoleID ${newRoleID}`)
return
}
else{
platform = matchmakingPlatforms[platformIndex]
}
if (!lastMatchmakingActivity[platformIndex]){
lastMatchmakingActivity[platformIndex] = {}
}
lastMatchmakingActivity[platformIndex][member.id] = Date.now()
//do stuff depending on what matchmaking role roleString represents
if (newRoleID === platform.roleIDLookingForOpponent) {
member.roles.remove([platform.roleIDLookingForOpponent,platform.roleIDPotentiallyAvailable,platform.roleIDDoNotNotify,roleIDNewMember,roleIDInactive]);//but don't remove "in-game" role, to allow looking while in-game
if (!matchmaker.memberIsInAMatch(member)){
log(`member not in a match. also removing @in-game`)
sleep(500).then(() =>{
member.roles.remove(platform.roleIDInGame)
})
}
// pause a moment for roles to be finished being removed
sleep(500).then(() => {
//assign '@looking for Opponent'
var role = member.guild.roles.cache.find(x => x.id === platform.roleIDLookingForOpponent);
member.roles.add(role);
log('Added role \'@Looking for Opponent\' for platform ' + platform.platformName + ' to member ' + member.user.username);
//send a message in the matchmaking channel alerting people that a user wants to play
sleep(1).then(async function(){
const matchSeekToAdd = new MatchSeek(member, platform.matchmakingTextChannel, true);
//await matchSeekToAdd.sendMessage();
//if (matchSeekToAdd.message){
if(matchmaker.addMatchSeek(matchSeekToAdd)){
log('added match seek to matchSeekSet')
}
else(
log('did not add match seek to matchSeekSet')
)
// log('matchseek added to list');
//} else {
// log('matchseek message was null');
//}
});
/*sleep(1).then(async function(){
let matchSeekToAdd = await new MatchSeek(member, matchmakingTextChannel, true)
await sleep(2000).then(() =>{
if (matchSeekToAdd.message !== null){
currentMatchSeekSet.add(matchSeekToAdd)
log('matchseek added to list')
}
else{
log('matchseek message was null')
}
});
})*/
//matchmakingTextChannel.send(member.user + ' **is looking for an opponent!**\n\n<@&' + roleIDLookingForOpponent+ '> <@&' + roleIDPotentiallyAvailable + '>')
})
return;
}
if (newRoleID === platform.roleIDPotentiallyAvailable) {
removeAllMatchmakingRoles(member, platformIndex);
// pause a moment for roles to be finished being removed
sleep(500).then(() => {
//assign '@looking for Opponent'
var role = member.guild.roles.cache.find(x => x.id === platform.roleIDPotentiallyAvailable);
member.roles.add(role);
log('Added role \'@Potentially available\' for platform ' + platform.platformName + ' to member ' + member.user.username);
//cancel any existing game seek
})
return;
}
if (newRoleID === platform.roleIDDoNotNotify) {
removeAllMatchmakingRoles(member, platformIndex); //todo: have this function remove all matchmaking roles on all platforms if a platform is not specified.
// pause a moment for roles to be finished being removed
sleep(500).then(() => {
//assign '@looking for Opponent'
var role = member.guild.roles.cache.find(x => x.id === platform.roleIDDoNotNotify);
member.roles.add(role);
log('Added role \'@Do Not Notify\' to member ' + member.user.username);
//cancel any existing game seek
})
return;
}
if (newRoleID === platform.roleIDInGame) {
removeAllMatchmakingRoles(member) //if they are going to in-game status, we remove all matchmaking roles from all platforms
// pause a moment for roles to be finished being removed
sleep(500).then(() => {
//assign '@in-game'
var role = member.guild.roles.cache.find(x => x.id === platform.roleIDInGame);
member.roles.add(role);
log('Added role \'@In-Game\' to member ' + member.user.username);
//cancel any existing game seek
})
return;
}
// if we are here, we didn't return, so we didn't change a role
log('Role for member ' + member.user.username + ' not changed because \'' + roleString + '\' is not a valid role name')
}
function addRoleToMember(roleID, member){
var role = member.guild.roles.cache.find(x => x.id === roleID);
member.roles.add(role);
log('Added role ' + role.name + ' to member ' + member.user.username);
}
//the following function removes all matchmaking roles. Note: this should be given a half second
//before code with subsequent role changes gets run.
//use like this, for example:
/*
removeAllMatchmakingRoles(member)
sleep(500).then(() => {
// Do the stuff that should follow the removeAllMatchmakingRoles function call
})
*/
function removeAllMatchmakingRoles(member, platformIndex) {
try{
var rolesToRemove = []
matchmakingPlatforms.forEach(platform =>{
//removes all matchmaking roles in a given platform, or for all platforms if platformIndex isn't specified
if (typeof platformIndex == "undefined" || platform.platformName === matchmakingPlatforms[platformIndex].platformName){
rolesToRemove = rolesToRemove.concat([platform.roleIDInGame,platform.roleIDLookingForOpponent,platform.roleIDPotentiallyAvailable,platform.roleIDDoNotNotify])
log(`removing all matchmaking roles for platform ${platform.platformName} from ${member.user.username}...`)
}
})
rolesToRemove = rolesToRemove.concat([roleIDNewMember,roleIDInactive])
log(`removing roles: ${rolesToRemove.toString()}`)
member.roles.remove(rolesToRemove)
}
catch(err){
log(`Error in removeAllMatchMakingRoles:`)
log(err)
}
}
function removeAllSkillRoles(member) {
//remove all skill roles
member.roles.remove([roleIDMaster, roleIDDiamond, roleIDPlatinum, roleIDGold, roleIDSilver, roleIDBronze, roleIDMasterPending, roleIDDiamondPending, roleIDPlatinumPending])
log('removing all skill roles from ' + member.user.username + '...')
}
function changeSkillRole(member, roleString){
//if roleString represents a valid role
if(validSkillRoleStrings.indexOf(roleString) > -1){
removeAllSkillRoles(member)
sleep(500).then(() => {
let roleID = member.guild.roles.cache.find(x => x.name === roleString).id
addRoleToMember(roleID, member)
});
if(roleString.includes("pending")){
//message the member
try{
member.send('Thank you for taking the skill survey! Note: for skill levels above Gold, your skill role will say "(pending verification)" on the end of it. After you\'ve proved your skill by playing well enough against players of the skill level you\'ve selected, a moderator can give you the appropriate role without the "(pending verification)" on the end.')
} catch (err) {
log('Failed to send member a message, perhaps they have blocked DMs?')