Skip to content

Commit 035e8ec

Browse files
committed
Adding try catch to two player match voting
1 parent 1685978 commit 035e8ec

File tree

2 files changed

+169
-149
lines changed

2 files changed

+169
-149
lines changed

src/events/interactionCreate.ts

Lines changed: 64 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -194,76 +194,80 @@ export default {
194194
}
195195
}
196196

197-
await handleTwoPlayerMatchVoting(interaction, {
198-
participants: matchUsersArray,
199-
onComplete: async (interaction, winner) => {
200-
const customSelId = interaction.values[0]
201-
const matchDataParts: string[] = customSelId.split('_')
202-
const matchId = parseInt(matchDataParts[1])
203-
204-
// Check if this match is Best of 3 or 5
205-
const matchDataObj = await getMatchData(matchId)
206-
const isBo3 = matchDataObj.best_of_3
207-
const isBo5 = matchDataObj.best_of_5
208-
209-
if (!isBo3 && !isBo5) {
210-
await setWinningTeam(matchId, winner)
211-
await endMatch(matchId)
212-
return
213-
} else {
214-
const embed = interaction.message.embeds[0]
215-
const fields = embed.data.fields || []
197+
try {
198+
await handleTwoPlayerMatchVoting(interaction, {
199+
participants: matchUsersArray,
200+
onComplete: async (interaction, winner) => {
201+
const customSelId = interaction.values[0]
202+
const matchDataParts: string[] = customSelId.split('_')
203+
const matchId = parseInt(matchDataParts[1])
204+
205+
// Check if this match is Best of 3 or 5
206+
const matchDataObj = await getMatchData(matchId)
207+
const isBo3 = matchDataObj.best_of_3
208+
const isBo5 = matchDataObj.best_of_5
209+
210+
if (!isBo3 && !isBo5) {
211+
await setWinningTeam(matchId, winner)
212+
await endMatch(matchId)
213+
return
214+
} else {
215+
const embed = interaction.message.embeds[0]
216+
const fields = embed.data.fields || []
216217

217-
// Update Best of scores in the embed (for display only)
218-
const winnerIndex = winner === 1 ? 0 : 1
219-
for (let i = 0; i < Math.min(2, fields.length); i++) {
220-
const val = fields[i].value || ''
221-
const lines = val.split('\n')
218+
// Update Best of scores in the embed (for display only)
219+
const winnerIndex = winner === 1 ? 0 : 1
220+
for (let i = 0; i < Math.min(2, fields.length); i++) {
221+
const val = fields[i].value || ''
222+
const lines = val.split('\n')
223+
224+
const cleaned = lines.filter(
225+
(l) => !l.includes('Win Votes') && !l.includes('<@'),
226+
)
222227

223-
const cleaned = lines.filter(
224-
(l) => !l.includes('Win Votes') && !l.includes('<@'),
225-
)
228+
const mmrIdx = cleaned.findIndex((l) => l.includes('MMR'))
229+
if (mmrIdx !== -1) {
230+
const mmrLine = cleaned[mmrIdx]
231+
const m = mmrLine.match(/Score:\s*(\d+)/i)
232+
let score = m ? parseInt(m[1], 10) || 0 : 0
226233

227-
const mmrIdx = cleaned.findIndex((l) => l.includes('MMR'))
228-
if (mmrIdx !== -1) {
229-
const mmrLine = cleaned[mmrIdx]
230-
const m = mmrLine.match(/Score:\s*(\d+)/i)
231-
let score = m ? parseInt(m[1], 10) || 0 : 0
234+
if (i === winnerIndex) score += 1
232235

233-
if (i === winnerIndex) score += 1
236+
cleaned[mmrIdx] =
237+
mmrLine.replace(/\s*-?\s*Score:\s*\d+/i, '').trimEnd() +
238+
` - Score: ${score}`
239+
}
234240

235-
cleaned[mmrIdx] =
236-
mmrLine.replace(/\s*-?\s*Score:\s*\d+/i, '').trimEnd() +
237-
` - Score: ${score}`
241+
fields[i].value = cleaned.join('\n')
238242
}
239243

240-
fields[i].value = cleaned.join('\n')
241-
}
244+
// Get updated scores from the embed (after incrementing)
245+
let scores = getBestOfMatchScores(fields)
246+
let requiredWins = isBo5 ? 3 : isBo3 ? 2 : 1
247+
const [team1Wins, team2Wins] = scores
248+
249+
// Check if a team has won the Best of series
250+
let winningTeam = 0
251+
if (team1Wins >= requiredWins) {
252+
winningTeam = 1
253+
} else if (team2Wins >= requiredWins) {
254+
winningTeam = 2
255+
}
242256

243-
// Get updated scores from the embed (after incrementing)
244-
let scores = getBestOfMatchScores(fields)
245-
let requiredWins = isBo5 ? 3 : isBo3 ? 2 : 1
246-
const [team1Wins, team2Wins] = scores
247-
248-
// Check if a team has won the Best of series
249-
let winningTeam = 0
250-
if (team1Wins >= requiredWins) {
251-
winningTeam = 1
252-
} else if (team2Wins >= requiredWins) {
253-
winningTeam = 2
254-
}
257+
if (winningTeam) {
258+
await setWinningTeam(matchId, winningTeam)
259+
await endMatch(matchId)
260+
return
261+
}
255262

256-
if (winningTeam) {
257-
await setWinningTeam(matchId, winningTeam)
258-
await endMatch(matchId)
259-
return
263+
interaction.message.embeds[0] = embed
264+
await interaction.update({ embeds: interaction.message.embeds })
260265
}
261-
262-
interaction.message.embeds[0] = embed
263-
await interaction.update({ embeds: interaction.message.embeds })
264-
}
265-
},
266-
})
266+
},
267+
})
268+
} catch (err) {
269+
console.error(err)
270+
}
267271
}
268272

269273
if (interaction.customId.startsWith('deck-bans-')) {

src/utils/voteHelpers.ts

Lines changed: 105 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -236,108 +236,124 @@ export async function handleTwoPlayerMatchVoting(
236236
) => {},
237237
},
238238
) {
239-
const embed = interaction.message.embeds[0]
240-
if (!embed) return console.error('No embed found in message')
241-
const fields = embed.data.fields
242-
if (!fields) return console.error('No fields found in embed')
243-
244-
const winMatchData: string[] = interaction.values[0].split('_')
245-
const winMatchTeamId = parseInt(winMatchData[2])
246-
const matchId = await getMatchIdFromMessage(interaction)
247-
if (!matchId) return console.error('No match found for this channel')
248-
249-
// Restrict to allowed voters
250-
if (participants.length && !participants.includes(interaction.user.id)) {
251-
return interaction.reply({
252-
content: `You are not allowed to vote in this poll.`,
253-
flags: MessageFlags.Ephemeral,
254-
})
255-
}
256-
257-
// Get current user vote from database
258-
const currentVote = await getUserVote(matchId, interaction.user.id)
259-
260-
// Check if user already voted for this team
261-
const userAlreadyVotedForThisTeam =
262-
currentVote &&
263-
currentVote.vote_type === 'win' &&
264-
currentVote.vote_value === winMatchTeamId
265-
266-
// If user already voted for this team, remove the vote
267-
if (userAlreadyVotedForThisTeam) {
268-
await removeUserVote(matchId, interaction.user.id)
269-
} else {
270-
// Otherwise, update their vote (this will replace any existing vote)
271-
await setUserVote(matchId, interaction.user.id, 'win', winMatchTeamId)
272-
}
273-
274-
// Get updated votes from database grouped by team
275-
const votesByTeam = await getVotesForMatchByTeam(matchId, 'win')
276-
277-
// Update the embed for display
278-
const voteArray: { team_id: number; votes: string[] }[] = []
279-
for (let i = 0; i < fields.length; i++) {
280-
if (
281-
fields[i].name.includes('Cancel Match') ||
282-
fields[i].name.includes('Votes')
283-
)
284-
continue
239+
try {
240+
const embed = interaction.message.embeds[0]
241+
if (!embed) return console.error('No embed found in message')
242+
const fields = embed.data.fields
243+
if (!fields) return console.error('No fields found in embed')
244+
245+
const winMatchData: string[] = interaction.values[0].split('_')
246+
const winMatchTeamId = parseInt(winMatchData[2])
247+
const matchId = await getMatchIdFromMessage(interaction)
248+
if (!matchId) return console.error('No match found for this channel')
249+
250+
// Restrict to allowed voters
251+
if (participants.length && !participants.includes(interaction.user.id)) {
252+
return interaction.reply({
253+
content: `You are not allowed to vote in this poll.`,
254+
flags: MessageFlags.Ephemeral,
255+
})
256+
}
285257

286-
const lines = fields[i].value?.split('\n') || []
287-
const mmrLine = lines.find((l) => l.includes('MMR')) || ''
258+
// Get current user vote from database
259+
const currentVote = await getUserVote(matchId, interaction.user.id)
260+
261+
// Check if user already voted for this team
262+
const userAlreadyVotedForThisTeam =
263+
currentVote &&
264+
currentVote.vote_type === 'win' &&
265+
currentVote.vote_value === winMatchTeamId
266+
267+
// If user already voted for this team, remove the vote
268+
if (userAlreadyVotedForThisTeam) {
269+
await removeUserVote(matchId, interaction.user.id)
270+
} else {
271+
// Otherwise, update their vote (this will replace any existing vote)
272+
await setUserVote(matchId, interaction.user.id, 'win', winMatchTeamId)
273+
}
288274

289-
// Get votes for this team from database (teams start at 1, array index starts at 0)
290-
const teamId = i + 1
291-
const teamVotes = votesByTeam.get(teamId) || []
292-
const voteLines = teamVotes.map((uid) => `<@${uid}>`)
275+
// Get updated votes from database grouped by team
276+
const votesByTeam = await getVotesForMatchByTeam(matchId, 'win')
277+
278+
// Update the embed for display
279+
const voteArray: { team_id: number; votes: string[] }[] = []
280+
for (let i = 0; i < fields.length; i++) {
281+
if (
282+
fields[i].name.includes('Cancel Match') ||
283+
fields[i].name.includes('Votes')
284+
)
285+
continue
286+
287+
const lines = fields[i].value?.split('\n') || []
288+
const mmrLine = lines.find((l) => l.includes('MMR')) || ''
289+
290+
// Get votes for this team from database (teams start at 1, array index starts at 0)
291+
const teamId = i + 1
292+
const teamVotes = votesByTeam.get(teamId) || []
293+
const voteLines = teamVotes.map((uid) => `<@${uid}>`)
294+
295+
let newValue = mmrLine
296+
if (voteLines.length > 0) {
297+
newValue += `\nWin Votes`
298+
newValue += '\n' + voteLines.join('\n')
299+
}
293300

294-
let newValue = mmrLine
295-
if (voteLines.length > 0) {
296-
newValue += `\nWin Votes`
297-
newValue += '\n' + voteLines.join('\n')
301+
fields[i].value = newValue || '\u200b'
302+
voteArray.push({ team_id: i, votes: voteLines })
298303
}
299304

300-
fields[i].value = newValue || '\u200b'
301-
voteArray.push({ team_id: i, votes: voteLines })
302-
}
303-
304-
interaction.message.embeds[0] = embed
305+
interaction.message.embeds[0] = embed
305306

306-
// Check if all participants voted
307-
const totalVotes = voteArray.reduce((sum, team) => sum + team.votes.length, 0)
308-
const allVoted = participants.length > 0 && totalVotes === participants.length
309-
310-
if (allVoted) {
311-
// Check majority
312-
const majority = Math.floor(participants.length / 2) + 1
313-
let winner: number | undefined
314-
for (let i = 0; i < voteArray.length; i++) {
315-
if (voteArray[i].votes.length >= majority) {
316-
winner = i + 1 // Teams start at 1
307+
// Check if all participants voted
308+
const totalVotes = voteArray.reduce(
309+
(sum, team) => sum + team.votes.length,
310+
0,
311+
)
312+
const allVoted =
313+
participants.length > 0 && totalVotes === participants.length
314+
315+
if (allVoted) {
316+
// Check majority
317+
const majority = Math.floor(participants.length / 2) + 1
318+
let winner: number | undefined
319+
for (let i = 0; i < voteArray.length; i++) {
320+
if (voteArray[i].votes.length >= majority) {
321+
winner = i + 1 // Teams start at 1
322+
}
317323
}
318-
}
319324

320-
if (winner) {
321-
await onComplete(interaction, winner)
322-
return
325+
if (winner) {
326+
await onComplete(interaction, winner)
327+
return
328+
}
323329
}
324-
}
325330

326-
// Acknowledge the interaction first
327-
await interaction.deferUpdate()
331+
// Acknowledge the interaction first
332+
await interaction.deferUpdate()
328333

329-
// Delete the old message and send a new one
330-
const channel = interaction.channel as GuildChannel
331-
const components = interaction.message.components
332-
await interaction.message.delete()
334+
// Delete the old message and send a new one
335+
const channel = interaction.channel as GuildChannel
336+
const components = interaction.message.components
337+
await interaction.message.delete()
333338

334-
if (channel && channel.isTextBased()) {
335-
const newMessage = await channel.send({
336-
embeds: [embed],
337-
components: components,
338-
})
339+
if (channel && channel.isTextBased()) {
340+
const newMessage = await channel.send({
341+
embeds: [embed],
342+
components: components,
343+
})
339344

340-
setLastWinVoteMessage(channel.id, newMessage.id)
345+
setLastWinVoteMessage(channel.id, newMessage.id)
346+
}
347+
} catch (err) {
348+
const channel = interaction.channel as GuildChannel
349+
if (channel && channel.isTextBased()) {
350+
channel.send(
351+
'Failed to handle voting. Please ping Jeff or Cas about this. Error: ' +
352+
err,
353+
)
354+
} else {
355+
console.error('Failed to handle voting. Error: ' + err)
356+
}
341357
}
342358
}
343359

0 commit comments

Comments
 (0)