-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1733 lines (1395 loc) · 70.2 KB
/
index.js
File metadata and controls
1733 lines (1395 loc) · 70.2 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 { Client, Collection, GatewayIntentBits, ComponentType, ChannelType, StringSelectMenuBuilder, ActionRowBuilder, ThreadAutoArchiveDuration, codeBlock, strikethrough, inlineCode, underscore, escapeMarkdown } = require('discord.js');
const { Op } = require("sequelize");
const fs = require('node:fs');
const { token, guildId, janitor_guild_id, janitor_channel_id, announcement_channel_id, tipping_channel_id, updates_channel_id, main_channel_id, admin_role_id, captain_role_id, event_name, event_name_short, event_type, event_number, match_format, teams_config, maps_config, has_divisions, short_notice_length, replays_channel_id, captains_channel_id } = require('./config.json');
const { Tip, Tipper, Match, Team, Static } = require('./dbObjects.js');
const { buttons_tip, buttons_tip_closed, buttons_tipped, button_closed, button_dm_setting_ann, button_dm_setting_tips, button_dm_none, button_register, buttons_warning, button_begin_team_ranking, button_begin_map_ranking, buttons_tipped_closed, button_phase_2, button_end_event, buttons_tipped_green_closed, buttons_dm_result, button_initialise } = require('./buttons-presets.js');
// globally scoped variables
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages] });
var myGuild = null;
var tipping_channel = null;
var announcement_channel = null;
var main_channel = null;
var replays_channel = null;
var updates_channel = null;
var captains_channel = null;
var janitor_channel = null;
var registration_message = null;
var captain_message = null;
var scoreboard_message = null;
var stats_message = null;
var static = null;
var team_roles = [];
var team_threads = [];
//#region FUNCTIONS
async function update_threads (interaction) {
/*let teams_filtered = team_roles.filter(t => t);
let reply = `team captains ${underscore('underlined')}`;
for (const team_role of teams_filtered) {
reply = reply+`\n<@&${team_role.id}>\n${await team_role.members.map( member => member._roles.includes(captain_role_id) ? underscore(escapeMarkdown(member.displayName)) : escapeMarkdown(member.displayName) ).join(', ')}`
}
const teams = await Team.findAll();
for (const team of teams) {
const message = await team_threads[team.id].send({ content: reply, allowedMentions: {parse: []} });
message.pin();
team_threads[team.id].setAutoArchiveDuration(ThreadAutoArchiveDuration.OneWeek);
team_threads[team.id].setName(team_roles[team.id].name);
}*/
team_threads[74].setName(team_roles[74].name);
interaction.editReply({ephemeral: true, content: "done"})
}
async function announce_match (interaction, match, time, is_short_notice) {
loggingAction(`${interaction.user.tag} used /${interaction.commandName}: [Match #${indent(match.id, 3, '0')}] (announce) ${time.toLocaleString("en-GB", date_options)}`);
if(match.result_a) {
loggingAction('but the match has already been played');
return interaction.editReply({ content: `This match has already been played.` })
}
// send warning
const a = await interaction.editReply({
content:
`Are you sure you wish to schedule [Match #${indent(match.id, 3, '0')}]?\n<@&${match.team_a.role_id}> - <@&${match.team_b.role_id}> - ${time.toLocaleString("en-GB", date_options)}`,
components: [buttons_warning]
})
const filter = i => { return true };
const collectedButton = await a?.awaitMessageComponent({ filter, idle: 60 * 1000, componentType: ComponentType.Button})
.catch(_e => { return interaction.editReply({ content: 'This menu has expired after 60 seconds. *You can dismiss the message.*', components: [] }) })
if (collectedButton.content === 'This menu has expired after 60 seconds. *You can dismiss the message.*') {return}
// user pressed a button
loggingAction(`${interaction.user.tag} used /${interaction.commandName}: [Match #${indent(match.id, 3, '0')}] (announce) ${time.toLocaleString("en-GB", date_options)} and ${collectedButton.customId}`)
if(collectedButton.customId == 'b_nevermind') {
return interaction.editReply({ content: 'Good choice.', components: [] })
}
// update match
match.time = time;
match.is_open = !is_short_notice;
match.is_short_notice = is_short_notice;
match.is_cancelled = false;
let now = new Date(Date.now());
match.history = (`\n${now.toLocaleString("en-GB", date_options_short)} <@${interaction.user.id}>: Match was scheduled for ${inlineCode(time.toLocaleString("en-GB", date_options_short))}`).concat(match.history);
var message = `[Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>`;
// updates
await updates_channel.messages.edit(match.announcement_id, { content: message+match.history, allowedMentions: {roles: [match.team_a.role_id, match.team_b.role_id]} })
if (match.is_open) {
let tipping_message = `'`+message+`\n${await team_roles[match.team_a.id].members.map(m=>m.displayName).join(', ')} - ${await team_roles[match.team_b.id].members.map(m=>m.displayName).join(', ')}\n${time.toLocaleString("en-GB", date_options)}`
const tipping = await tipping_channel.send({ content: tipping_message, components: [buttons_tip], allowedMentions: {parse: []} });
match.tipping_id = tipping.id;
}
let update_text = message+`\nhttps://discord.com/channels/${guildId}/${updates_channel.id}/${match.announcement_id} Match was scheduled for ${inlineCode(time.toLocaleString("en-GB", date_options_short))}`;
let update = await updates_channel.send({ content: update_text, allowedMentions: {parse: []} });
await team_threads[match.team_a.id].send({ content: update_text, allowedMentions: {roles: [match.team_a.role_id]} });
await team_threads[match.team_b.id].send({ content: update_text, allowedMentions: {roles: [match.team_b.role_id]} });
if (match.latest_update_id) {
await updates_channel.messages.delete(match.latest_update_id);
}
match.latest_update_id = update.id;
await match.save();
await match.restore()
await print_team_matches(match.team_a);
await print_team_matches(match.team_b);
// create tips
if (match.is_open) {
const tippers = await Tipper.findAll();
for (const tipper of tippers) {
createTip (interaction, tipper, match);
}
}
// send match data
const res = await fetch('https://speedball.the-dmark.com/stats/post/match-data.php',{
method: 'POST',
body: JSON.stringify({
event: event_type,
event_number: event_number,
match_format: match_format,
match_number: match.id,
is_cancelled: match.is_cancelled,
planned_date: match.time.toISOString().replace(/T/, ' ').replace(/\..+/, ''),
// planned_date: match.time.toUTCString(),
team_a_id: match.team_a.id,
team_b_id: match.team_b.id,
}),
headers: {
'content-type': 'application/json; charset=UTF-8',
'accept': '*/*',
'user-agent':'*'
},
})
if(res.ok){
//const data = await res.json();
loggingAction(`[Match #${indent(match.id, 3, '0')}] date has been sent to website.`)
} else {
await loggingError(`[Match #${indent(match.id, 3, '0')}] date could not be sent to website.`,'','')
}
interaction.editReply({ content: `Successfully scheduled [Match #${indent(match.id, 3, '0')}].`, components: [] });
return
}
async function cancel_match (interaction, match) {
loggingAction(`${interaction.user.tag} used /${interaction.commandName}: [Match #${indent(match.id, 3, '0')}] (cancel)`);
var message = `[Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>}`;
// cancel warning buttons
const warning = await interaction.editReply({ content: `Are you sure you wish to CANCEL [Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>?`, components: [buttons_warning] })
const filter = i => { return true };
const collectedButton = await warning?.awaitMessageComponent({ filter, idle: 60 * 1000, componentType: ComponentType.Button})
.catch(_e => { return interaction.editReply({ content: 'This menu has expired after 60 seconds. *You can dismiss the message.*', components: [] }) })
if (collectedButton.content === 'This menu has expired after 60 seconds. *You can dismiss the message.*') {return}
// user pressed a button
loggingAction(`${interaction.user.tag} used /${interaction.commandName}: [Match #${indent(match.id, 3, '0')}] (cancel) and ${collectedButton.customId}`)
if(collectedButton.customId == 'b_nevermind') {
interaction.editReply({ content: 'Good choice.', components: [] })
return
}
// update match
let now = new Date(Date.now());
match.is_cancelled = true;
match.is_short_notice = false;
match.is_open = true;
match.time = (match.result_a ? match.time : null);
match.history = (`\n${now.toLocaleString("en-GB", date_options_short)} <@${interaction.user.id}>: Match was cancelled.`).concat(match.history);
var message = `[Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>`;
//updates
await updates_channel.messages.edit(match.announcement_id, { content: message+match.history, allowedMentions: {parse: []} })
let update_text = message+`\nhttps://discord.com/channels/${guildId}/${updates_channel.id}/${match.announcement_id} Match was cancelled.`;
let update = await updates_channel.send({ content: update_text, allowedMentions: {parse: []} });
await team_threads[match.team_a.id].send({ content: update_text, allowedMentions: {roles: [match.team_a.role_id]} });
await team_threads[match.team_b.id].send({ content: update_text, allowedMentions: {roles: [match.team_b.role_id]} });
if (match.latest_update_id) {
await updates_channel.messages.delete(match.latest_update_id);
}
match.latest_update_id = update.id;
match.save();
// soft delete tips
const tips = await match.getTips();
for (const tip of tips) {
if (tip.dm_id){
const user = await client.users.fetch(tip.tipper_id);
user.dmChannel.messages.edit(tip.dm_id, {content: `[Match #${indent(match.id, 3, '0')}]\nThe match was cancelled.`, components: []});
tip.dm_id = null; tip.save();
}
tip.destroy();
}
if (match.tipping_id) {
await tipping_channel.messages.delete(match.tipping_id);
match.tipping_id = null;
}
await match.save(); await match.destroy();
await print_team_matches(match.team_a);
await print_team_matches(match.team_b);
// seding match data
const res = await fetch('https://speedball.the-dmark.com/stats/post/match-data.php',{
method: 'POST',
body: JSON.stringify({
event: event_type,
event_number: event_number,
match_format: match_format,
match_number: match.id,
is_cancelled: match.is_cancelled,
team_a_id: match.team_a.id,
planned_date: ( match.result_a ? match.time.toISOString().replace(/T/, ' ').replace(/\..+/, '') : "" ),
team_b_id: match.team_b.id
}),
headers: {
'content-type': 'application/json; charset=UTF-8',
'accept': '*/*',
'user-agent':'*'
},
})
if(res.ok){
//const data = await res.json();
loggingAction(`[Match #${indent(match.id, 3, '0')}] data has been sent to website.`)
}
else {
await loggingError(`[Match #${indent(match.id, 3, '0')}] date could not be sent to website.`,'','')
}
interaction.editReply({ content: `Successfully cancelled [Match #${indent(match.id, 3, '0')}]`, components: [] })
advance_phase();
return
}
async function uncancel_match (interaction, match) {
loggingAction(`${interaction.user.tag} used /${interaction.commandName}: [Match #${indent(match.id, 3, '0')}] (un-cancel)`);
var message = `[Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>}`;
// cancel warning buttons
const warning = await interaction.editReply({ content: `Are you sure you wish to UN-CANCEL [Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>?`, components: [buttons_warning] })
const filter = i => { return true };
const collectedButton = await warning?.awaitMessageComponent({ filter, idle: 60 * 1000, componentType: ComponentType.Button})
.catch(_e => { return interaction.editReply({ content: 'This menu has expired after 60 seconds. *You can dismiss the message.*', components: [] }) })
if (collectedButton.content === 'This menu has expired after 60 seconds. *You can dismiss the message.*') {return}
// user pressed a button
loggingAction(`${interaction.user.tag} used /${interaction.commandName}: [Match #${indent(match.id, 3, '0')}] (un-cancel) and ${collectedButton.customId}`)
if(collectedButton.customId == 'b_nevermind') {
interaction.editReply({ content: 'Good choice.', components: [] })
return
}
// update match
match.is_cancelled = false;
let now = new Date(Date.now());
match.history = (`\n${now.toLocaleString("en-GB", date_options_short)} <@${interaction.user.id}>: Match was un-cancelled.`).concat(match.history);
var message = `[Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>`;
//updates
await updates_channel.messages.edit(match.announcement_id, { content: message+match.history, allowedMentions: {parse: []} })
let update_text = message+`\nhttps://discord.com/channels/${guildId}/${updates_channel.id}/${match.announcement_id} Match was un-cancelled.`;
let update = await updates_channel.send({ content: update_text, allowedMentions: {parse: []} });
await team_threads[match.team_a.id].send({ content: update_text, allowedMentions: {roles: [match.team_a.role_id]} });
await team_threads[match.team_b.id].send({ content: update_text, allowedMentions: {roles: [match.team_b.role_id]} });
if (match.latest_update_id) {
await updates_channel.messages.delete(match.latest_update_id);
}
match.latest_update_id = update.id;
await match.save(); await match.destroy();
await print_team_matches(match.team_a);
await print_team_matches(match.team_b);
// seding match data
const res = await fetch('https://speedball.the-dmark.com/stats/post/match-data.php',{
method: 'POST',
body: JSON.stringify({
event: event_type,
event_number: event_number,
match_format: match_format,
match_number: match.id,
is_cancelled: match.is_cancelled,
team_a_id: match.team_a.id,
team_b_id: match.team_b.id
}),
headers: {
'content-type': 'application/json; charset=UTF-8',
'accept': '*/*',
'user-agent':'*'
},
})
if(res.ok){
//const data = await res.json();
loggingAction(`[Match #${indent(match.id, 3, '0')}] data has been sent to website.`)
}
else {
await loggingError(`[Match #${indent(match.id, 3, '0')}] data could not be sent to website.`,'','')
}
interaction.editReply({ content: `Successfully un-cancelled [Match #${indent(match.id, 3, '0')}]`, components: [] })
//advance_phase();
return
}
async function reschedule_match (interaction, match, time, is_short_notice, is_open) {
loggingAction(`${interaction.user.tag} used /${interaction.commandName}: [Match #${indent(match.id, 3, '0')}] (reschedule) ${time.toLocaleString("en-GB", date_options)}`);
if(match.result_a) {
loggingAction('but the match has already been played');
return interaction.editReply({ content: `This match has already been played.` })
}
// reschedule warning buttons
const warning = await interaction.editReply({ content: `Are you sure you wish to reschedule [Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>?\nFrom: ${match.time.toLocaleString("en-GB", date_options)}\nTo: ${time.toLocaleString("en-GB", date_options)}`, components: [buttons_warning] })
const filter = i => { return true };
const collectedButton = await warning?.awaitMessageComponent({ filter, idle: 60 * 1000, componentType: ComponentType.Button})
.catch(_e => { return interaction.editReply({ content: 'This menu has expired after 60 seconds. *You can dismiss the message.*', components: [] }) })
if (collectedButton.content === 'This menu has expired after 60 seconds. *You can dismiss the message.*') {return}
// user pressed a button
loggingAction(`${interaction.user.tag} used /${interaction.commandName}: [Match #${indent(match.id, 3, '0')}] (reschedule) ${time.toLocaleString("en-GB", date_options)} and ${collectedButton.customId}`)
if(collectedButton.customId == 'b_nevermind') {
interaction.editReply({ content: 'Good choice.', components: [] })
return
}
// update match and announcements
match.time = time;
let now = new Date(Date.now());
match.history = (`\n${now.toLocaleString("en-GB", date_options_short)} <@${interaction.user.id}>: Match was rescheduled for ${inlineCode(time.toLocaleString("en-GB", date_options_short))}`).concat(match.history);
await match.save();
var message = `[Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>`;
//updates
await updates_channel.messages.edit(match.announcement_id, { content: message+match.history, allowedMentions: {parse: []} })
let update_text = message+`\nhttps://discord.com/channels/${guildId}/${updates_channel.id}/${match.announcement_id} Match was rescheduled for ${inlineCode(time.toLocaleString("en-GB", date_options_short))}`;
let update = await updates_channel.send({content: update_text, allowedMentions: {parse: []} });
await team_threads[match.team_a.id].send({ content: update_text, allowedMentions: {roles: [match.team_a.role_id]} });
await team_threads[match.team_b.id].send({ content: update_text, allowedMentions: {roles: [match.team_b.role_id]} });
if (match.latest_update_id) {
await updates_channel.messages.delete(match.latest_update_id);
}
match.latest_update_id = update.id;
await match.save();
let tipping_message = `'`+message+`\n${await team_roles[match.team_a.id].members.map(m=>m.displayName).join(', ')} - ${await team_roles[match.team_b.id].members.map(m=>m.displayName).join(', ')}\n${time.toLocaleString("en-GB", date_options)}`
// handling different states for tipping
//open match rescheduled into short notice
if (!match.is_short_notice && is_short_notice
&& (!is_open && match.time.getTime()+short_notice_length > time.getTime()
|| match.time.getTime()+short_notice_length > now.getTime()) ) {
const tips = await match.getTips();
for (const tip of tips) {
if (tip.dm_id){
const user = await client.users.fetch(tip.tipper_id);
user.dmChannel.messages.edit(tip.dm_id, {content: `[Match #${indent(match.id, 3, '0')}]\nThe match was rescheduled into short notice.`, components: []});
tip.dm_id = null; tip.save();
}
tip.destroy();
}
match.is_short_notice = true;
match.is_open = false;
await tipping_channel.message.delete(match.tipping_id);
match.tipping_id = null;
await match.save();
}
// open match is closed (but not into short notice)
else if (match.is_open && !is_open) {
closeMatch(match);
}
// closed (but already announced) match is opened
else if (!match.is_open && !match.is_short_notice && !is_short_notice){
match.is_open = true;
match.is_short_notice = false;
const tipping = await tipping_channel.messages.fetch(match.tipping_id);
await tipping.edit({ content: tipping_message, components: [buttons_tip], allowedMentions: {parse: []} })
// create tips
const tippers = await Tipper.findAll();
for (const tipper of tippers) {
createTip (interaction, tipper, match);
}
}
await match.save()
await print_team_matches(match.team_a);
await print_team_matches(match.team_b);
const res = await fetch('https://speedball.the-dmark.com/stats/post/match-data.php',{
method: 'POST',
body: JSON.stringify({
event: event_type,
event_number: event_number,
match_format: match_format,
match_number: match.id,
planned_date: match.time.toISOString().replace(/T/, ' ').replace(/\..+/, ''),
// planned_date: match.time.toUTCString(),
team_a_id: match.team_a.id,
team_b_id: match.team_b.id,
}),
headers: {
'content-type': 'application/json; charset=UTF-8',
'accept': '*/*',
'user-agent':'*'
},
})
if(res.ok){
//const data = await res.json();
loggingAction(`[Match #${indent(match.id, 3, '0')}] data has been sent to website.`)
}
else {
await loggingError(`[Match #${indent(match.id, 3, '0')}] date could not be sent to website.`,'','')
}
return interaction.editReply({ content: `Successfully rescheduled [Match #${indent(match.id, 3, '0')}].`, components: [] })
}
async function postpone_match (interaction, match) {
try {
loggingAction(`${interaction.user.tag} used /${interaction.commandName}: [Match #${indent(match.id, 3, '0')}] (postpone)`);
if(!match.time) {
loggingAction('but the match was not scheduled to begin with');
return interaction.editReply({ content: `This match is not scheduled.` })
}
if(match.result_a) {
loggingAction('but the match has already been played');
return interaction.editReply({ content: `This match has already been played.` })
}
// send warning
const a = await interaction.editReply({
content:
`Are you sure you wish to POSTPONE [Match #${indent(match.id, 3, '0')}]?\n<@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>`,
components: [buttons_warning]
})
const filter = i => { return true };
const collectedButton = await a?.awaitMessageComponent({ filter, idle: 60 * 1000, componentType: ComponentType.Button})
.catch(_e => { return interaction.editReply({ content: 'This menu has expired after 60 seconds. *You can dismiss the message.*', components: [] }) })
if (collectedButton.content === 'This menu has expired after 60 seconds. *You can dismiss the message.*') {return}
// user pressed a button (confirm/nevermind)
loggingAction(`${interaction.user.tag} pressed ${interaction.customId} [Match #${indent(match.id, 3, '0')}] and ${collectedButton.customId}`);
if(collectedButton.customId == 'b_nevermind') {
interaction.editReply({ content: 'Good choice.', components: [] })
return
}
// update match
let now = new Date(Date.now());
match.time = null;
match.is_short_notice = false;
match.is_open = true;
match.history = (`\n${now.toLocaleString("en-GB", date_options_short)} <@${interaction.user.id}>: Match was postponed`).concat(match.history);
await match.save();
var message = `[Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>`;
//updates
await updates_channel.messages.edit(match.announcement_id, { content: message+match.history, allowedMentions: {parse: []} })
let update_text = message+`\nhttps://discord.com/channels/${guildId}/${updates_channel.id}/${match.announcement_id} Match was postponed.`;
let update = await updates_channel.send({content: update_text, allowedMentions: {parse: []} });
await team_threads[match.team_a.id].send({ content: update_text, allowedMentions: {roles: [match.team_a.role_id]} });
await team_threads[match.team_b.id].send({ content: update_text, allowedMentions: {roles: [match.team_b.role_id]} });
if (match.latest_update_id) {
await updates_channel.messages.delete(match.latest_update_id);
}
match.latest_update_id = update.id;
await print_team_matches(match.team_a);
await print_team_matches(match.team_b);
// soft delete tips
const tips = await match.getTips();
for (const tip of tips) {
if (tip.dm_id){
const user = await client.users.fetch(tip.tipper_id);
user.dmChannel.messages.edit(tip.dm_id, {content: `[Match #${indent(match.id, 3, '0')}]\nThe match was postponed.`, components: []});
tip.dm_id = null; tip.save();
}
tip.destroy();
}
if (match.tipping_id) {
await tipping_channel.messages.delete(match.tipping_id);
match.tipping_id = null;
}
await match.save(); await match.destroy();
// send match data
const res = await fetch('https://speedball.the-dmark.com/stats/post/match-data.php',{
method: 'POST',
body: JSON.stringify({
event: event_type,
event_number: event_number,
match_format: match_format,
match_number: match.id,
planned_date: "",
team_a_id: match.team_a.id,
team_b_id: match.team_b.id,
}),
headers: {
'content-type': 'application/json; charset=UTF-8',
'accept': '*/*',
'user-agent':'*'
},
})
if(res.ok){
//const data = await res.json();
loggingAction(`[Match #${indent(match.id, 3, '0')}] data has been sent to website.`)
}
else {
await loggingError(`[Match #${indent(match.id, 3, '0')}] date could not be sent to website.`,'','')
}
interaction.editReply({ content: `Successfully postponed [Match #${indent(match.id, 3, '0')}].`, components: [] });
return
} catch (error) {
await loggingError('b_postpone_match', `${interaction.user.tag} pressed ${interaction.customId}${typeof collectedButton !== 'undefined' ? ` and ${collectedButton.customId}` : '' }`, error);
return interaction.editReply({ content: `There was an error while executing this command!\nThe error has been submitted`, components: [] });
}
}
async function closeMatch (match) {
if (!match.is_open) {return}
match.is_open = false;
match.save();
tipping_channel.messages.edit( match.tipping_id, { components: [button_closed, buttons_tip_closed]} );
const tips = await Tip.findAll( { where: {match_id: match.id} } )
for (const tip of tips) {
if (tip.dm_id) {
const user = client.users.cache.get(tip.tipper_id);
user.dmChannel.messages.edit(tip.dm_id, { components: [buttons_tipped_closed(tip.score_a)] })
}
}
if(!match.is_short_notice && !match.is_cancelled) {postTips(match);}
loggingAction(`[Match #${indent(match.id, 3, '0')}] closed.`);
return
}
async function createTip (interaction, tipper, match) {
try {
//if (match.is_short_notice || tipper.id == client.user.id) {return}
if (match.is_short_notice) {return}
// // tip back-end
var tip = await Tip.findOne({ where: { tipper_id: tipper.id, match_id: match.id }, paranoid: false });
if (!tip) {
tip = await Tip.create({ tipper_id: tipper.id, match_id: match.id });
} else { tip.restore();}
if (['0','1','2','3','4'].includes(interaction.customId)) {
tip.score_a = interaction.customId;
await tip.save();
if (interaction.channel.isDMBased()) {
tipper.dm_tips++
interaction.update({});
} else {
tipper.channel_tips++
await interaction.reply({
ephemeral: true,
content: `[Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}>\n\nYour tip has been received.`,
components: [buttons_tipped_closed(tip.score_a)]
})
}
tipper.save();
}
// // tip front-end
// find or send the tip dm
var dm = null;
const user = await client.users.fetch(tipper.id);
if (tip.dm_id == null && !tipper.dm_setting_tips) {
return
}
else if (tip.dm_id == null && tipper.dm_setting_tips) {
dm = await user.dmChannel.send({
content: `You can now tip on [Match #${indent(match.id, 3, '0')}]`
});
tip.dm_id = dm.id; tip.save();
} else {
dm = await user.dmChannel.messages.fetch(tip.dm_id);
}
// edit the tip dm
await dm.edit({
content: `'[Match #${indent(match.id, 3, '0')}] ${team_roles[match.team_a.id].name} - ${team_roles[match.team_b.id].name}\n${await team_roles[match.team_a.id].members.map(m=>m.displayName).join(', ')} - ${await team_roles[match.team_b.id].members.map(m=>m.displayName).join(', ')}\n${match.time.toLocaleString("en-GB", date_options)}`,
components: [(match.is_open ? buttons_tipped(tip.score_a) : buttons_tip_closed)] //this takes into account if the match is posted as closed, but this is prevented in /announcematch
})
} catch (error) {
// this error message needs some work, for when someone scheduled a match
await loggingError('createTip()', `${interaction.user.tag} tipped "${interaction.customId}" on Match #${indent(match.id, 3, '0')} in ${(interaction.channel.isDMBased() ? 'dm_channel' : 'tipping_channel')}`, error);
return interaction.editReply({ content: `There was an error while executing this command!\nThe error has been submitted.`, components: [], ephemeral: true });
}
}
async function generate_first_leg () {
if (static.phase == 1) {
loggingAction("\n\nGenerating Phase 1\n");
}
const teams = await Team.findAll();
const teams_concat = teams.concat(teams);
var match_id = 0;
for (let home_team = 0; home_team <= teams.length-1; home_team++) {
const out_teams = teams_concat.slice(home_team+1, home_team+1 + home_matches(teams, home_team));
for (const out_team of out_teams) {
const team_a = teams[home_team];
const team_b = out_team;
loggingAction(`#${++match_id}: ${team_roles[team_a.id].name} - ${team_roles[team_b.id].name}`);
const match = await Match.create({ id: match_id });
await match.setTeam_a(team_a);
await match.setTeam_b(team_b);
await match.destroy();
// the bot tips randomly
bot_tip(match_id)
}
}
}
async function generate_first_leg_TEST () {
if (static.phase == 1) {
loggingAction("\n\nGenerating Phase 1\n");
}
const teams = await Team.findAll();
var match_id = 0;
const uneven = teams.length % 2;
for (let round = 1; round < teams.length+uneven; round++) {
loggingAction(`Round ${round}`);
var i = teams.length-round;
if (teams.length % 2 > 0) {i++}
var j = i;
if (j < teams.length) {
loggingAction(`#${++match_id}: ${team_roles[teams[0].id].name} - ${team_roles[teams[j].id].name}`)
const match = await Match.create({ id: match_id });
if (round%4 == 1 || round%4 == 2) {
await match.setTeam_a(teams[0]);
await match.setTeam_b(teams[j]);
} else {
await match.setTeam_a(teams[j]);
await match.setTeam_b(teams[0]);
}
await match.destroy();
// the bot tips randomly
bot_tip(match_id)
}
for (let k = 2; k <= teams.length/2 +uneven; k++) {
if (++i > teams.length+uneven-1) {i = 1;}
if (--j < 1) {j = teams.length+uneven-1;}
if (uneven == 0 || (i < teams.length && j < teams.length) ) {
loggingAction(`#${++match_id}: ${team_roles[teams[i].id].name} - ${team_roles[teams[j].id].name}`)
const match = await Match.create({ id: match_id });
await match.setTeam_a(teams[i]);
await match.setTeam_b(teams[j]);
await match.destroy();
// the bot tips randomly
bot_tip(match_id)
}
}
}
}
async function generate_second_leg () {
const matches = await Match.findAll({ paranoid: false, include: ['team_a','team_b'] });
let match_id = matches.length;
for (const first_match of matches) {
const second_match = await Match.create({id: ++match_id});
await second_match.setTeam_a(first_match.team_b.id);
await second_match.setTeam_b(first_match.team_a.id);
loggingAction(`#${second_match.id}: ${team_roles[second_match.team_a.id].name} - Team #${team_roles[second_match.team_b.id].name}`);
// the bot tips randomly
bot_tip (match_id)
}
}
async function generate_phase_2 () {
for (const team_config of teams_config) {
const team = await Team.findOne({where: {id: team_config.id}});
team.div = team_config.div; team.save();
}
const teams = await Team.findAll();
const teams_concat = teams.concat(teams);
for (let div = 1; div<=2; div++) {
loggingAction(`\n\nPhase 2 - DIVISION ${div}\n`);
const div_teams = teams.filter( (team) => team.div == div);
const div_teams_concat = div_teams.concat(div_teams);
var match_id = 100*div;
for (let home_team = 0; home_team <= div_teams.length-1; home_team++) {
let p1_home_team = null;
for (let i=0; i < teams.length; i++) {
if (div_teams[home_team].id == teams[i].id) { p1_home_team = i }
}
const p1_out_teams = teams_concat.slice(p1_home_team+1, p1_home_team+1 + home_matches(teams, p1_home_team));
const opponents = div_teams_concat.slice(home_team+1, div_teams.length);
for (const opponent of opponents) {
var team_b = null;
var team_a = null;
if (p1_out_teams.includes(opponent)) {
team_a = opponent;
team_b = div_teams[home_team];
} else {
team_a = div_teams[home_team];
team_b = opponent;
}
loggingAction(`#${++match_id}: ${team_roles[team_a.id].name} - ${team_roles[team_b.id].name}`);
const match = await Match.create({ id: match_id });
await match.setTeam_a(team_a);
await match.setTeam_b(team_b);
await match.destroy();
// the bot tips randomly
bot_tip (match_id)
}
}
for (const team of teams) {
await print_team_matches(team);
}
}
static.phase = 2;
static.save();
}
function home_matches (teams, home_team) { // Get the number of home matches this team is supposed to have in phase 1
/*
if (home_team <= (teams.length-1)/2 && home_team % 2 == 1
|| home_team >= (teams.length-1)/2 && home_team % 2 == 0) {
return Math.floor((teams.length-1)/2)
} else {
return Math.ceil((teams.length-1)/2)
}
*/
if (home_team % 2 == 1) {
return Math.floor((teams.length-1)/2)
} else {
return Math.ceil((teams.length-1)/2)
}
}
async function getName (user_id) {
const member = await myGuild.members.fetch(user_id);
return (member.displayName);
}
function isAdmin (interaction) {
return (interaction.member._roles.includes(admin_role_id));
}
function isTeamCaptain (interaction, role_a_id, role_b_id) {
return (interaction.member._roles.includes(admin_role_id)
|| ( interaction.member._roles.includes(captain_role_id) && (interaction.member._roles.includes(role_a_id) || role_a_id == 'dummy') )
|| ( interaction.member._roles.includes(captain_role_id) && (interaction.member._roles.includes(role_b_id) || role_a_id == 'dummy') )
)
}
function loggingAction (action_text) {
let now = new Date(Date.now());
fs.appendFileSync('myLog.txt', `\n${now.toUTCString()}: ${action_text}`);
console.log(action_text)
return
}
async function loggingError (location_text, action_text, error) {
let now = new Date(Date.now());
const error_text =
`\n${now.toUTCString()}: ERROR in ${location_text}:`+
`\n${action_text}`+
`\n\n${error.stack}\n`;
console.error(error);
fs.appendFileSync('myLog.txt',error_text);
await janitor_channel.send(codeBlock(error_text));
return
}
async function postTips (match) {
var response1 = `[Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> - <@&${match.team_b.role_id}> has been closed for tips.`;
var response2 = '';
if((await match.countTips()) < 2) {
response1 = response1.concat(`\n**No one tipped on this match! Had I known this, I would not have worked on this bot. >:(**`);
}
for (var i = 4; i >= 0; i--) {
const tips = await match.getTips({ where: {score_a: i} });
response2 = response2.concat(`\n(${i}-${4-i}) - ${tips.length} - `);
for (const tip of tips) {
response2 = response2.concat(`${await getName(tip.tipper_id)}, `);
}
response2 = response2.slice(0,-2);
}
await tipping_channel.send({content: `${response1}\n${codeBlock(response2)}`, allowedMentions: {parse: []}});
return
}
async function advance_phase () {
if ( await Match.count({paranoid: false}) == await Match.count({ where: {[Op.or]: [{result_a: {[Op.not]: null}}, {is_cancelled: true}]} , paranoid: false }) ) {
if (static.phase == 1) {
updates_channel.send({
content: 'All Phase 1 matches have been played.Please\n\n**add the teams\' divisions to the config file**\n\n**restart the bot**\n\nand press the button below.',
components: [button_phase_2]
})
}
else {
updates_channel.send({
content: 'All matches have been played.\n\nPlease make sure all things are in order and press the button below to finish the event.',
components: [button_end_event]
})
}
}
return
}
async function request_result (match) {
try {
const link = 'https://speedball.the-dmark.com/stats/list/results.php?&event='+`${event_type}`+'&number='+`${event_number}`+'&match='+`${match.id}`+'&api=json';
const res = await fetch(link);
if (res.ok) {
const object = await res.json();
var i = 0;
var result_a = 0;
var log_text = `Received [Match #${indent(match.id, 3, '0')}] results:\n`+link;
for (const map in object.data) {
i++;
if(object.data[map].winner_team_id == match.team_a.id) {result_a++;};
log_text = log_text.concat(`\nmap #${i} - winner: ${team_roles[object.data[map].winner_team_id]?.name}, loser: ${team_roles[object.data[map].looser_team_id]?.name}`)
}
if (i != 4) {
loggingAction(log_text+`\nbut only ${i} matches have been played.`);
return null
}
loggingAction(log_text);
return result_a;
}
else {return false}
} catch (error) {
await loggingError('function request_result', '', error);
}
}
async function delete_result (interaction, match) {
loggingAction(`Deleting result of [Match #${indent(match.id, 3, '0')}]`);
match.result_a = null;
// updates
let now = new Date(Date.now());
match.history = (`\n${now.toLocaleString("en-GB", date_options_short)} <@${interaction.user.id}>: Result was deleted.`).concat(match.history);
var message = `[Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> _ - _ <@&${match.team_b.role_id}>`;
await updates_channel.messages.edit(match.announcement_id, { content: message+match.history, allowedMentions: {roles: [match.team_a.role_id, match.team_b.role_id]} })
let update = await updates_channel.send({
content: message+`\nhttps://discord.com/channels/${guildId}/${updates_channel.id}/${match.announcement_id}`
+` Result was deleted`,
allowedMentions: {parse: []}
})
if (match.latest_update_id) {
await updates_channel.messages.delete(match.latest_update_id);
}
match.latest_update_id = update.id;
match.save(); match.restore();
// edit teams' matches messages
await print_team_matches(match.team_a);
await print_team_matches(match.team_b);
// edit dms
const tips = await Tip.findAll({where: {match_id: match.id}, paranoid: false})
for (const tip of tips) {
if (tip.dm_id != null) {
const user = client.users.cache.get(tip.tipper_id);
await user.dmChannel.messages.edit(tip.dm_id, { components: [buttons_tipped_closed(tip.score_a)] })
}
await tip.restore();
}
if (match.tipping_id) {
tipping_channel.messages.edit( match.tipping_id, { components: [buttons_tip_closed] } );
}
await update_scoreboard();
return interaction.editReply({ content: `The result has been deleted.` })
}
async function submit_result (match, result_a) {
loggingAction(`Submitting result: ${team_roles[match.team_a.id].name} ${result_a} - ${4-result_a} ${team_roles[match.team_b.id].name}`);
match.result_a = result_a;
match.is_open = false;
// updates
let now = new Date(Date.now());
match.history = (`\n${now.toLocaleString("en-GB", date_options_short)}: Result was received: ${result_a} - ${4-result_a}`).concat(match.history);
var message = `[Match #${indent(match.id, 3, '0')}] <@&${match.team_a.role_id}> ${result_a} - ${4-result_a} <@&${match.team_b.role_id}>`;
await updates_channel.messages.edit(match.announcement_id, { content: message+match.history, allowedMentions: {roles: [match.team_a.role_id, match.team_b.role_id]} })
if (match.tipping_id) {
tipping_channel.messages.edit( match.tipping_id, { components: [buttons_tipped_green_closed(match.result_a)] } );
}
let update = await updates_channel.send({
content: message+`\nhttps://discord.com/channels/${guildId}/${updates_channel.id}/${match.announcement_id}`
+` Match ended: ${result_a} - ${4-result_a}`,
allowedMentions: {parse: []}
})
if (match.latest_update_id) {