-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
2758 lines (2686 loc) · 117 KB
/
index.ts
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
// Runs the VPCC-Bot
import _assert from "assert";
import { CategoryChannel, Client, Constants, DiscordAPIError, Guild, GuildChannel, Intents, Interaction, MessageActionRow, MessageButton, MessageComponentInteraction, MessageOptions, Permissions, Role, Team, TextChannel, User, VoiceChannel } from "discord.js";
import Keyv from "keyv";
import { KeyvFile } from "keyv-file";
import NodeCache from "node-cache";
import ReplitClient from "@replit/database";
require("dotenv").config();
const client = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS ], rejectOnRateLimit: () => true });
client.on("ready", client => {
console.log(`Logged in as ${client.user.tag}`);
});
function sleep(milliseconds: number) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
function assert<T>(thing: T): asserts thing is NonNullable<T> {
_assert(thing != null);
}
type Store = {
get(resource: string): Promise<Object>,
set(resource: string, data: Object): Promise<void>,
}
// keyv-file based store (will be upgraded to use replit's built in key value store later)
class KeyvStore implements Store {
keyv: Keyv<Object>;
constructor(keyv: Keyv<Object>) {
this.keyv = keyv;
};
async get(resource: string): Promise<Object> {
return (await this.keyv.get(resource)) ?? {};
};
async set(resource: string, data: Object): Promise<void> {
if (JSON.stringify(data) === "{}")
await this.keyv.delete(resource);
else
await this.keyv.set(resource, data);
};
}
// helper store that forwards assignments to an additional store
class CopyStore implements Store {
constructor(
public main: Store,
public backup: Store,
) {};
async get(resource: string): Promise<Object> {
return await this.main.get(resource);
};
async set(resource: string, data: Object): Promise<void> {
await this.main.set(resource, data);
return await this.backup.set(resource, data);
};
}
// wrapper class around the replit client to include a clear method
class ReplitBackedMap {
constructor(public client: ReplitClient) {};
async get(key: string): Promise<any> {
try { return await this.client.get(key) ?? undefined; }
catch (e) {
const raw = await this.client.get(key, { raw: true }) ?? undefined;
if (!raw) return raw;
return JSON.parse(raw.slice(1, -1));
}
}
async set(key: string, value: any) { await this.client.set(encodeURIComponent(key), value); return; }
async delete(key: string) { await this.client.delete(key); return true; }
async clear() { await this.client.empty(); return; }
}
/*
const fileStore = new KeyvStore(new Keyv({
store: new KeyvFile({
filename: "store.json",
}),
}) as Keyv<Object>);
*/
assert(process.env.REPLIT_DB_URL);
const replitStore = new KeyvStore(new Keyv({
store: new ReplitBackedMap(
new ReplitClient(process.env.REPLIT_DB_URL)
),
}));
let store: Store = replitStore;
/*
(async () => {
async function getset(resource: string): Promise<Record<string, any>> {
const data = await fileStore.get(resource);
await replitStore.set(resource, data);
await sleep(20);
return data;
}
// check if we've haven't migrated yet
const version = 2;
const meta = await store.get(`/meta`) as Record<string, any>;
if ((meta.version ?? 0) < version) {
// users
for (const id of (await getset(`/users`)).userIds ?? [])
await getset(`/user/${id}`);
// teams
for (const id of (await getset(`/teams`)).teamIds ?? [])
await getset(`/team/${id}`);
// workshops
for (const id of (await getset(`/workshops`)).ids ?? [])
await getset(`/workshop/${id}`);
// challenges
for (const id of (await getset(`/challenges`)).ids ?? [])
await getset(`/challenges/${id}`);
// submissions
for (const id of (await getset(`/submissions`)).ids ?? [])
await getset(`/submissions/${id}`);
// submissions
for (const id of (await getset(`/submissions`)).ids ?? [])
await getset(`/submissions/${id}`);
// interactions
for (const id of (await getset(`/interactions`)).interactionIds ?? [])
await getset(`/interaction/${id}`);
// joinRandom
await getset(`/joinRandom`);
// leaderboard
await getset(`/leaderboard`);
// update migration version
await store.set(`/meta`, { version });
}
console.log(`at version ${version}`);
store = replitStore;
})();
*/
// Helper function to remove an element from an array
function removeFromArray<T>(array: T[], element: T): typeof array {
const index = array.lastIndexOf(element);
if (index !== -1)
array.splice(index, 1);
return array;
}
// Asynchronous version of Array.prototype.find
async function findPredicate<T>(array: T[], predicate: (v: T, i: number, a: typeof array) => Promise<boolean>): Promise<T | undefined> {
for (let i = 0; i < array.length; i++) {
if (await predicate(array[i], i, array)) {
return array[i];
}
}
return undefined;
}
// - VPCC specific helper functions
// global cache object
type ResourceFetchOptions = string | { force?: boolean; resource: string; cache?: boolean };
class Resources {
store: Store;
cache: NodeCache;
resourceCache: WeakMap<object, string>;
constructor(store: Store) {
this.store = store;
this.cache = new NodeCache();
this.resourceCache = new WeakMap();
};
// call with a resource string or an object with { resource, force = false, cache = true }
async fetch(options: ResourceFetchOptions): Promise<Record<string, any>> {
if (typeof options === "string")
options = { resource: options };
let obj: Record<string, any> | null | undefined = undefined;
if (!(options.force ?? false))
obj = this.cache.get(options.resource);
if (obj == null) {
obj = await this.store.get(options.resource);
if (options.cache ?? true)
this.cache.set(options.resource, obj);
}
this.resourceCache.set(obj, options.resource);
return obj;
};
// update the resource object to the store
async push(obj: Record<string, any>) {
const resource = this.resourceCache.get(obj);
if (resource == null) return;
this.cache.del(resource);
return await this.store.set(resource, obj);
};
// invalidate the cache
async invalidate() {
this.cache.flushAll();
};
}
function createResources(store: Store): Resources {
return new Resources(store);
}
const resources = createResources(store);
// creates a "transaction" that updates all changed values at the end
class Transaction {
resources: Resources;
data: Record<string, any>;
constructor(resources: Resources) {
this.resources = resources;
this.data = {};
};
// call with a resource string or an object with resources.fetch.options
async fetch(options: ResourceFetchOptions): Promise<Record<string, any>> {
if (typeof options === "string")
options = { resource: options };
if (this.data[options.resource] != null)
return this.data[options.resource];
const obj = await this.resources.fetch(options);
if (this.data[options.resource] != null)
return this.data[options.resource];
return this.data[options.resource] = obj;
};
// pushes all changes and clears data
async commit(): Promise<void> {
for (const resource in this.data) {
// future: check if something actually changed before pushing
await this.resources.push(this.data[resource]);
delete this.data[resource];
}
};
}
function createTransaction(resources: Resources) {
return new Transaction(resources);
}
let running = false;
// fetchable type
type Fetchable = Transaction | Resources;
// deletes all values from an object
function clearObject(obj: Record<string, any>) {
for (const name in obj)
delete obj[name];
}
type TeamsData = {
teamIds: TeamData["id"][],
}
type UsersData = {
userIds: UserData["id"][],
}
type TeamData = {
id: string,
name: string,
memberIds: string[],
discordRoleId: string,
discordTextChannelId: string,
discordVoiceChannelId: string,
freeToJoin?: boolean,
submissionIds?: string[],
}
type UserData = {
id: string,
teamId?: string,
discordUserId: string,
}
// get users info
async function fetchUsers(resources: Fetchable): Promise<UsersData> {
const users = await resources.fetch(`/users`);
users.userIds ??= [];
return users as UsersData;
}
// get teams info
async function fetchTeams(resources: Fetchable): Promise<TeamsData> {
const teams = await resources.fetch(`/teams`);
teams.teamIds ??= [];
return teams as TeamsData;
}
// Typed Object.keys
function* objectKeys<T>(thing: T): Generator<keyof T> {
for (const name in thing) {
yield name as keyof T;
}
}
// find user with matching requirements
async function findUser(resources: Fetchable, requirements: Partial<UserData>) {
users:
for (const userId of (await fetchUsers(resources)).userIds) {
let user = await fetchUser(resources, userId);
for (const name of objectKeys(requirements))
if (requirements[name] !== user[name])
continue users;
return user;
}
return undefined;
}
// find team with matching requirements
async function findTeam(resources: Fetchable, requirements: Partial<TeamData>) {
teams:
for (const teamId of (await fetchTeams(resources)).teamIds) {
let team = await fetchTeam(resources, teamId);
for (const name of objectKeys(requirements))
if (requirements[name] !== team[name])
continue teams;
return team;
}
return undefined;
}
// find user with id
async function fetchUser(resources: Fetchable, userId: string): Promise<UserData> {
const user = await resources.fetch(`/user/${userId}`);
user.id ??= userId;
return user as UserData;
}
// find teamId with id
async function fetchTeam(resources: Fetchable, teamId: string): Promise<TeamData> {
const team = await resources.fetch(`/team/${teamId}`);
team.id ??= teamId;
return team as TeamData;
}
async function createUser(_guild: any, transaction: Fetchable, { id, ...properties }: UserData): Promise<UserData> {
const users = await fetchUsers(transaction);
const user = await fetchUser(transaction, id);
// create user with properties
Object.assign(user, properties);
(users.userIds ??= []).push(user.id);
return user;
}
class InteractionError extends Error {
name = "InteractionError";
}
async function createTeam(guild: Guild, transaction: Fetchable, { id, ...properties }: Pick<TeamData, "id" | "name" | "freeToJoin">): Promise<TeamData> {
const teams = await fetchTeams(transaction);
const team = await fetchTeam(transaction, id);
// create team with properties
Object.assign(team, properties);
(teams.teamIds ??= []).push(team.id);
team.memberIds ??= [];
// create team role
const role = await guild.roles.create({ name: `Team ${team.name}` });
team.discordRoleId = role.id;
// get supervisor role
const supervisorRole = (await guild.roles.fetch()).find((role: { name: string; }) => role.name.toLowerCase() === "supervisor")
// create team text and voice channels
const teamCategory = (await guild.channels.fetch()).find((channel: GuildChannel) => (
channel instanceof CategoryChannel
&& channel.name.toLowerCase() === "team"
)) as CategoryChannel | undefined;
if (teamCategory == null)
throw new Error("team category not found");
const channelOptions = {
parent: teamCategory,
permissionOverwrites: [
{ id: guild.roles.everyone, deny: [ Permissions.FLAGS.VIEW_CHANNEL ] },
{ id: role, allow: [ Permissions.FLAGS.VIEW_CHANNEL ] },
],
};
if (supervisorRole != null) {
channelOptions.permissionOverwrites.push(
{ id: supervisorRole, allow: [ Permissions.FLAGS.VIEW_CHANNEL ] },
);
} else {
console.log("sus no supervisor role");
}
const textChannel = await guild.channels.create(`Team ${team.name}`, channelOptions);
const voiceChannel = await guild.channels.create(`Team ${team.name}`, { type: "GUILD_VOICE", ...channelOptions });
team.discordTextChannelId = textChannel.id;
team.discordVoiceChannelId = voiceChannel.id;
return team;
}
async function joinTeam(guild: Guild, _transaction: Fetchable, team: TeamData, user: UserData) {
// join team
(team.memberIds ??= []).push(user.id);
user.teamId = team.id;
// join team role
const discordMember = await guild.members.fetch(user.discordUserId);
const role = await guild.roles.fetch(team.discordRoleId);
assert(role);
await discordMember.roles.add(role);
}
async function renameTeam(guild: Guild, _transaction: Fetchable, team: TeamData, name: string) {
// rename team
team.name = name;
// rename team channels
assert(team.discordTextChannelId);
assert(team.discordVoiceChannelId);
const textChannel = await guild.channels.fetch(team.discordTextChannelId);
const voiceChannel = await guild.channels.fetch(team.discordVoiceChannelId);
assert(textChannel);
assert(voiceChannel);
await textChannel.edit({ name: `Team ${name}` });
await voiceChannel.edit({ name: `Team ${name}` });
// rename role
assert(team.discordRoleId);
const role = await guild.roles.fetch(team.discordRoleId);
assert(role);
await role.edit({ name: `Team ${name}` });
}
async function leaveTeam(guild: Guild, transaction: Fetchable, user: UserData) {
assert(user.teamId);
const team = await fetchTeam(transaction, user.teamId);
team.id ??= user.teamId;
// leave team role
const discordMember = await guild.members.fetch(user.discordUserId);
assert(team.discordRoleId);
const role = await guild.roles.fetch(team.discordRoleId);
assert(role);
await discordMember.roles.remove(role);
// leave team
removeFromArray((team.memberIds ??= []), user.id);
user.teamId = undefined;
}
async function destroyTeam(guild: Guild, transaction: Fetchable, team: TeamData) {
const teams = await fetchTeams(transaction);
// remove team channels
assert(team.discordTextChannelId);
assert(team.discordVoiceChannelId);
const textChannel = await guild.channels.fetch(team.discordTextChannelId);
const voiceChannel = await guild.channels.fetch(team.discordVoiceChannelId);
assert(textChannel);
assert(voiceChannel);
await textChannel.delete();
await voiceChannel.delete();
// remove team role
assert(team.discordRoleId);
const role = await guild.roles.fetch(team.discordRoleId);
assert(role);
await role.delete();
// remove team
removeFromArray((teams.teamIds ??= []), team.id);
clearObject(team);
}
async function checkJoinRandom() {
const guild = await client.guilds.fetch(process.env.GUILD_ID!);
console.log("running check on joinRandom");
const transaction = createTransaction(resources);
// check if joinRandom info is past 30 minutes
const joinRandomInfo = await transaction.fetch(`/joinRandom`);
if (joinRandomInfo.start == null || joinRandomInfo.start + 30 * 60_000 > Date.now())
return;
console.log("attempting to add user");
// ensure user still doesnt have a team
const caller = await fetchUser(transaction, joinRandomInfo.caller);
let bestTeam = undefined;
if (caller.teamId == null) {
// loop through all teams and get a free to join team with the smallest team size
for (const teamId of (await fetchTeams(transaction)).teamIds ?? []) {
const team = await fetchTeam(transaction, teamId);
if (!team.freeToJoin) continue;
if (team.memberIds.length >= 4) continue;
if (!bestTeam ? true : team.memberIds.length < bestTeam.memberIds.length) {
bestTeam = team;
}
}
// if there's no team available, dm the user with sad face
if (bestTeam == null) {
(await (await guild.channels.fetch(joinRandomInfo.discordChannelId) as TextChannel).messages.fetch(joinRandomInfo.discordMessageId)).delete();
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds ?? [], joinRandomInfo.interactionId);
clearObject(await transaction.fetch(`/interaction/${joinRandomInfo.interactionId}`));
clearObject(joinRandomInfo);
await transaction.commit();
await (await (await guild.members.fetch(caller.discordUserId)).createDM()).send("30 minutes passed but no free to join teams were available :(")
return;
}
// join the team and clear info
await joinTeam(guild, transaction, bestTeam, caller);
}
const channel = await guild.channels.fetch(joinRandomInfo.discordChannelId) as TextChannel;
(await channel.messages.fetch(joinRandomInfo.discordMessageId)).delete();
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds ?? [], joinRandomInfo.interactionId);
clearObject(await transaction.fetch(`/interaction/${joinRandomInfo.interactionId}`));
clearObject(joinRandomInfo);
await transaction.commit();
if (bestTeam != null) {
await (await (await guild.members.fetch(caller.discordUserId)).createDM()).send(`30 minutes passed so I've put you in team ${bestTeam.name}`);
}
}
client.once("ready", async () => {
while (true) {
await Promise.all([
checkJoinRandom(),
sleep(60_000),
]);
}
});
// - Resolution functions
async function resolveUser(resources: Fetchable, userResolvable: string): Promise<UserData | undefined> {
const userById = await resources.fetch(`/user/${userResolvable}`);
if (userById.id)
return userById as UserData;
for (const userId of (await resources.fetch(`/users`)).userIds ?? []) {
const user = await resources.fetch(`/user/${userId}`);
if (user.discordUserId === userResolvable)
return user as UserData;
}
}
async function resolveTeam(resources: Fetchable, teamResolvable: string): Promise<TeamData | undefined> {
const teamById = await resources.fetch(`/team/${teamResolvable}`);
if (teamById.id)
return teamById as TeamData;
for (const teamId of (await resources.fetch(`/teams`)).teamIds ?? []) {
const team = await resources.fetch(`/team/${teamId}`);
if (team.name.toLowerCase() === teamResolvable.toLowerCase())
return team as TeamData;
}
}
async function resolveWorkshop(resources: Fetchable, workshopResolvable: string): Promise<Record<string, any> | undefined> {
const workshopById = await resources.fetch(`/workshop/${workshopResolvable}`);
if (workshopById.id)
return workshopById;
for (const workshopId of (await resources.fetch(`/workshops`)).ids ?? []) {
const workshop = await resources.fetch(`/workshop/${workshopId}`);
if (workshop.name.toLowerCase() === workshopResolvable.toLowerCase())
return workshop;
}
}
async function resolveChallenge(resources: Fetchable, challengeResolvable: string): Promise<Record<string, any> | undefined> {
const challengeById = await resources.fetch(`/challenges/${challengeResolvable}`);
if (challengeById.id)
return challengeById;
if (challengeResolvable.includes(":")) {
const splitIndex = challengeResolvable.indexOf(":");
const workshop = await resolveWorkshop(resources, challengeResolvable.substring(0, splitIndex));
const challengeResolvable2 = challengeResolvable.substring(splitIndex + 1);
if (workshop)
for (const challengeId of (workshop.challengeIds ?? [])) {
const challenge = await resources.fetch(`/challenges/${challengeId}`);
if (challenge.name.toLowerCase() === challengeResolvable2.toLowerCase())
return challenge;
}
}
for (const challengeId of (await resources.fetch(`/challenges`)).ids ?? []) {
const challenge = await resources.fetch(`/challenges/${challengeId}`);
if (challenge.name.toLowerCase() === challengeResolvable.toLowerCase())
return challenge;
}
}
async function resolveSubmission(resources: Fetchable, submissionResolvable: string): Promise<Record<string, any> | undefined> {
const submissionById = await resources.fetch(`/submissions/${submissionResolvable}`);
if (submissionById.id)
return submissionById;
}
// - Prompt creation helpers
function createInfoOptions({ title, description = undefined, info }: {
title: string,
description?: string,
info: Record<string, string[] | undefined>,
}): Pick<MessageOptions, "content"> {
return { content: (
title + "\n"
+ (description ? description + "\n" : "")
+ Object.entries(info)
.map(([ k, v ]) => v == null ? "" : ` - ${k}: ${v.length > 0 ? v.join(", ") : "*empty*"}\n`)
.join("")
) };
}
function createTeamInvitationOptions(
teamName: string,
caller: string,
waiting: string[],
accepted: string[],
declined: string[],
disabled: boolean = false,
): MessageOptions {
return {
...createInfoOptions({
title: `${caller} is inviting people to join Team ${teamName}`,
info: { "Waiting": waiting, "Accepted": accepted, "Declined": declined },
}),
components: [
new MessageActionRow({ components: [
new MessageButton({ customId: "accept", label: "Accept", style: "SUCCESS", disabled }),
new MessageButton({ customId: "decline", label: "Decline", style: "DANGER", disabled }),
new MessageButton({ customId: "cancel", label: "Cancel", style: "SECONDARY", disabled }),
] }),
],
};
}
function createTeamJoinRequestOptions(
teamName: string,
caller: string,
waiting: string[],
approved: string[],
rejected: string[],
disabled: boolean = false,
): MessageOptions {
return {
...createInfoOptions({
title: `${caller} wants to join Team ${teamName} (${Math.floor((waiting.length + approved.length + rejected.length) / 2 + 1)} needed for approval)`,
info: { "Waiting": waiting, "Approved": approved, "Rejected": rejected },
}),
components: [
new MessageActionRow({ components: [
new MessageButton({ customId: "approve", label: "Approve", style: "SUCCESS", disabled }),
new MessageButton({ customId: "reject", label: "Reject", style: "DANGER", disabled }),
new MessageButton({ customId: "cancel", label: "Cancel", style: "SECONDARY", disabled }),
] }),
],
};
}
function createTeamRenameRequestOptions(
teamName: string,
newTeamName: string,
caller: string,
waiting: string[],
approved: string[],
rejected: string[],
disabled: boolean = false,
): MessageOptions {
return {
...createInfoOptions({
title: `${caller} wants to rename Team ${teamName} to ${newTeamName} (${Math.floor((waiting.length + approved.length + rejected.length) / 2 + 1)} needed for approval)`,
info: { "Waiting": waiting, "Approved": approved, "Rejected": rejected },
}),
components: [
new MessageActionRow({ components: [
new MessageButton({ customId: "approve", label: "Approve", style: "SUCCESS", disabled }),
new MessageButton({ customId: "reject", label: "Reject", style: "DANGER", disabled }),
new MessageButton({ customId: "cancel", label: "Cancel", style: "SECONDARY", disabled }),
] }),
],
};
}
function createRoleUpdateOptions(
roleName: string,
disabled: boolean = false,
): MessageOptions {
return { components: [
new MessageActionRow({ components: [
new MessageButton({ customId: "add", label: `Get ${roleName} role`, style: "SUCCESS", disabled }),
new MessageButton({ customId: "remove", label: `Remove ${roleName} role`, style: "SECONDARY", disabled }),
] }),
] };
}
// accept: ✅
// deny: ❌
// cancel: 🗑️
/*
const filter = (reaction, user) => reaction.emoji.name === '👍' && user.id === message.author.id;
const reactions = await message.awaitReactions({ filter, max: 1, time: 60_000 });
*/
const ephemeral = true;
// Process button interactions
client.on("interactionCreate", async (interaction: Interaction) => {
if (!interaction.isButton())
return;
try {
await interaction.deferUpdate();
} catch (e) {
console.log(e);
}
console.log({
timestamp: Date.now(),
userDisplayName: interaction.user.tag,
userId: interaction.user.id,
messageId: interaction.message.id,
customId: interaction.customId,
});
try {
if (running) return;
running = true;
assert(interaction.guild);
assert(interaction.channel);
const message = await interaction.channel.messages.fetch((await interaction.fetchReply()).id);
const transaction = createTransaction(resources);
if (!((await transaction.fetch(`/interactions`)).interactionIds ?? []).includes(interaction.message.id)) {
// await interaction.editReply(`Could not find interaction to continue`);
console.log("unknown interaction");
return;
}
const info = await transaction.fetch(`/interaction/${interaction.message.id}`);
const action = interaction.customId;
if (info.type === "teamCreate") {
// ensure caller
let callerUser = await findUser(transaction, { discordUserId: interaction.user.id });
if (callerUser == null)
callerUser = await createUser(interaction.guild, transaction, { id: `${interaction.id}${interaction.user.id}`, discordUserId: interaction.user.id });
async function createTeamInvitationOptionsFromInfo(info: Record<string, any>, disabled: boolean = false): Promise<MessageOptions> {
return createTeamInvitationOptions(
info.futureTeamName,
`<@${(await fetchUser(transaction, info.caller)).discordUserId}>`,
await Promise.all(info.waiting.map(async (id: string) => `<@${(await fetchUser(resources, id)).discordUserId}>`)),
await Promise.all(info.accepted.map(async (id: string) => `<@${(await fetchUser(resources, id)).discordUserId}>`)),
await Promise.all(info.declined.map(async (id: string) => `<@${(await fetchUser(resources, id)).discordUserId}>`)),
disabled,
)
}
if (action === "accept") {
if (info.caller === callerUser.id)
throw new InteractionError(`You cannot accept your own invitation`);
if (info.accepted.includes(callerUser.id))
throw new InteractionError(`You cannot accept this invitation again`);
if (info.declined.includes(callerUser.id))
throw new InteractionError(`You cannot accept this invitation after declining it`);
if (!info.waiting.includes(callerUser.id))
throw new InteractionError(`You weren't invited`);
// fail if caller is already in a team
if (callerUser.teamId != null) {
throw new InteractionError(`You are already on a team`);
}
if (info.accepted.length === 0) {
// fail if another team with same name exists
if (await findTeam(transaction, { name: info.futureTeamName }) != null) {
const options = await createTeamInvitationOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, info.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
await message.reply(`Team called ${info.futureTeamName} now exists :(`);
return;
}
removeFromArray(info.waiting, callerUser.id);
info.accepted.push(callerUser.id);
// create team
const team = await createTeam(interaction.guild, transaction, {
id: info.futureTeamId,
name: info.futureTeamName,
});
for (const userId of [ info.caller, ...info.accepted ])
await joinTeam(interaction.guild, transaction, team, await fetchUser(transaction, userId));
if (info.waiting.length === 0) {
const options = await createTeamInvitationOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
await message.reply(`Team ${team.name} is created`);
return
}
await transaction.commit();
await message.edit(await createTeamInvitationOptionsFromInfo(info));
await message.reply(`Team ${team.name} is created`);
return;
} else {
// fail if team is full
const team = await fetchTeam(transaction, info.futureTeamId)
if (team.memberIds.length >= 4)
throw new InteractionError(`Team ${info.futureTeamName} is now full`);
removeFromArray(info.waiting, callerUser.id);
info.accepted.push(callerUser.id);
await joinTeam(interaction.guild, transaction, team, callerUser);
if (info.waiting.length === 0) {
const options = await createTeamInvitationOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
return
}
await transaction.commit();
await message.edit(await createTeamInvitationOptionsFromInfo(info));
await interaction.followUp({ ephemeral, content: `Accepted invitation to join team ${team.name}` });
return;
}
}
if (action === "decline") {
if (info.caller === callerUser.id)
throw new InteractionError(`You cannot decline your own invitation`);
if (info.declined.includes(callerUser.id))
throw new InteractionError(`You cannot decline this invitation again`);
if (info.accepted.includes(callerUser.id))
throw new InteractionError(`You cannot decline this invitation after accepting it`);
if (!info.waiting.includes(callerUser.id))
throw new InteractionError(`You weren't invited`);
removeFromArray(info.waiting, callerUser.id);
info.declined.push(callerUser.id);
if (info.waiting.length == 0) {
const teamName = info.futureTeamName;
const options = await createTeamInvitationOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
await message.reply(`Team ${teamName} won't be created`);
return;
}
await transaction.commit();
await message.edit(await createTeamInvitationOptionsFromInfo(info));
await interaction.followUp({ ephemeral, content: `Declined invitation to join team ${info.futureTeamName}` });
return;
}
if (action === "cancel") {
if (info.caller !== callerUser.id)
throw new InteractionError(`You aren't the inviter`);
const teamName = info.futureTeamName;
const options = await createTeamInvitationOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
await message.reply(`Invitations to team ${teamName} cancelled`);
return;
}
}
if (info.type === "teamJoin") {
const team = await fetchTeam(transaction, info.teamId);
const numMembers = info.waiting.length + info.approved.length + info.rejected.length;
async function createTeamJoinRequestOptionsFromInfo(info: Record<string, any>, disabled: boolean = false): Promise<MessageOptions> {
return createTeamJoinRequestOptions(
team.name,
`<@${(await fetchUser(transaction, info.caller)).discordUserId}>`,
await Promise.all(info.waiting.map(async (id: string) => `<@${(await fetchUser(resources, id)).discordUserId}>`)),
await Promise.all(info.approved.map(async (id: string) => `<@${(await fetchUser(resources, id)).discordUserId}>`)),
await Promise.all(info.rejected.map(async (id: string) => `<@${(await fetchUser(resources, id)).discordUserId}>`)),
disabled,
)
}
// ensure caller
let callerUser = await findUser(transaction, { discordUserId: interaction.user.id });
if (callerUser == null)
callerUser = await createUser(interaction.guild, transaction, { id: `${interaction.id}${interaction.user.id}`, discordUserId: interaction.user.id });
if (action === "approve") {
if (info.approved.includes(callerUser.id))
throw new InteractionError(`You cannot approve this join request again`);
if (info.rejected.includes(callerUser.id))
throw new InteractionError(`You cannot approve this join request after rejecting it`);
if (!info.waiting.includes(callerUser.id))
throw new InteractionError(`You are not in this team`);
removeFromArray(info.waiting, callerUser.id);
info.approved.push(callerUser.id);
const requester = await fetchUser(transaction, info.caller);
if (info.approved.length > numMembers / 2) {
// fail if team is full
if (team.memberIds.length >= 4) {
const options = await createTeamJoinRequestOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
await message.reply(`<@${requester.discordUserId}>'s requested team is now full`);
return;
}
// fail if caller is already in a team
if (requester.teamId != null) {
const options = await createTeamJoinRequestOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
await message.reply(`<@${requester.discordUserId}> now has a team`);
return;
}
await joinTeam(interaction.guild, transaction, team, requester);
const options = await createTeamJoinRequestOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
await message.reply(`<@${requester.discordUserId}> joined team ${team.name}`);
return;
}
await transaction.commit();
await message.edit(await createTeamJoinRequestOptionsFromInfo(info));
await interaction.followUp({ ephemeral, content: `Approved request from <@${requester.discordUserId}> to join team ${team.name}` });
return;
}
if (action === "reject") {
if (info.rejected.includes(callerUser.id))
throw new InteractionError(`You cannot reject this join request again`);
if (info.approved.includes(callerUser.id))
throw new InteractionError(`You cannot reject this join request after approving it`);
if (!info.waiting.includes(callerUser.id))
throw new InteractionError(`You are not in this team`);
removeFromArray(info.waiting, callerUser.id);
info.rejected.push(callerUser.id);
const callerDiscordUserId = (await fetchUser(transaction, info.caller)).discordUserId;
if (info.rejected.length >= numMembers / 2) {
const options = await createTeamJoinRequestOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
await message.reply(`Rejected <@${callerDiscordUserId}>'s request to join team ${team.name}`);
return;
}
await transaction.commit();
await message.edit(await createTeamJoinRequestOptionsFromInfo(info));
await interaction.followUp({ ephemeral, content: `Rejected request from <@${callerDiscordUserId}> to join team ${team.name}` });
return;
}
if (action === "cancel") {
if (info.caller !== callerUser.id)
throw new InteractionError(`You can't cancel someone else's request to join`);
const callerDiscordUserId = (await fetchUser(transaction, info.caller)).discordUserId;
const options = await createTeamJoinRequestOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
await message.reply(`<@${callerDiscordUserId}>'s request to join ${team.name} is cancelled`);
return;
}
}
if (info.type === "teamRename") {
const team = await fetchTeam(transaction, info.teamId);
const numMembers = info.waiting.length + info.approved.length + info.rejected.length;
async function createTeamRenameRequestOptionsFromInfo(info: Record<string, any>, disabled: boolean = false): Promise<MessageOptions> {
return createTeamRenameRequestOptions(
team.name,
info.newTeamName,
`<@${(await fetchUser(transaction, info.caller)).discordUserId}>`,
await Promise.all(info.waiting.map(async (id: string) => `<@${(await fetchUser(resources, id)).discordUserId}>`)),
await Promise.all(info.approved.map(async (id: string) => `<@${(await fetchUser(resources, id)).discordUserId}>`)),
await Promise.all(info.rejected.map(async (id: string) => `<@${(await fetchUser(resources, id)).discordUserId}>`)),
disabled,
)
}
// ensure caller
let callerUser = await findUser(transaction, { discordUserId: interaction.user.id });
if (callerUser == null)
callerUser = await createUser(interaction.guild, transaction, { id: `${interaction.id}${interaction.user.id}`, discordUserId: interaction.user.id });
if (action === "approve") {
if (info.caller === callerUser.id)
throw new InteractionError(`You cannot approve your own rename request`);
if (info.approved.includes(callerUser.id))
throw new InteractionError(`You cannot approve this rename request again`);
if (info.rejected.includes(callerUser.id))
throw new InteractionError(`You cannot approve this rename request after rejecting it`);
if (!info.waiting.includes(callerUser.id))
throw new InteractionError(`You are not in this team`);
removeFromArray(info.waiting, callerUser.id);
info.approved.push(callerUser.id);
if (info.approved.length > numMembers / 2) {
const oldTeamName = team.name;
// fail if another team with same name exists
if (await findTeam(transaction, { name: info.newTeamName }) != null) {
const options = await createTeamRenameRequestOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
await message.reply(`Team called ${info.newTeamName} now exists :(`);
return;
}
const options = await createTeamRenameRequestOptionsFromInfo(info, true);
await renameTeam(interaction.guild, transaction, team, info.newTeamName);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);
clearObject(info);
await transaction.commit();
await message.edit(options);
await message.reply(`Renamed team ${oldTeamName} to ${team.name}`);
return;
}
await transaction.commit();
await message.edit(await createTeamRenameRequestOptionsFromInfo(info));
await interaction.followUp({ ephemeral, content: `Approved request to rename team ${team.name} to ${info.newTeamName}` });
return;
}
if (action === "reject") {
if (info.caller === callerUser.id)
throw new InteractionError(`You cannot reject your own rename request`);
if (info.rejected.includes(callerUser.id))
throw new InteractionError(`You cannot reject this rename request again`);
if (info.approved.includes(callerUser.id))
throw new InteractionError(`You cannot reject this rename request after approving it`);
if (!info.waiting.includes(callerUser.id))
throw new InteractionError(`You are not in this team`);
removeFromArray(info.waiting, callerUser.id);
info.rejected.push(callerUser.id);
if (info.rejected.length >= numMembers / 2) {
const teamName = info.newTeamName;
const options = await createTeamRenameRequestOptionsFromInfo(info, true);
removeFromArray((await transaction.fetch(`/interactions`)).interactionIds, interaction.message.id);