Skip to content

Commit

Permalink
Merge branch 'develop' into preview
Browse files Browse the repository at this point in the history
  • Loading branch information
tuanddd committed Aug 21, 2023
2 parents 7365c09 + c37648f commit c343e51
Show file tree
Hide file tree
Showing 6 changed files with 238 additions and 102 deletions.
4 changes: 1 addition & 3 deletions src/adapters/mochi-guess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ class MochiGuess extends Fetcher {
thread_id: string
token_id?: string
}) {
body.bet_default_value ||= 1
// body.token_id ||= "61388b7c-5505-4fdf-8084-077422369a93"
body.token_id ||= "941f0fb1-00da-49dc-a538-5e81fc874cb4"
return await this.jsonFetch(`${MOCHI_GUESS_API_BASE_URL}/games`, {
Expand All @@ -45,7 +44,6 @@ class MochiGuess extends Fetcher {
{
method: "POST",
body: {
bet_amount: 1,
option_code,
player_id,
},
Expand All @@ -63,7 +61,7 @@ class MochiGuess extends Fetcher {
)
}

public async endGame(id: number, referee_id: string, option_code: string) {
public async endGame(id: string, referee_id: string, option_code: string) {
return await this.jsonFetch(
`${MOCHI_GUESS_API_BASE_URL}/games/${id}/result`,
{
Expand Down
15 changes: 2 additions & 13 deletions src/commands/guess/choice/slash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,6 @@ const slashCmd: SlashCommand = {
},
}

if (game.result || now() >= moment(game.end_at).unix() * 1000) {
return {
messageOptions: {
content: "Game already ended",
},
}
}

if (game.referee_id === i.user.id) {
return {
messageOptions: {
Expand All @@ -84,11 +76,8 @@ const slashCmd: SlashCommand = {

await mochiGuess.joinGame(game.id, i.user.id, optionCode)

const dmChannel = await i.user.createDM(true).catch(() => null)
i.editReply({
content: `A join request has been sent to your DM${
dmChannel ? `, <#${dmChannel.id}>` : ""
}`,
await i.editReply({
content: `A join request has been sent to you. Please check your inbox.`,
})
},
category: "Game",
Expand Down
165 changes: 128 additions & 37 deletions src/commands/guess/end/slash.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,120 @@
import { SlashCommandSubcommandBuilder } from "@discordjs/builders"
import { utils } from "@consolelabs/mochi-formatter"
import { SlashCommandSubcommandBuilder, userMention } from "@discordjs/builders"
import mochiGuess from "adapters/mochi-guess"
import { ThreadChannel } from "discord.js"
import { now, truncate } from "lodash"
import { ThreadChannel, MessageOptions, EmbedFieldData } from "discord.js"
import { now, truncate, groupBy } from "lodash"
import { logger } from "logger"
import moment from "moment-timezone"
import { SlashCommand } from "types/common"
import { capitalizeFirst, equalIgnoreCase } from "utils/common"
import { timeouts, timers } from ".."

import { composeEmbedMessage } from "ui/discord/embed"
import { SPACE } from "utils/constants"

export async function cleanupAfterEndGame(
thread: ThreadChannel,
gameCode: string
) {
try {
clearTimeout(timeouts.get(gameCode))
clearInterval(timers.get(gameCode))

await thread.setLocked(true, "game ended")
await thread.setArchived(true, "game ended")
} catch (e: any) {
logger.error(e)
logger.warn("Cannot cleanup after game end")
}
}

export async function announceResult(
thread: ThreadChannel,
answer: string,
gameResult: any
) {
const group = groupBy(gameResult, (r) => {
const isLoser = r.final_amount.split("").at(0) === "-"
return isLoser ? "losers" : "winners"
})
group.winners ??= []
group.losers ??= []
const embed = composeEmbedMessage(null, {
color: "GREEN",
})
embed.setTitle(":crossed_swords: Result")
embed.setDescription(
"The rewards you received include taxes and transaction fees. Please be aware when receiving rewards. Contact us if you have questions or concerns. Thank you! \nHere is the result:"
)

const winners =
group.winners.length === 0
? ["No one"]
: group.winners.map(
(t) =>
`> ${userMention(t.player_id)} +${t.final_amount} ${t.token_name}`
)

const losers =
group.losers.length === 0
? ["No one"]
: group.losers.map(
(t) =>
`> ${userMention(t.player_id)} ${t.final_amount} ${t.token_name}`
)

const embedFields: any[] = [
{
name: ":dart: Answer",
value: `> ${answer}\n`,
inline: false,
},
{
name: ":star_struck: Winners",
value: `${winners.join("\n")}\n`,
inline: false,
},
{
name: ":face_with_symbols_over_mouth: Losers",
value: `${losers.join("\n")}\n`,
inline: false,
},
]

embed.setFields(embedFields)

// const winnerEmbedFields = group.winners.map((t) => {
// const val = `${userMention(t.player_id)} +${utils.formatTokenDigit(
// t.final_amount
// )} ${t.token_name}\n`
// return {
// name: ":star_struck: Winners",
// value: val,
// inline: false,
// }
// })
//
// const loserEmbedFields = group.losers.map((t) => {
// const val = `${userMention(t.player_id)} -${utils.formatTokenDigit(
// t.final_amount.slice(1)
// )} ${t.token_name}\n`
//
// return {
// name: ":face_with_symbols_over_mouth: Losers",
// value: val,
// inline: false,
// }
// })
//
// embed.setFields(winnerEmbedFields, loserEmbedFields)

const msgOpt: MessageOptions = {
embeds: [embed],
}

await thread.send(msgOpt).catch(() => null)
}

const slashCmd: SlashCommand = {
name: "end",
prepare: () => {
Expand Down Expand Up @@ -111,43 +219,26 @@ const slashCmd: SlashCommand = {
}
}

const thread = (await i.client.channels.fetch(
game.thread_id
)) as ThreadChannel
const thread = (await i.client.channels
.fetch(game.thread_id)
.catch(() => null)) as ThreadChannel

await thread.send({
content: [`Time is up!`].join("\n"),
})

clearTimeout(timeouts.get(game.code))
clearInterval(timers.get(game.code))

await mochiGuess.endGame(game.code, i.user.id, optionCode)

const options = (game.options ?? []).map((opt: any) => {
const players = (opt.game_player ?? []).map(
(player: any) => `<@${player.player_id}>`
if (!thread) return
const gameResult = await mochiGuess
.endGame(code, i.user.id, optionCode)
.catch(() => null)
await i.deleteReply().catch(() => null)
if (gameResult?.data) {
await announceResult(
thread,
(game.options ?? []).find((opt: any) =>
equalIgnoreCase(optionCode, opt.code)
)?.option ?? "NA",
gameResult.data
)
return `${opt.option}: ${players.join(", ")}`
})

await thread.setArchived(true, "game ended").catch(() => null)
await thread.setLocked(true, "game ended").catch(() => null)

return {
messageOptions: {
content: [
`> ${game.question}`,
...options,
"",
`The answer is: ${
(game.options ?? []).find((opt: any) =>
equalIgnoreCase(optionCode, opt.code)
)?.option ?? "NA"
}`,
].join("\n"),
},
}

await cleanupAfterEndGame(thread, code)
},
category: "Game",
help: () => Promise.resolve({}),
Expand Down
Loading

0 comments on commit c343e51

Please sign in to comment.