-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathduel.ts
More file actions
467 lines (416 loc) · 17 KB
/
duel.ts
File metadata and controls
467 lines (416 loc) · 17 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
import {
ActionRowBuilder,
ApplicationCommandOptionType,
ButtonBuilder,
ButtonInteraction,
ButtonStyle,
CommandInteraction,
EmbedBuilder,
GuildMember,
MessageActionRowComponentBuilder,
User,
inlineCode,
} from 'discord.js'
import { Discord, Slash, SlashGroup, SlashOption } from 'discordx'
import { injectable } from 'tsyringe'
import { ORM } from '../persistence/ORM.js'
import { Duels } from '../../prisma/generated/prisma-client-js/index.js'
import { ColorRoles } from './roleCommands/changecolor.js'
import {
ephemeralButtonFollowup,
ephemeralReply,
getCallerFromCommand,
getGuildAndCallerFromCommand,
} from '../utils/CommandUtils.js'
import { shuffleArray } from '../utils/Helpers.js'
export const DUEL_COOLDOWN = 10 * 60 * 1000 // Cooldown period after loss in milliseconds
const GLOBAL_DUEL_TIMEOUT_DURATION = 5 * 60 * 1000
const NAMED_DUEL_TIMEOUT_DURATION = 1 * 60 * 1000
const DRAW_TIMEOUT_DURATION = 10 * 60 * 1000
@Discord()
@SlashGroup({ name: 'duel', description: 'Duel minigame' })
@SlashGroup('duel')
@injectable()
class Duel {
private inProgress = false
// Time before the duel is declared dead in milliseconds
private timeout: ReturnType<typeof setTimeout> | null = null
public constructor(private client: ORM) {}
@Slash({ name: 'challenge', description: 'Challenge the chat to a duel' })
private async duel(
@SlashOption({
name: 'wager',
type: ApplicationCommandOptionType.String,
description: 'Make this duel mean something',
required: false,
})
wager: string | undefined,
@SlashOption({
name: 'opponent',
type: ApplicationCommandOptionType.User,
description: 'The one person who can accept the duel',
})
wantedAccepter: GuildMember | undefined,
interaction: CommandInteraction
) {
if (wager && wager.length > 420) {
return ephemeralReply(interaction, { content: 'Stop.' })
}
// Get the challenger from the DB. Create them if they don't exist yet.
const challenger = interaction.user
if (challenger.id === wantedAccepter?.id) {
return ephemeralReply(interaction, { content: 'You cannot duel yourself.' })
}
if (wantedAccepter?.user.bot) {
return ephemeralReply(interaction, { content: 'Stop trying to fight a bot, chat.' })
}
// Check if a duel is currently already going on.
if (this.inProgress) {
return ephemeralReply(interaction, { content: 'A duel is already in progress.' })
}
const challengerStats = await this.getUserWithDuelStats(interaction.user.id)
if (!challengerStats) {
return ephemeralReply(interaction, { content: 'An unexpected error occurred.' })
}
// check if the challenger has recently lost
const userCooldownEnd = challengerStats.lastLoss.getTime() + DUEL_COOLDOWN
if (userCooldownEnd > Date.now()) {
return ephemeralReply(interaction, {
content: `${challenger}, you have recently lost a duel. You can duel again <t:${Math.floor(userCooldownEnd / 1000)}:R>.`,
})
}
const wagerMsg = wager ? '> ' + wager + '\n' : ''
let timeoutDuration = GLOBAL_DUEL_TIMEOUT_DURATION
let content = `${wagerMsg}${challenger} is looking for a duel, press the button to accept.`
let failedDuelContent = `${wagerMsg}${challenger} failed to find someone to duel.`
// Differenciate between a global duel and a named one
if (wantedAccepter) {
// Check wanted accepter cooldown before creating a duel
// The duel would almost certantly time out if that were the case
const wantedAccepterStats = await this.getUserWithDuelStats(wantedAccepter.id)
if (!wantedAccepterStats) {
return ephemeralReply(interaction, {
content: "An unexpected error occurred while fetching your opponents' stats.",
})
}
const wantedAccepterCooldownEnd = wantedAccepterStats.lastLoss.getTime() + DUEL_COOLDOWN
if (wantedAccepterCooldownEnd > Date.now()) {
return ephemeralReply(interaction, {
content: `${wantedAccepter} has recently lost a duel, you cannot challenge them right now. They can duel again <t:${Math.floor(wantedAccepterCooldownEnd / 1000)}:R>.`,
})
}
timeoutDuration = NAMED_DUEL_TIMEOUT_DURATION
content = `${wagerMsg}${challenger} is looking for a duel against ${wantedAccepter}, press the button to accept.`
failedDuelContent = `${wagerMsg}${wantedAccepter} failed to accept ${challenger}'s duel.`
}
// Are we on global CD?
// todo MultiGuild: This shouldn't be hardcoded (#Mixu's id)
const guildId = interaction.guildId
if (guildId && interaction.channelId !== '340275382093611011') {
const guildOptions = await this.client.guildOptions.upsert({
where: { guildId },
update: {},
create: { guildId },
})
const globalCooldownEnd = guildOptions.lastDuel.getTime() + guildOptions.globalDuelCD
if (globalCooldownEnd > Date.now()) {
return ephemeralReply(interaction, {
content: `Duels are on cooldown here. You can duel again <t:${Math.floor(globalCooldownEnd / 1000)}:R>.`,
})
}
}
this.inProgress = true
// Disable the duel after a timeout
this.timeout = setTimeout(async () => {
this.inProgress = false
// Disable the button
const button = this.createButton(true)
const row = new ActionRowBuilder<MessageActionRowComponentBuilder>().addComponents(button)
await interaction.editReply({ content: failedDuelContent, components: [row] })
}, timeoutDuration)
const row = new ActionRowBuilder<MessageActionRowComponentBuilder>().addComponents(this.createButton(false))
const response = await interaction.reply({ content, withResponse: true, components: [row] })
const collector = response.resource?.message?.createMessageComponentCollector()
if (!collector) {
throw new Error('Could not create duel button collector.')
}
collector.on('collect', async (collectionInteraction: ButtonInteraction) => {
await collectionInteraction.deferUpdate()
// Prevent accepting your own duels and ensure that the accepter is valid.
const accepter = collectionInteraction.user
if (wantedAccepter && accepter.id !== wantedAccepter.id) {
return ephemeralButtonFollowup(collectionInteraction, { content: "This duel wasn't meant for you, BEGONE!" })
}
const accepterStats = await this.getUserWithDuelStats(collectionInteraction.user.id)
if (!accepterStats || accepterStats.id === challenger.id) {
return
}
// Check if the accepter has recently lost and can't duel right now. Print their timeout.
const accepterCooldownEnd = accepterStats.lastLoss.getTime() + DUEL_COOLDOWN
if (accepterCooldownEnd > Date.now()) {
return ephemeralButtonFollowup(collectionInteraction, {
content: `${accepter}, you have recently lost a duel. You can duel again <t:${Math.floor(accepterCooldownEnd / 1000)}:R>.`,
})
}
if (!this.inProgress) {
// This case is not really supposed to happen because you should not be able to accept a duel after it has expired
// We are handling this anyways
await ephemeralButtonFollowup(collectionInteraction, {
content: `Someone beat you to the challenge! (or the duel expired... who knows!). You may issue a new challenge with ${inlineCode('/duel')}.`,
})
// Disable the button
const button = this.createButton(true)
const row = new ActionRowBuilder<MessageActionRowComponentBuilder>().addComponents(button)
return collectionInteraction.editReply({
components: [row],
})
}
// Set the Duel global CD
// todo MultiGuild: This shouldn't be hardcoded
if (guildId && interaction.channelId !== '340275382093611011') {
await this.client.guildOptions.update({
where: { guildId: guildId },
data: { lastDuel: new Date() },
})
}
// Disable duel
this.inProgress = false
// Disable the timeout that will change the message
if (this.timeout) {
clearTimeout(this.timeout)
}
// Disable the button
const button = this.createButton(true)
const row = new ActionRowBuilder<MessageActionRowComponentBuilder>().addComponents(button)
await collectionInteraction.editReply({
components: [row],
})
// Get and announce the winner
const accepterScore = this.getRandomScore()
const challengerScore = this.getRandomScore()
let winnerText = ''
if (challengerScore > accepterScore) {
await this.updateUserScore(challengerStats.duelStats[0], 'win')
await this.updateUserScore(accepterStats.duelStats[0], 'loss')
const [guild, member] = getGuildAndCallerFromCommand(collectionInteraction)
await ColorRoles.setColor('#FFFFFF', member, guild)
winnerText = `${challenger} has won!`
} else if (accepterScore > challengerScore) {
await this.updateUserScore(challengerStats.duelStats[0], 'loss')
await this.updateUserScore(accepterStats.duelStats[0], 'win')
const [guild, member] = getGuildAndCallerFromCommand(interaction)
await ColorRoles.setColor('#FFFFFF', member, guild)
winnerText = `${accepter} has won!`
} else {
await this.updateUserScore(challengerStats.duelStats[0], 'draw')
await this.updateUserScore(accepterStats.duelStats[0], 'draw')
const challengerMember = getCallerFromCommand(interaction)
const accepterMember = getCallerFromCommand(collectionInteraction)
challengerMember?.timeout(DRAW_TIMEOUT_DURATION, 'Tied a duel!')
accepterMember?.timeout(DRAW_TIMEOUT_DURATION, 'Tied a duel!')
winnerText = "It's a draw! Now go sit in a corner for 10 minutes and think about your actions..."
}
await collectionInteraction.editReply({
content: `${wagerMsg}${accepter} has rolled a ${accepterScore} and ${challenger} has rolled a ${challengerScore}. ${winnerText}`,
})
})
}
@Slash({ name: 'stats', description: 'Display your duel statistics' })
private async duelStats(interaction: CommandInteraction) {
await interaction.deferReply()
// TODO: Once/If we implement seasons this will need to change from findFirst
const user = interaction.user
const stats = await this.client.duels.findFirst({
where: {
userId: user.id,
},
})
const member = interaction.member
if (stats && member instanceof GuildMember) {
const { wins, winStreak, winStreakMax, losses, lossStreak, lossStreakMax, draws } = stats
let currentStreak = 'Current streak: '
if (winStreak > 0) {
// User is currently on a win streak
currentStreak += `**${winStreak} ${this.plural(winStreak, 'win')}**`
} else if (lossStreak > 0) {
// User is currently on a loss streak
currentStreak += `**${lossStreak} ${this.plural(lossStreak, 'loss')}**`
} else if (draws > 0) {
// User's last duel was a draw which reset both streaks
currentStreak = 'Your last duel was a draw'
} else {
// User has never dueled
currentStreak = 'You have never dueled before'
}
const bestStreak = `Best streak: **${winStreakMax} ${this.plural(winStreakMax, 'win')}**`
const worstStreak = `Worst streak: **${lossStreakMax} ${this.plural(lossStreakMax, 'loss')}**`
const statsEmbed = new EmbedBuilder()
// Color is either the user or Firynth's
.setColor(member?.displayHexColor ?? '#77618F')
.setAuthor({
iconURL: member.user.avatarURL() ?? '',
name: `${member.nickname ?? member.user.username}'s scoresheet: ${wins}-${losses}-${draws}`,
})
.setDescription([currentStreak, bestStreak, worstStreak].join('\n'))
await interaction.followUp({ embeds: [statsEmbed] })
} else {
await interaction.followUp(`${user}, you have never duelled before.`)
}
}
@Slash({ name: 'streaks', description: 'Show the overall duel statistics' })
private async streaks(interaction: CommandInteraction) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const streakStats = ['winStreakMax', 'lossStreakMax', 'draws', 'losses', 'wins'] as const
const statFormatter = async (statName: (typeof streakStats)[number], emptyText: string): Promise<string> => {
let stats = await this.client.$queryRawUnsafe<Duels[]>(
`SELECT * FROM Duels WHERE ${statName}=(SELECT MAX(${statName}) FROM Duels) AND ${statName} > 0`
)
if (stats.length == 0) {
return emptyText
}
let extraMessage = ''
if (stats.length > 2) {
// If more than 2 users share the same stat, shuffle the array and only print the first two.
// The rest will be listed as n other users
extraMessage = `, and ${stats.length - 2} other user${stats.length - 2 > 1 ? 's' : ''}`
stats = shuffleArray(stats).slice(0, 2)
}
const statHavers = await Promise.all(
stats.map(async (duel) => {
const member = await interaction.guild?.members.fetch(duel.userId)
return member?.nickname ?? member?.user?.username ?? ''
})
)
return `${stats[0][statName]} by ${statHavers.join(', ')}${extraMessage}`
}
const statsEmbed = new EmbedBuilder()
.setColor('#9932CC')
.setTitle('Duel streaks and stats')
.addFields(
{
name: 'Highest win streak',
value: await statFormatter('winStreakMax', 'Somehow, nobody has won a duel yet.'),
},
{
name: 'Highest loss streak',
value: await statFormatter('lossStreakMax', 'Somehow, nobody has lost a duel yet.'),
},
{
name: 'Highest # of draws',
value: await statFormatter('draws', 'Nobody has had a draw yet, good for them.'),
},
{ name: 'Highest # of wins', value: await statFormatter('wins', 'Somehow, nobody has won a duel yet.') },
{ name: 'Highest # of losses', value: await statFormatter('losses', 'Somehow, nobody has lost a duel yet.') }
)
await interaction.reply({ embeds: [statsEmbed] })
}
plural(streak: number, outcome: 'win' | 'loss'): string {
if (outcome === 'win') {
return streak === 1 ? 'win' : 'wins'
} else {
return streak === 1 ? 'loss' : 'losses'
}
}
private async updateUserScore(stats: Duels, outcome: 'win' | 'loss' | 'draw') {
switch (outcome) {
case 'draw': {
await this.client.duels.update({
where: {
id: stats.id,
},
data: {
draws: { increment: 1 },
lossStreak: 0,
winStreak: 0,
},
})
break
}
case 'win': {
await this.client.duels.update({
where: {
id: stats.id,
},
data: {
wins: { increment: 1 },
lossStreak: 0,
winStreak: { increment: 1 },
// Increment win streak if it's bigger than the current one
winStreakMax: stats.winStreak + 1 > stats.winStreakMax ? stats.winStreakMax + 1 : stats.winStreakMax,
},
})
break
}
default: {
// loss
await this.client.duels.update({
where: {
id: stats.id,
},
data: {
losses: { increment: 1 },
winStreak: 0,
lossStreak: { increment: 1 },
// Increment losss streak if it's bigger than the current one
lossStreakMax: stats.lossStreak + 1 > stats.lossStreakMax ? stats.lossStreakMax + 1 : stats.lossStreakMax,
user: {
update: {
lastLoss: new Date(),
},
},
},
})
}
}
}
private getRandomScore(): number {
return Math.floor(Math.random() * 101)
}
private createButton(disabled: boolean): ButtonBuilder {
let button = new ButtonBuilder().setEmoji('🎲').setStyle(ButtonStyle.Primary).setCustomId('duel-btn')
if (disabled) {
button = button.setLabel("It's over").setDisabled(true)
} else {
button = button.setLabel('Accept duel')
}
return button
}
private async getUserWithDuelStats(userId: string) {
// I'm not sure if we can do conditionals to check if no duelStats exist, so I went the verbose route...
return this.client.user
.upsert({
where: {
id: userId,
},
create: {
id: userId,
duelStats: {
create: [{}],
},
},
update: {},
include: {
duelStats: true,
},
})
.then(async (user) => {
if (user.duelStats.length === 0) {
return this.client.user.update({
where: {
id: user.id,
},
data: {
duelStats: {
create: [{}],
},
},
include: {
duelStats: true,
},
})
} else {
return user
}
})
}
}