-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathafkCheck.js
More file actions
1323 lines (1182 loc) · 74.7 KB
/
afkCheck.js
File metadata and controls
1323 lines (1182 loc) · 74.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const Discord = require('discord.js')
const fs = require('fs')
const ErrorLogger = require('../lib/logError')
const AfkTemplate = require('./afkTemplate.js')
const pointLogger = require('../lib/pointLogger')
const extensions = require(`../lib/extensions`)
const consumablePopTemplates = require(`../data/keypop.json`);
const popCommand = require('./pop.js');
const AfkButton = require('../lib/afk/AfkButton');
const { writePoint } = require('../metrics.js');
const { Point } = require('@influxdata/influxdb-client');
module.exports = {
name: 'afk',
description: 'The new version of the afk check',
requiredArgs: 1,
args: '<run symbol> <location>',
role: 'eventrl',
/**
* Main Execution Function
* @param {Discord.Message} message
* @param {String[]} args
* @param {Discord.Client} bot
* @param {import('mysql').Connection} db
*/
async execute(message, args, bot, db) {
let alias = args.shift().toLowerCase()
const afkTemplateNames = await AfkTemplate.resolveTemplateAlias(bot.settings[message.guild.id], message.member, message.guild.id, message.channel.id, alias)
if (afkTemplateNames instanceof AfkTemplate.AfkTemplateValidationError) return message.channel.send(afkTemplateNames.message())
if (afkTemplateNames.length == 0) return await message.channel.send('This afk template does not exist.')
const afkTemplateName = afkTemplateNames.length == 1 ? afkTemplateNames[0] : await AfkTemplate.templateNamePrompt(message, afkTemplateNames)
const afkTemplate = await AfkTemplate.AfkTemplate.tryCreate(bot, bot.settings[message.guild.id], message, afkTemplateName)
if (afkTemplate instanceof AfkTemplate.AfkTemplateValidationError) {
if (afkTemplate.invalidChannel()) await message.delete()
await message.channel.send(afkTemplate.message())
return
}
let location = args.join(' ')
if (location.length >= 1024) return await message.channel.send('Location must be below 1024 characters, try again')
if (location == '') location = 'None'
message.react('✅')
const afkModule = new afkCheck(afkTemplate, bot, db, message, location)
await afkModule.createChannel()
await afkModule.sendButtonChoices()
await afkModule.sendInitialStatusMessage()
if (afkTemplate.startDelay > 0) setTimeout(() => afkModule.start(), afkTemplate.startDelay*1000)
else afkModule.start()
},
returnRaidIDsbyMemberID(bot, memberID) {
return Object.keys(bot.afkChecks).filter(raidID => bot.afkChecks[raidID].leader == memberID)
},
returnRaidIDsbyMemberVoice(bot, voiceID) {
return Object.keys(bot.afkChecks).filter(raidID => bot.afkChecks[raidID].channel == voiceID)
},
returnRaidIDsbyRaidID(bot, RSAID) {
return Object.keys(bot.afkChecks).filter(raidID => bot.afkChecks[raidID].raidStatusMessage && bot.afkChecks[raidID].raidStatusMessage.id == RSAID)
},
returnRaidIDsbyAll(bot, memberID, voiceID, argument) {
return [...new Set([
...this.returnRaidIDsbyMemberID(bot, memberID),
...this.returnRaidIDsbyMemberVoice(bot, voiceID),
...this.returnRaidIDsbyMemberVoice(bot, argument),
...this.returnRaidIDsbyRaidID(bot, argument)
])]
},
returnActiveRaidIDs(bot) {
return Object.keys(bot.afkChecks)
},
async loadBotAfkChecks(guild, bot, db) {
const storedAfkChecks = Object.values(require('../data/afkChecks.json')).filter(raid => raid.guild.id === guild.id);
for (const currentStoredAfkCheck of storedAfkChecks) {
const messageChannel = guild.channels.cache.get(currentStoredAfkCheck.message.channelId)
const message = await messageChannel.messages.fetch(currentStoredAfkCheck.message.id)
const afkTemplateName = currentStoredAfkCheck.afkTemplateName
const afkTemplate = await AfkTemplate.AfkTemplate.tryCreate(bot, bot.settings[message.guild.id], message, afkTemplateName)
if (afkTemplate instanceof AfkTemplate.AfkTemplateValidationError) {
console.log(afkTemplate.message())
continue
}
writePoint(new Point('afkchecksmodules')
.tag('raidID', currentStoredAfkCheck.raidID)
.stringField('module', 'insert'))
bot.afkModules[currentStoredAfkCheck.raidID] = new afkCheck(afkTemplate, bot, db, message, currentStoredAfkCheck.location)
await bot.afkModules[currentStoredAfkCheck.raidID].loadBotAfkCheck(currentStoredAfkCheck)
}
console.log(`Restored ${storedAfkChecks.length} afk checks for ${guild.name}`);
}
}
class afkCheck {
/**
* @param {AfkTemplate.AfkTemplate} afkTemplate
* @param {Discord.Client} bot
* @param {import('mysql').Connection} db
* @param {Discord.Message} message
* @param {String} location
*/
#bot;
#botSettings;
#db;
#afkTemplate;
#message;
#guild;
#channel;
#leader;
#raidID;
#pointlogMid;
#body = null;
constructor(afkTemplate, bot, db, message, location) {
this.#bot = bot // bot
this.#botSettings = bot.settings[message.guild.id] // bot settings
this.#afkTemplate = afkTemplate // static AFK template
this.#db = db // bot database
this.#message = message // message of the afk
this.#guild = message.guild // guild of the afk
this.#channel = null // channel of the afk
this.#leader = message.member // leader of the afk
this.#raidID = null // ID of the afk
this.#pointlogMid = null
this.members = [] // All members in the afk
this.staffEarlyMembers = [] // Staff members who clicked nitro to join the AFK
this.buttons = afkTemplate.buttons.map(button => new AfkButton(this.#botSettings, this.#bot.storedEmojis, this.#guild, button))
this.reactRequests = {} // {messageId => AfkButton}
this.cap = afkTemplate.cap
this.location = location // Location of the afk
this.singleUseHotfixStopTimersDontUseThisAnywhereElse = false // DO NOT USE THIS. ITS A HOTFIX. https://canary.discord.com/channels/343704644712923138/706670131115196588/1142549685719027822
// Phase 0 is a special case, before start delay has expired
this.phase = this.#afkTemplate.startDelay > 0 ? 0 : 1 // Current phase of the afk
this.timer = null // End time of the current phase of the AFK (Date)
this.completes = 0 // Number of times the afk has been completed
this.logging = false // Whether logging is active
this.ended_by = null
this.raidStatusMessage = null // raid status message
this.raidStatusInteractionHandler = null // raid status interaction handler
this.raidCommandsMessage = null // raid commands message
this.raidInfoMessage = null // raid info message
this.raidCommandsInteractionHandler = null // raid commands interaction handler
this.raidChannelsMessage = null // raid channels message
this.raidChannelsInteractionHandler = null // raid channels interaction handler
}
get active() {
return !(this.ended_by || this.aborted_by || this.deleted_by)
}
get vcLounge() {
return this.#guild.channels.cache.get(this.#botSettings.voice.lounge)
}
get guild() { return this.#guild }
get vcOptions() { return this.#afkTemplate.vcOptions }
get channel() { return this.#channel }
// needed for parsemembers
get afkTemplateName() { return this.#afkTemplate.templateName }
// needed for location command
get leader() { return this.#leader }
isVcless() { return this.vcOptions == AfkTemplate.TemplateVCOptions.NO_VC }
raidLeaderDisplayName() {
return this.#leader.displayName.replace(/[^a-z|]/gi, '').split('|')[0]
}
afkTitle() {
return `${this.raidLeaderDisplayName()}'s ${this.#afkTemplate.name}`
}
#pingText() {
return this.#afkTemplate.pingRoles ? `${this.#afkTemplate.pingRoles.join(' ')}, ` : ``
}
async start() {
if (this.phase === 0) this.phase = 1
this.timer = new Date(Date.now() + (this.#body[this.phase].timeLimit * 1000))
writePoint(new Point('afkchecksmodules')
.tag('raidID', this.#raidID)
.stringField('module', 'insert'))
this.#bot.afkModules[this.#raidID] = this
await Promise.all([this.sendStatusMessage(), this.sendCommandsMessage(), this.sendChannelsMessage()])
this.startTimers()
this.saveBotAfkCheck()
}
get flag() {
return this.location ? {'us': ':flag_us:', 'eu': ':flag_eu:'}[this.location.toLowerCase().substring(0, 2)] : ''
}
saveBotAfkCheck(deleteCheck = false) {
if (deleteCheck) {
writePoint(new Point('afkchecksmodules')
.tag('raidID', this.#raidID)
.stringField('check', 'delete')
.stringField('module', 'delete'))
delete this.#bot.afkChecks[this.#raidID]
delete this.#bot.afkModules[this.#raidID]
}
else {
writePoint(new Point('afkchecksmodules')
.tag('raidID', this.#raidID)
.stringField('check', 'create'))
this.#bot.afkChecks[this.#raidID] = {
afkTemplateName: this.afkTemplateName,
message: this.#message,
guild: this.#guild,
channel: this.#channel,
leader: this.#leader,
raidID: this.#raidID,
members: this.members,
staffEarlyMembers: this.staffEarlyMembers,
buttons: this.buttons.map(button => button.toJSON()),
reactRequests: Object.fromEntries(Object.entries(this.reactRequests).map(([messageId, button]) => [messageId, {name: button.name, ...button.toJSON()}])),
body: this.#body,
cap: this.cap,
time: Date.now(),
location: this.location,
phase: this.phase,
timer: this.timer.getTime(),
completes: this.completes,
ended_by_id: this.ended_by?.id,
aborted_by: this.aborted_by,
deleted_by: this.deleted_by,
raidStatusMessage: this.raidStatusMessage,
raidCommandsMessage: this.raidCommandsMessage,
pointlogMid: this.#pointlogMid,
raidInfoMessage: this.raidInfoMessage,
raidChannelsMessage: this.raidChannelsMessage,
}
}
writePoint(new Point('afkchecksmodules')
.tag('raidID', this.#raidID)
.booleanField('fileWrite', true))
fs.writeFileSync('./data/afkChecks.json', JSON.stringify(this.#bot.afkChecks, null, 4), err => { if (err) ErrorLogger.log(err, this.#bot, this.#guild) })
}
async loadBotAfkCheck(storedAfkCheck) {
this.#channel = storedAfkCheck.channel ? this.#guild.channels.cache.get(storedAfkCheck.channel.id) : null
this.#raidID = storedAfkCheck.raidID
this.members = storedAfkCheck.members
this.staffEarlyMembers = this.staffEarlyMembers
this.buttons = storedAfkCheck.buttons.map(button => new AfkButton(this.#botSettings, this.#bot.storedEmojis, this.#guild, {...this.#afkTemplate.getButton(button.name), ...button}))
this.reactRequests = Object.fromEntries(Object.entries(storedAfkCheck.reactRequests).map(([messageId, button]) => [messageId, new AfkButton(this.#botSettings, this.#bot.storedEmojis, this.#guild, {...this.#afkTemplate.getButton(button.name), ...button})]))
this.#body = storedAfkCheck.body
this.cap = storedAfkCheck.cap
this.location = storedAfkCheck.location
this.phase = storedAfkCheck.phase
this.timer = new Date(storedAfkCheck.timer)
this.completes = storedAfkCheck.completes
this.ended_by = this.#guild.members.cache.get(storedAfkCheck.ended_by_id)
// deleted or aborted afk checks are not saved in the json
this.deleted_by = null
this.aborted_by = null
this.raidStatusMessage = await this.#afkTemplate.raidStatusChannel.messages.fetch(storedAfkCheck.raidStatusMessage.id)
this.raidCommandsMessage = await this.#afkTemplate.raidCommandChannel.messages.fetch(storedAfkCheck.raidCommandsMessage.id)
this.raidInfoMessage = await this.#afkTemplate.raidInfoChannel.messages.fetch(storedAfkCheck.raidInfoMessage.id)
this.raidChannelsMessage = await this.#afkTemplate.raidActiveChannel.messages.fetch(storedAfkCheck.raidChannelsMessage.id)
this.#pointlogMid = storedAfkCheck.pointlogMid
if (this.phase <= this.#afkTemplate.phases && !this.ended_by) this.start()
else {
this.raidStatusInteractionHandler = new Discord.InteractionCollector(this.#bot, { message: this.raidStatusMessage, interactionType: Discord.InteractionType.MessageComponent, componentType: Discord.ComponentType.Button })
this.raidStatusInteractionHandler.on('collect', interaction => this.interactionHandler(interaction))
this.raidCommandsInteractionHandler = new Discord.InteractionCollector(this.#bot, { message: this.raidCommandsMessage, interactionType: Discord.InteractionType.MessageComponent, componentType: Discord.ComponentType.Button })
this.raidCommandsInteractionHandler.on('collect', (interaction) => this.interactionHandler(interaction))
this.raidChannelsInteractionHandler = new Discord.InteractionCollector(this.#bot, { message: this.raidChannelsMessage, interactionType: Discord.InteractionType.MessageComponent, componentType: Discord.ComponentType.Button })
this.raidChannelsInteractionHandler.on('collect', (interaction) => this.interactionHandler(interaction))
this.saveBotAfkCheck()
if (this.active) this.postAfk(null)
}
}
async createChannel() {
if (this.#afkTemplate.vcOptions == AfkTemplate.TemplateVCOptions.NO_VC) return
else if (this.#afkTemplate.vcOptions == AfkTemplate.TemplateVCOptions.STATIC_VC) return this.#channel = this.#leader.voice.channel
let channel = await this.#afkTemplate.raidTemplateChannel.clone({
name: this.afkTitle(),
parent: this.#afkTemplate.raidCategory.id,
userLimit: this.cap,
position: 0
})
await this.#leader.voice.setChannel(channel).catch(er => {})
for (let minimumViewRaiderRole of this.#afkTemplate.minimumViewRaiderRoles) await channel.permissionOverwrites.edit(minimumViewRaiderRole.id, { Connect: false, ViewChannel: true }).catch(er => ErrorLogger.log(er, this.#bot, this.#guild))
for (let minimumJoinRaiderRole of this.#afkTemplate.minimumJoinRaiderRoles) await channel.permissionOverwrites.edit(minimumJoinRaiderRole.id, { Connect: false, ViewChannel: true }).catch(er => ErrorLogger.log(er, this.#bot, this.#guild))
await channel.permissionOverwrites.edit(this.#leader.id, { Connect: true, ViewChannel: true, Speak: true }).catch(er => ErrorLogger.log(er, this.#bot, this.#guild))
this.#channel = channel
}
async sendButtonChoices() {
for (const [buttonIdx, button] of this.buttons.entries()) {
await button.choicePrompt(this.#message, this.#leader);
if (button.limit == 0 && button.choice != AfkTemplate.TemplateButtonChoice.NO_CHOICE) this.buttons.splice(buttonIdx, 1)
}
}
startTimers() {
if (this.#channel) this.moveInEarlysTimer = setInterval(() => this.moveInEarlys(), 10000)
let updatePanelTimer = setInterval((updatePanelTimer) => this.updatePanel(updatePanelTimer), 5000)
this.updatePanelTimer = updatePanelTimer
}
async moveInEarlys() {
for (let i of this.earlySlotMembers()) {
let member = this.#guild.members.cache.get(i)
if (!member.voice.channel) continue
if (member.voice.channel.name.includes('lounge') || member.voice.channel.name.includes('Lounge') || member.voice.channel.name.includes('drag')) await member.voice.setChannel(this.#channel.id).catch(er => { })
}
}
#timerSecondsRemaining() {
return Math.round((this.timer - new Date()) / 1000)
}
async updatePanel(timer) {
if (this.singleUseHotfixStopTimersDontUseThisAnywhereElse) return clearInterval(timer)
const secondsRemaining = this.#timerSecondsRemaining()
if (secondsRemaining <= 0) return this.processPhaseNext()
if (!this.raidStatusMessage) return
let reactables = this.getReactables(this.phase)
let components = reactables.concat(this.getPhaseControls(this.phase))
await Promise.all([
this.raidStatusMessage?.edit({ embeds: [this.#genRaidStatusEmbed()], components: components }),
this.raidCommandsMessage?.edit(this.#genRaidCommands()),
this.raidInfoMessage?.edit(this.#genRaidInfo()),
this.raidChannelsMessage?.edit(this.#genRaidChannels())
].filter(i => i))
}
#genEmbedFooter() {
if (this.aborted_by) return { text: `${this.#guild.name} • Aborted by ${this.aborted_by.nickname}`, iconURL: this.#guild.iconURL() }
if (this.deleted_by) return { text: `${this.#guild.name} • Deleted by ${this.deleted_by.nickname}`, iconURL: this.#guild.iconURL() }
if (this.ended_by) return { text: `${this.#guild.name} • Ended by ${this.ended_by.nickname}`, iconURL: this.#guild.iconURL() }
const secondsRemaining = this.#timerSecondsRemaining()
return { text: `${this.#guild.name} • ${Math.floor(secondsRemaining / 60)} Minutes and ${secondsRemaining % 60} Seconds Remaining`, iconURL: this.#guild.iconURL() }
}
#genEmbedBase() {
return new Discord.EmbedBuilder()
.setAuthor({ name: `AFK for ${this.#afkTemplate.name} by ${this.raidLeaderDisplayName()}`, iconURL: this.#leader.user.avatarURL() })
.setColor(this.#body[this.phase || 1].embed.color ? this.#body[this.phase || 1].embed.color : '#ffffff')
.setTimestamp(Date.now())
}
#genRaidStatusEmbed() {
const afkTemplateBody = this.#body[this.phase || 1]
const embed = this.#genEmbedBase()
// This RNG might need to get fixed or it will change every time the embed is generated
if (afkTemplateBody.embed.thumbnail) embed.setThumbnail(afkTemplateBody.embed.thumbnail[Math.floor(Math.random()*afkTemplateBody.embed.thumbnail.length)])
if (this.phase == 0) {
embed.setDescription(`\`${this.#afkTemplate.name}\`${this.flag ? ` in (${this.flag})` : ''} will begin in ${Math.round(this.#afkTemplate.startDelay)} seconds. Be prepared to join the raid.`)
embed.setFooter({ text: this.#guild.name, iconURL: this.#guild.iconURL() })
} else {
if (!(this.aborted_by || this.deleted_by) && afkTemplateBody.embed.image) embed.setImage(this.#botSettings.strings[afkTemplateBody.embed.image] ? this.#botSettings.strings[afkTemplateBody.embed.image] : afkTemplateBody.embed.image)
if (this.aborted_by) {
embed.setDescription(`This afk check has been aborted`)
} else if (this.ended_by) {
embed.setDescription(`This afk check has been ended.${this.#afkTemplate.vcOptions != AfkTemplate.TemplateVCOptions.NO_VC ? ` If you get disconnected during the run, **JOIN LOUNGE** *then* press the huge **RECONNECT** button` : ``}`)
} else {
embed.setDescription(afkTemplateBody.embed.description)
}
embed.setFooter(this.#genEmbedFooter())
}
return embed
}
#genRaidStatus() {
let components = this.getReactables(this.phase).concat(this.getPhaseControls(this.phase))
if (this.aborted_by || this.deleted_by) components = []
else if (this.ended_by) components = this.addReconnectButton()
return { embeds: [this.#genRaidStatusEmbed()], components }
}
#genRaidCommandsEmbed() {
const embed = this.#genEmbedBase()
embed.setDescription(`**Raid Leader: ${this.#leader} \`\`${this.#leader.nickname}\`\`\nVC: ${this.#channel ? this.#channel : "VCLess"}\nLocation:** \`\`${this.location}\`\` ${this.flag ? ` in (${this.flag})` : ''}`)
embed.setFooter(this.#genEmbedFooter())
for (const button of this.buttons) {
embed.addFields({ name: button.memberListLabel(false), value: button.memberList(), inline: true })
}
for (const button of Object.values(this.reactRequests)) {
embed.addFields({ name: button.memberListLabel(true), value: button.memberList(), inline: true })
}
return embed
}
#genRaidCommands() {
let components = this.getPhaseControls()
if (this.aborted_by || this.deleted_by) components = []
else if (this.ended_by) components = this.addDeleteandLoggingButtons()
return { embeds: [this.#genRaidCommandsEmbed()], components }
}
#genRaidInfoEmbed() {
const embed = this.#genRaidCommandsEmbed()
if (this.ended_by) {
if (this.#pointlogMid) embed.addFields({ name: 'Points Log MID', value: this.#pointlogMid })
let raiders_text = `Raiders`
let raiders_value = `None!`
this.members.forEach(m => {
if (raiders_value.length >= 1000) {
embed.addFields({ name: raiders_text, value: raiders_value })
raiders_text = `-`
raiders_value = `, <@!${m}>`
} else raiders_value == 'None!' ? raiders_value = `<@!${m}>` : raiders_value += `, <@!${m}>`
})
embed.addFields({ name: raiders_text, value: raiders_value })
}
return embed
}
#genRaidInfo() {
return { embeds: [this.#genRaidInfoEmbed()] }
}
#genRaidChannelsEmbed() {
const embed = this.#genEmbedBase()
if (this.getLoggingText()) embed.addFields({ name: `Logging Info`, value: this.getLoggingText(), inline: false })
embed.setDescription(`**Raid Leader: ${this.#leader} \`\`${this.#leader.nickname}\`\`\nVC: ${this.#channel ? this.#channel : "VCLess"}\nLocation:** \`\`${this.location}\`\` ${this.flag ? ` in (${this.flag})` : ''}\n\nWhenever the run is over. Click the button to delete the channel.`)
embed.setFooter(this.#genEmbedFooter())
return embed
}
#genRaidChannels() {
let components = this.getPhaseControls()
if (!this.active) components = this.addDeleteandLoggingButtons()
return { content: `${this.#leader}`, embeds: [this.#genRaidChannelsEmbed()], components }
}
async sendInitialStatusMessage() {
this.#body = this.#afkTemplate.processBody(this.#channel)
const raidStatusMessageContents = {
content: `${this.#pingText()}**${this.#afkTemplate.name}** ${this.flag ? ` (${this.flag})` : ''} by ${this.#leader} is starting inside of **${this.#guild.name}**${this.#channel ? ` in ${this.#channel}` : ``}`,
embeds: [this.#afkTemplate.startDelay > 0 ? this.#genRaidStatusEmbed() : null]
};
[this.raidStatusMessage] = await Promise.all([
this.#afkTemplate.raidStatusChannel.send(raidStatusMessageContents),
this.#body[1].message && this.#afkTemplate.raidStatusChannel.send({ content: `${this.#body[1].message} in 5 seconds...` }).then(msg => setTimeout(async () => await msg.delete(), 5000)),
...Object.values(this.#afkTemplate.raidPartneredStatusChannels).map(channel => channel.send({ content: `**${this.#afkTemplate.name}** is starting inside of **${this.#guild.name}**${this.#channel ? ` in ${this.#channel}` : ``}` }))
])
this.raidStatusInteractionHandler = new Discord.InteractionCollector(this.#bot, { message: this.raidStatusMessage, interactionType: Discord.InteractionType.MessageComponent, componentType: Discord.ComponentType.Button })
this.raidStatusInteractionHandler.on('collect', interaction => this.interactionHandler(interaction))
this.#raidID = this.raidStatusMessage.id
}
async sendStatusMessage() {
this.raidStatusMessage = await this.raidStatusMessage.edit({ content: `${this.#pingText()}**${this.#afkTemplate.name}** ${this.flag ? ` (${this.flag})` : ''}`, ...this.#genRaidStatus() })
if (!this.raidStatusInteractionHandler) {
this.raidStatusInteractionHandler = new Discord.InteractionCollector(this.#bot, { message: this.raidStatusMessage, interactionType: Discord.InteractionType.MessageComponent, componentType: Discord.ComponentType.Button })
this.raidStatusInteractionHandler.on('collect', interaction => this.interactionHandler(interaction))
}
for (let i in this.#afkTemplate.reacts) {
let start = this.#afkTemplate.reacts[i].start
let end = start + this.#afkTemplate.reacts[i].lifetime
if (start > this.phase) continue
if (end <= this.phase) {
await this.raidStatusMessage.reactions.cache.get(this.#afkTemplate.reacts[i].emote.id).remove()
continue
}
await this.raidStatusMessage.react(this.#afkTemplate.reacts[i].emote.id)
}
}
async sendCommandsMessage() {
const raidCommandsMessageContents = this.#genRaidCommands()
const raidInfoMessageContents = this.#genRaidInfo();
[
this.raidCommandsMessage,
this.raidInfoMessage
] = await Promise.all([
this.raidCommandsMessage?.edit(raidCommandsMessageContents) || this.#afkTemplate.raidCommandChannel.send(raidCommandsMessageContents),
this.raidInfoMessage?.edit(raidInfoMessageContents) || this.#afkTemplate.raidInfoChannel.send(raidInfoMessageContents)
])
if (!this.raidCommandsInteractionHandler) {
this.raidCommandsInteractionHandler = new Discord.InteractionCollector(this.#bot, { message: this.raidCommandsMessage, interactionType: Discord.InteractionType.MessageComponent, componentType: Discord.ComponentType.Button })
this.raidCommandsInteractionHandler.on('collect', (interaction) => this.interactionHandler(interaction))
}
}
async sendChannelsMessage() {
const raidChannelsMessageContents = this.#genRaidChannels()
this.raidChannelsMessage = await (this.raidChannelsMessage?.edit(raidChannelsMessageContents) || this.#afkTemplate.raidActiveChannel.send(raidChannelsMessageContents))
if (!this.raidChannelsInteractionHandler) {
this.raidChannelsInteractionHandler = new Discord.InteractionCollector(this.#bot, { message: this.raidChannelsMessage, interactionType: Discord.InteractionType.MessageComponent, componentType: Discord.ComponentType.Button })
this.raidChannelsInteractionHandler.on('collect', (interaction) => this.interactionHandler(interaction))
}
}
getPhaseControls() {
const components = []
const phaseActionRow = new Discord.ActionRowBuilder().addComponents([
new Discord.ButtonBuilder()
.setLabel(`✅ ${this.#body[this.phase].nextPhaseButton ? `${this.#body[this.phase].nextPhaseButton}` : `Phase ${this.phase}`}`)
.setStyle(3)
.setCustomId(`phase`),
new Discord.ButtonBuilder()
.setLabel('❌ Abort')
.setStyle(4)
.setCustomId(`abort`)
])
if (this.#afkTemplate.capButton) phaseActionRow.addComponents([
new Discord.ButtonBuilder()
.setLabel(`🔒 Set Cap`)
.setStyle(2)
.setCustomId(`cap`)
])
components.push(phaseActionRow)
return components
}
getReactables() {
const components = []
let reactablesActionRow = []
let counter = 0
for (const button of this.buttons) {
if (!button.present(this.phase)) continue
if (button.isCap) button.limit = this.cap
reactablesActionRow.push(button.reactableButton(this.phase))
counter ++
if (counter == 5) {
counter = 0
const component = new Discord.ActionRowBuilder({ components: reactablesActionRow })
components.push(component)
reactablesActionRow = []
}
}
if (counter != 0) {
const component = new Discord.ActionRowBuilder({ components: reactablesActionRow })
components.push(component)
}
return components
}
getLoggingText() {
const loggingMessages = []
if (this.#botSettings.backend.allowAdditionalCompletes) loggingMessages.push(`Completes: \`${this.completes}\``)
loggingMessages.push(...this.buttons.filter(button => button.isLogged()).map(button => {
const emote = button.emote ? `${button.emote.text} ` : ``
return `${emote}${button.name} Logged: \`${button.logged}\``
}))
return loggingMessages.join('\n')
}
getButton(buttonName) {
return this.buttons.find(button => button.name === buttonName)
}
#reactionIsFull(button) {
return (button.limit && button.members.length >= button.limit)
|| (button.parent && button.parent.some(i => this.getButton(i).members.length >= this.getButton(i).limit))
}
/**
*
* @param {Discord.MessageComponentInteraction} interaction
*/
async interactionHandler(interaction) {
if (!interaction.isButton()) return
const isReactRequestInteraction = interaction.message.id !== this.raidStatusMessage.id
const button = isReactRequestInteraction ? this.reactRequests[interaction.message.id] : this.getButton(interaction.customId)
if (button) {
const emote = button.emote ? `${button.emote.text} ` : ``
if (button.minRole && !interaction.member.roles.cache.has(button.minRole.id)) {
return await interaction.reply({ embeds: [extensions.createEmbed(interaction, `You do not have the required role ${button.minRole} to react to this run.`, null)], ephemeral: true })
}
if (
// Clicking on the same button twice
button.members.includes(interaction.member.id) ||
// Clicking on the same button you've already clicked on a ;request embed
Object.values(this.reactRequests).some(requestButton => requestButton.name == button.name && requestButton.members.includes(interaction.member.id)) ||
// Clicking on the same button you've already clicked on the RSA embed
(isReactRequestInteraction && this.getButton(button.name).members.includes(interaction.member.id))
) {
return await interaction.reply({ embeds: [extensions.createEmbed(interaction, `You have already reacted as ${emote}${interaction.customId}. Try another react or try again next run.`, null)], ephemeral: true })
}
if (this.#reactionIsFull(button)) {
return await interaction.reply({ embeds: [extensions.createEmbed(interaction, `Too many people have already reacted and confirmed for that. Try another react or try again next run.`, null)], ephemeral: true })
}
let confirmInteraction = false
switch (button.type) {
case AfkTemplate.TemplateButtonType.LOG:
case AfkTemplate.TemplateButtonType.LOG_SINGLE:
case AfkTemplate.TemplateButtonType.NORMAL:
confirmInteraction = await this.processReactableNormal(interaction, button)
break
case AfkTemplate.TemplateButtonType.SUPPORTER:
confirmInteraction = await this.processReactableSupporter(interaction, button)
break
case AfkTemplate.TemplateButtonType.POINTS:
confirmInteraction = await this.processReactablePoints(interaction, button)
break
}
if (!confirmInteraction) return
if (this.#reactionIsFull(button)) {
return await confirmInteraction.reply({ embeds: [extensions.createEmbed(interaction, `Too many people have already reacted and confirmed for that. Try another react or try again next run.`, null)], ephemeral: true })
}
if (button.members.includes(interaction.member.id)) {
return await confirmInteraction.reply({ embeds: [extensions.createEmbed(interaction, `You have already been confirmed for this reaction`, null)], ephemeral: true })
}
button.members.push(interaction.member.id)
await this.reactableSendLoc(confirmInteraction, button.location || button.parent?.some(parent => this.getButton(parent)?.location))
if (button.parent) {
for (let i of button.parent) {
const parentButton = this.getButton(i);
if (!parentButton.members.includes(interaction.member.id)) parentButton.members.push(interaction.member.id)
}
}
await Promise.all([
this.raidCommandsMessage.edit(this.#genRaidCommands(), this.#bot, this.#guild),
this.raidInfoMessage.edit(this.#genRaidInfo())
])
return
}
else if (['abort', 'phase', 'cap', 'additional', 'end'].includes(interaction.customId) || interaction.customId.startsWith('log ')) {
if (this.#afkTemplate.minimumStaffRoles.some(roles => roles.every(role => interaction.member.roles.cache.has(role.id)))) return await this.processPhaseControl(interaction)
else {
return await interaction.reply({ embeds: [extensions.createEmbed(interaction, `You do not have the required Staff Role to use this button.`, null)], ephemeral: true })
}
} else if (interaction.customId == 'reconnect') {
return await this.processReconnect(interaction)
} else {
return await interaction.reply({ embeds: [extensions.createEmbed(interaction, `How did you press something that's unpressable? ඞ.`, null)], ephemeral: true })
}
}
earlyLocationMembers() {
const locationButtons = this.buttons.filter(button => button.location || this.buttons.some(parent => button.parent?.includes(parent.name) && parent.location));
return locationButtons.map(button => button.members).flat()
}
earlySlotMembers() {
return this.buttons.map(button => button.members).flat().concat(this.staffEarlyMembers);
}
async processPhaseControl(interaction) {
switch (interaction.customId) {
case "abort":
await this.processPhaseAbort(interaction)
break
case "phase":
await this.processPhaseNext(interaction)
break
case "cap":
await this.processPhaseCap(interaction)
break
case "additional":
await this.processPhaseAdditional(interaction)
break
case "end":
await this.processPhaseEnd(interaction)
break
default:
if (interaction.customId.startsWith('log ')) await this.processPhaseLog(interaction)
break
}
}
async processPhaseAbort(interaction) {
const text = `Are you sure you want to abort this run?`
const confirmButton = new Discord.ButtonBuilder()
.setLabel('❌ Abort')
.setStyle(Discord.ButtonStyle.Secondary)
const cancelButton = new Discord.ButtonBuilder()
const {value: confirmValue, interaction: subInteraction} = await interaction.confirmPanel(text, null, confirmButton, cancelButton, 10000, true)
if (!subInteraction) return await interaction.editReply({ embeds: [extensions.createEmbed(interaction, `Timed out. You can dismiss this message.`, null)], components: [] })
else if (!confirmValue) return await subInteraction.update({ embeds: [extensions.createEmbed(interaction, `Cancelled. You can dismiss this message.`, null)], components: [] })
else await subInteraction.update({ embeds: [extensions.createEmbed(interaction, `Successfully aborted the run. You can dismiss this message.`, null)], components: [] })
this.raidStatusInteractionHandler.stop()
this.raidCommandsInteractionHandler.stop()
this.raidChannelsInteractionHandler.stop()
if (this.moveInEarlysTimer) clearInterval(this.moveInEarlysTimer)
if (this.updatePanelTimer) clearInterval(this.updatePanelTimer)
if (this.#channel) await this.#channel.delete()
this.aborted_by = this.#guild.members.cache.get(interaction.member.id)
this.raidStatusMessage.reactions.removeAll()
await Promise.all([
this.raidStatusMessage.edit({ content: null, ...this.#genRaidStatus() }),
this.raidCommandsMessage.edit(this.#genRaidCommands()),
this.raidInfoMessage.edit(this.#genRaidInfo()),
this.raidChannelsMessage.delete()
])
this.saveBotAfkCheck(true)
}
async processPhaseNext(interaction) {
if (interaction && interaction.member != this.#leader) {
const text = `Are you sure you want to move to the next phase in this run?`
const confirmButton = new Discord.ButtonBuilder()
.setLabel('✅ Confirm')
.setStyle(Discord.ButtonStyle.Success)
const cancelButton = new Discord.ButtonBuilder()
let confirmValue, subInteraction;
[interaction, {value: confirmValue, interaction: subInteraction}] = await Promise.all([interaction.deferUpdate(), interaction.confirmPanel(text, null, confirmButton, cancelButton, 10000, true)])
if (!subInteraction) return await interaction.editReply({ embeds: [extensions.createEmbed(interaction, `Timed out. You can dismiss this message.`, null)], components: [] })
else if (!confirmValue) return await subInteraction.update({ embeds: [extensions.createEmbed(interaction, `Cancelled. You can dismiss this message.`, null)], components: [] })
else subInteraction.update({ embeds: [extensions.createEmbed(interaction, `Successfully moved to the next phase of the run. You can dismiss this message.`, null)], components: [] })
}
if (this.phase >= this.#afkTemplate.phases) return this.postAfk(interaction)
this.phase += 1
this.timer = new Date(Date.now() + (this.#body[this.phase].timeLimit * 1000))
if (this.updatePanelTimer) clearInterval(this.updatePanelTimer)
const [tempRaidStatusMessage] = await Promise.all([
this.#body[this.phase].message && this.#afkTemplate.raidStatusChannel.send({ content: `${this.#body[this.phase].message} in 5 seconds...` }),
(interaction?.message.id == this.raidStatusMessage ? interaction.editButtons({ disabled: true }) : this.raidStatusMessage.editButtons({ disabled: true })),
(interaction?.message.id == this.raidCommandsMessage ? interaction.editButtons({ disabled: true }) : this.raidCommandsMessage.editButtons({ disabled: true })),
(interaction?.message.id == this.raidChannelsMessage ? interaction.editButtons({ disabled: true }) : this.raidChannelsMessage.editButtons({ disabled: true }))
])
setTimeout(async () => {
if (this.#body[this.phase].vcState == AfkTemplate.TemplateVCState.OPEN && this.#channel) for (let minimumJoinRaiderRole of this.#afkTemplate.minimumJoinRaiderRoles) await this.#channel.permissionOverwrites.edit(minimumJoinRaiderRole.id, { Connect: true, ViewChannel: true })
else if (this.#body[this.phase].vcState == AfkTemplate.TemplateVCState.LOCKED && this.#channel) for (let minimumJoinRaiderRole of this.#afkTemplate.minimumJoinRaiderRoles) await this.#channel.permissionOverwrites.edit(minimumJoinRaiderRole.id, { Connect: false, ViewChannel: true })
await Promise.all([this.sendStatusMessage(), this.sendCommandsMessage(), this.sendChannelsMessage()])
if (this.phase <= this.#afkTemplate.phases) {
let updatePanelTimer = setInterval((updatePanelTimer) => this.updatePanel(updatePanelTimer), 5000)
this.updatePanelTimer = updatePanelTimer
}
this.saveBotAfkCheck()
}, 5000)
setTimeout(async () => { if (tempRaidStatusMessage) await tempRaidStatusMessage.delete() }, 5000)
}
async processPhaseCap(interaction) {
const text = `What is the cap you want for this run?`
const confirmNumberMenu = new Discord.StringSelectMenuBuilder()
.setPlaceholder(`Number of Members`)
.setOptions(
{ label: '1', value: '1' },
{ label: '2', value: '2' },
{ label: '3', value: '3' },
{ label: 'None', value: '0' },
)
const {value: confirmNumberValue, interaction: subInteraction} = await interaction.selectPanel(text, null, confirmNumberMenu, 30000, true, true)
const number = Number.isInteger(parseInt(confirmNumberValue)) ? parseInt(confirmNumberValue) : null
if (!subInteraction) return await interaction.editReply({ embeds: [extensions.createEmbed(interaction, `Timed out. You can dismiss this message.`, null)], components: [] })
else if (!number) return await subInteraction.update({ embeds: [extensions.createEmbed(interaction, `Cancelled or Invalid Cap. You can dismiss this message.`, null)], components: [] })
else await subInteraction.update({ embeds: [extensions.createEmbed(interaction, `Successfully set the cap to ${number}. You can dismiss this message.`, null)], components: [] })
this.cap = number
if (this.#channel) this.#channel.setUserLimit(this.cap)
this.updatePanel()
}
async processPhaseAdditional(interaction) {
if (this.logging) return await interaction.reply({ embeds: [extensions.createEmbed(interaction, `You have already logged an additional complete recently. Please wait and try again!`, null)], ephemeral: true })
const text = `Are you sure you want to log an additional complete to all members of this run?`
const confirmButton = new Discord.ButtonBuilder()
.setLabel('Log Additional Complete')
.setStyle(Discord.ButtonStyle.Secondary)
const cancelButton = new Discord.ButtonBuilder()
const {value: confirmValue, interaction: logCompleteInteraction} = await interaction.confirmPanel(text, null, confirmButton, cancelButton, 10000, true)
if (!logCompleteInteraction) return await interaction.editReply({ embeds: [extensions.createEmbed(interaction, `Timed out. You can dismiss this message.`, null)], components: [] })
else if (!confirmValue) return await logCompleteInteraction.update({ embeds: [extensions.createEmbed(interaction, `Cancelled. You can dismiss this message.`, null)], components: [] })
else await logCompleteInteraction.update({ embeds: [extensions.createEmbed(interaction, `Successfully logged an additional complete to all members of the run. You can dismiss this message.`, null)], components: [] })
this.logging = true
this.completes++
await this.raidChannelsMessage.edit(this.#genRaidChannels())
setTimeout(this.loggingAfk.bind(this), 60000)
}
#lookupGuildMember(name) {
return this.#guild.members.cache.get(name) || this.#guild.members.cache.filter(user => user.nickname != null).find(nick => nick.nickname.replace(/[^a-z|]/gi, '').toLowerCase().split('|').includes(name.toLowerCase()))
}
async #keyNameInputPrompt(i) {
await i.showModal(
new Discord.ModalBuilder()
.setTitle("Whose key are you logging?")
.setCustomId('keynamemodal')
.addComponents(
new Discord.ActionRowBuilder().addComponents(
new Discord.TextInputBuilder()
.setLabel('Key Name')
.setCustomId('keyname')
.setStyle(Discord.TextInputStyle.Short)
)
)
)
let keyNameResp
try {
keyNameResp = await i.awaitModalSubmit({time: 600_000})
} catch(e) {
if (e.code == 'InteractionCollectorError') return [undefined, i]
throw e
}
const newMemberName = keyNameResp.fields.getField('keyname').value
const newMember = this.#lookupGuildMember(newMemberName)
if (!newMember) return [undefined, keyNameResp.reply({content: `Invalid username: ${newMemberName}`, ephemeral: true})]
return [newMember, keyNameResp]
}
async processPhaseLog(interaction, modded) {
const buttonName = interaction.customId.split(' ').slice(2).join(' ')
const buttonType = interaction.customId.split(' ')[1]
const button = this.getButton(buttonName)
let member = null
let number = 1
let logOption = button.logOptions[interaction.customId.split(' ')[1]]
let isModded = interaction.customId.split(' ')[1] == 'Modded'
let choiceText = button.emote ? `${button.emote.text} **${buttonType} ${buttonName}**` : `**${buttonType} ${buttonName}**`
if (button.members.length == 0) {
[member, interaction] = await this.#keyNameInputPrompt(interaction)
if (!member) return
} else if (button.members.length == 1) {
member = this.#guild.members.cache.get(button.members[0])
} else {
const text = `Which member do you want to log ${choiceText} reacts for this run?\nChoose or input a username or id.`
const confirmMemberMenu = new Discord.StringSelectMenuBuilder()
.setPlaceholder(`Name of ${button.name}s`)
for (let i of button.members) confirmMemberMenu.addOptions({ label: this.#guild.members.cache.get(i).nickname, value: i })
const {value: confirmMemberValue, interaction: logKeyInteraction} = await interaction.selectPanel(text, null, confirmMemberMenu, 10000, true, true)
if (confirmMemberValue) member = this.#lookupGuildMember(confirmMemberValue)
if (!logKeyInteraction) return await interaction.followUp({ embeds: [extensions.createEmbed(interaction, `Timed out. You can dismiss this message.`, null)], ephemeral: true })
else if (!member) return await logKeyInteraction.update({ embeds: [extensions.createEmbed(interaction, `Cancelled or Invalid Member. You can dismiss this message.`, null)], components: [] })
interaction = logKeyInteraction
}
const keyCountMsg = await interaction.reply({
embeds: [
new Discord.EmbedBuilder()
.setDescription(`Logging ${number} ${choiceText} for ${member}.`)
.setFooter({ text: `${interaction.guild.name} • ${this.afkTitle()}`, iconURL: interaction.guild.iconURL() })
],
components: [
new Discord.ActionRowBuilder()
.addComponents(
new Discord.ButtonBuilder().setCustomId('incr').setLabel('+1').setStyle(Discord.ButtonStyle.Primary),
new Discord.ButtonBuilder().setCustomId('save').setLabel('Save').setStyle(Discord.ButtonStyle.Success),
new Discord.ButtonBuilder().setCustomId('cancel').setLabel('Cancel').setStyle(Discord.ButtonStyle.Danger),
new Discord.ButtonBuilder().setCustomId('input').setLabel('Input Key Count').setStyle(Discord.ButtonStyle.Secondary),
new Discord.ButtonBuilder().setCustomId('changeuser').setLabel('Change Key Popper').setStyle(Discord.ButtonStyle.Secondary)
)
],
ephemeral: true
})
// This is a workaround for https://github.com/discordjs/discord.js/issues/7992
// The bug is that if you have buttons on an ephermeral message, you can't have a Collector
// on them unless you fetch the reply. We can't pass `fetchReply` when we make the reply
// because we need the Interaction to be able to delete it. So, we fetch the reply ourselves
// in order to make the collector.
const collector = (await keyCountMsg.interaction.fetchReply()).createMessageComponentCollector({ componentType: Discord.ComponentType.Button });
const savePops = await new Promise(res => {
collector.on('collect', async i => {
switch (i.customId) {
case 'save': return res(true)
case 'cancel': return res(false)
case 'incr':
number += 1
break
case 'changeuser':
let newMember;
[newMember, i] = await this.#keyNameInputPrompt(i)
if (!newMember) return
member = newMember
break
case 'input':
await i.showModal(
new Discord.ModalBuilder()
.setTitle('How many keys would you like to log?')
.setCustomId('keycountmodal')
.addComponents(
new Discord.ActionRowBuilder().addComponents(
new Discord.TextInputBuilder()
.setLabel('Key Count')
.setCustomId('keycount')
.setStyle(Discord.TextInputStyle.Short)
)
)
)
let keyCountResp
try {
keyCountResp = await i.awaitModalSubmit({time: 600_000})
} catch(e) {
if (e.code == 'InteractionCollectorError') return
throw e
}
const newNumber = parseInt(keyCountResp.fields.getField('keycount').value)
if (isNaN(newNumber) || newNumber < 0) return await keyCountResp.reply({content: `Invalid number: ${newNumber}`, ephemeral: true})
number = newNumber
i = keyCountResp
break
}
return await i.update({ embeds: [extensions.createEmbed(interaction, `Logging ${number} ${choiceText} for ${member}.`, null)] })
});
})
collector.stop()
await keyCountMsg.delete()
if (!savePops) return
for (let option of logOption.logName) {
let keyTemplate = popCommand.findKey(this.#guild.id, option);
if (keyTemplate) {
let consumablepopsValueNames = `userid, guildid, unixtimestamp, amount, ismodded, templateid, raidid`
let consumablepopsValues = `'${member.id}', '${this.#guild.id}', '${Date.now()}', '${number}', ${isModded}, '${keyTemplate.templateID}', '${this.#raidID}'`
this.#db.query(`INSERT INTO consumablepops (${consumablepopsValueNames}) VALUES (${consumablepopsValues})`, (err, rows) => {
if (err) return console.log(`${option} missing from ${this.#guild.name} ${this.#guild.id}`)
})
}
this.#db.query(`UPDATE users SET ${option} = ${option} + ${number} WHERE id = '${member.id}'`, (err, rows) => {
if (err) return console.log(`${option} missing from ${this.#guild.name} ${this.#guild.id}`)
})
this.#db.query(`SELECT ${option} FROM users WHERE id = '${member.id}'`, async (err, rows) => {
if (err) return console.log(`${option} missing from ${this.#guild.name} ${this.#guild.id}`)
let embed = new Discord.EmbedBuilder()
.setColor('#0000ff')
.setTitle(`${button.name} logged!`)
.setDescription(`${member} now has \`\`${parseInt(rows[0][option]) + parseInt(number)}\`\` (+\`${number}\`) ${choiceText} pops`)
.setFooter({ text: `${interaction.guild.name} • ${this.afkTitle()}`, iconURL: interaction.guild.iconURL() })
await (this.raidCommandsMessage?.reply({ embeds: [embed] }) || this.#afkTemplate.raidCommandChannel.send({ embeds: [embed] }))
})
}
if (this.#botSettings.backend.points) {
let points = logOption.points * number * logOption.multiplier
await this.#db.promise().query('UPDATE users SET points = points + ? WHERE id = ?', [points, member.id])
let pointsLog = [{ uid: member.id, points: points, reason: `${button.name}`}]
await pointLogger.pointLogging(pointsLog, this.#guild, this.#bot, this.#genEmbedBase())
}
button.logged += number
await this.raidChannelsMessage.edit(this.#genRaidChannels())
}
async processPhaseEnd(interaction) {
const text = `Are you sure you want to delete this run?`
const confirmButton = new Discord.ButtonBuilder()
.setLabel('Delete Channel')
.setStyle(Discord.ButtonStyle.Secondary)
const cancelButton = new Discord.ButtonBuilder()
const {value: confirmValue, interaction: subInteraction} = await interaction.confirmPanel(text, null, confirmButton, cancelButton, 10000, true)
if (!subInteraction) return await interaction.editReply({ embeds: [extensions.createEmbed(interaction, `Timed out. You can dismiss this message.`, null)], components: [] })
else if (!confirmValue) return await subInteraction.update({ embeds: [extensions.createEmbed(interaction, `Cancelled. You can dismiss this message.`, null)], components: [] })
else await subInteraction.update({ embeds: [extensions.createEmbed(interaction, `Successfully deleted the run. You can dismiss this message.`, null)], components: [] })
this.raidStatusInteractionHandler.stop()
this.raidCommandsInteractionHandler.stop()
this.raidChannelsInteractionHandler.stop()
if (this.#channel) await this.#channel.delete()
this.deleted_by = this.#guild.members.cache.get(interaction.member.id)
await Promise.all([
this.raidStatusMessage.edit({ content: null, ...this.#genRaidStatus() }),
this.raidCommandsMessage.edit(this.#genRaidCommands()),
this.raidInfoMessage.edit(this.#genRaidInfo()),
this.raidChannelsMessage.delete()
])
this.saveBotAfkCheck(true)
}
async processReconnect(interaction) {