diff --git a/src/bot/commands/debug.ts b/src/bot/commands/debug.ts index 0b38e92a..a2dbde7a 100644 --- a/src/bot/commands/debug.ts +++ b/src/bot/commands/debug.ts @@ -171,9 +171,7 @@ const runDelete = async ( const runList = (): string => debugActions .map((action) => { - const modes = ["preview", action.live ? "live" : null, "sandbox"] - .filter(Boolean) - .join(", "); + const modes = ["preview", action.live ? "live" : null, "sandbox"].filter(Boolean).join(", "); return `**${action.name}**: ${action.description}\n target: ${action.targetHint}\n modes: ${modes}`; }) .join("\n\n"); @@ -188,9 +186,7 @@ export const debugCommand: BotCommand = { builder: new SlashCommandBuilder() .setName("debug") .setDescription("Preview, sandbox, or live-repost bot messages (staff only)") - .addSubcommand((sub) => - sub.setName("list").setDescription("List the debuggable bot actions"), - ) + .addSubcommand((sub) => sub.setName("list").setDescription("List the debuggable bot actions")) .addSubcommand((sub) => sub .setName("run") @@ -221,10 +217,7 @@ export const debugCommand: BotCommand = { option .setName("method") .setDescription("Live roll-call only: edit the existing message, or repost a fresh one") - .addChoices( - { name: "edit", value: "edit" }, - { name: "repost", value: "repost" }, - ), + .addChoices({ name: "edit", value: "edit" }, { name: "repost", value: "repost" }), ), ) .addSubcommand((sub) => @@ -262,22 +255,22 @@ export const debugCommand: BotCommand = { return; } + // Ack before the member fetch + permission check so a slow Discord REST + // call cannot expire the interaction (see /rollcall). + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const member = await interaction.guild.members.fetch(interaction.user.id); if (!(await isStaff(member, payload))) { - await interaction.reply({ - content: "You don't have permission to use debug.", - flags: MessageFlags.Ephemeral, - }); + await interaction.editReply("You don't have permission to use debug."); return; } const subcommand = interaction.options.getSubcommand(); if (subcommand === "list") { - await interaction.reply({ content: runList(), flags: MessageFlags.Ephemeral }); + await interaction.editReply({ content: runList() }); return; } - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const client = interaction.client as Client; const actionName = interaction.options.getString("action", true); const target = interaction.options.getString("target")?.trim() || undefined; @@ -300,9 +293,7 @@ export const debugCommand: BotCommand = { return; } const state = await action.inspect(payload, target); - await interaction.editReply( - "```json\n" + JSON.stringify(state, null, 2) + "\n```", - ); + await interaction.editReply("```json\n" + JSON.stringify(state, null, 2) + "\n```"); return; } diff --git a/src/bot/commands/remindEvaluations.ts b/src/bot/commands/remindEvaluations.ts index 8340a39f..1aaaa839 100644 --- a/src/bot/commands/remindEvaluations.ts +++ b/src/bot/commands/remindEvaluations.ts @@ -64,17 +64,16 @@ export const remindEvaluationsCommand: BotCommand = { return; } + // Ack before the member fetch + permission check so a slow Discord REST + // call cannot expire the interaction (see /rollcall). + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const member = await interaction.guild.members.fetch(interaction.user.id); if (!(await isStaff(member, payload))) { - await interaction.reply({ - content: "You don't have permission to trigger evaluation reminders.", - flags: MessageFlags.Ephemeral, - }); + await interaction.editReply("You don't have permission to trigger evaluation reminders."); return; } - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const client = interaction.client as Client; const missionInput = interaction.options.getString("mission")?.trim(); diff --git a/src/bot/commands/rollcall.ts b/src/bot/commands/rollcall.ts index 41576378..09c62328 100644 --- a/src/bot/commands/rollcall.ts +++ b/src/bot/commands/rollcall.ts @@ -31,17 +31,17 @@ export const rollCallCommand: BotCommand = { return; } + // Acknowledge before the member fetch and permission check: Discord drops an + // interaction that is not acked within 3 seconds, and deferring afterwards + // fails with "Unknown interaction" (10062) even for a legitimate caller. + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const member = await interaction.guild.members.fetch(interaction.user.id); if (!(await isStaff(member, payload))) { - await interaction.reply({ - content: "You don't have permission to trigger roll-calls.", - flags: MessageFlags.Ephemeral, - }); + await interaction.editReply("You don't have permission to trigger roll-calls."); return; } - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const client = interaction.client as Client; const missionInput = interaction.options.getString("mission")?.trim(); diff --git a/src/bot/events/interactionCreate.ts b/src/bot/events/interactionCreate.ts index f2da9f35..537f5c76 100644 --- a/src/bot/events/interactionCreate.ts +++ b/src/bot/events/interactionCreate.ts @@ -1,6 +1,7 @@ import { type ButtonInteraction, MessageFlags } from "discord.js"; import type { Payload } from "payload"; import { findUserByDiscordId } from "@/bot/lib/resolve"; +import { safeEphemeralReply } from "@/bot/lib/interactions"; import { attendanceHash, buildAttendanceRow, @@ -112,10 +113,11 @@ export const handleButtonInteraction = async ( `[Bot] RSVP interaction failed for mission #${missionId}: ${errorMessage(error)}`, ); if (!interaction.replied && !interaction.deferred) { - await interaction.reply({ - content: "Something went wrong while updating your attendance.", - flags: MessageFlags.Ephemeral, - }); + await safeEphemeralReply( + interaction, + payload, + "Something went wrong while updating your attendance.", + ); } } }; diff --git a/src/bot/events/transferInteractions.ts b/src/bot/events/transferInteractions.ts index d770181e..efb49912 100644 --- a/src/bot/events/transferInteractions.ts +++ b/src/bot/events/transferInteractions.ts @@ -43,8 +43,18 @@ const parseTransferInteraction = (customId: string): ParsedTransferInteraction | return { requestId, action }; }; -const replyEphemeral = (interaction: TransferInteraction, content: string): Promise => - interaction.reply({ content, flags: MessageFlags.Ephemeral }); +// Interaction replies fail with DiscordAPIError 10062 "Unknown interaction" once +// Discord has dropped the token (a stale button press, or a click that arrives +// after the 15 minute window). Never let that surface as an unhandled rejection: +// discord.js re-emits it on the client as an 'error' event. +const replyEphemeral = async (interaction: TransferInteraction, content: string): Promise => { + try { + await interaction.reply({ content, flags: MessageFlags.Ephemeral }); + } catch (error) { + const message = error instanceof Error ? error.message : "Unknown error"; + console.error(`[Bot] Could not deliver a transfer interaction reply: ${message}`); + } +}; const currentLeaderSide = async ( payload: Payload, @@ -102,16 +112,17 @@ const editOutcome = async ({ }: OutcomeEdit): Promise => { if (!interaction.message) return; const row = - outcome === "appealed" - ? appealRow(requestId, true) - : transferDecisionRow(requestId, true); + outcome === "appealed" ? appealRow(requestId, true) : transferDecisionRow(requestId, true); await interaction.message.edit({ embeds: [decisionOutcomeEmbed(outcome, status, reason)], components: [row], }); }; -const showRejectModal = async (interaction: ButtonInteraction, requestId: number): Promise => { +const showRejectModal = async ( + interaction: ButtonInteraction, + requestId: number, +): Promise => { const reason = new TextInputBuilder() .setCustomId(REJECTION_REASON_ID) .setStyle(TextInputStyle.Paragraph) diff --git a/src/bot/index.ts b/src/bot/index.ts index f7e54ed8..655e41a8 100644 --- a/src/bot/index.ts +++ b/src/bot/index.ts @@ -1,4 +1,4 @@ -import { Client, Events, GatewayIntentBits, MessageFlags } from "discord.js"; +import { Client, Events, GatewayIntentBits } from "discord.js"; import { getPayload } from "payload"; import config from "@payload-config"; import { botConfig } from "./config"; @@ -9,9 +9,13 @@ import { handlePresenceModal } from "./commands/discordPresence"; import { services } from "./services"; import { handleButtonInteraction } from "./events/interactionCreate"; import { handleTransferInteraction } from "./events/transferInteractions"; +import { safeEphemeralReply } from "./lib/interactions"; // Usage: `bun run bot`. Standalone long-running process; connects to Discord // and shares the Postgres database with the web app via the Payload config. +const errorMessageOf = (error: unknown): string => + error instanceof Error ? error.message : "Unknown error"; + const main = async () => { const payload = await getPayload({ config }); @@ -19,6 +23,15 @@ const main = async () => { intents: [GatewayIntentBits.Guilds], }); + // discord.js emits 'error' on the client whenever an event listener rejects + // (interactions, gateway hiccups, REST failures). Node's default for an + // unhandled 'error' event is to throw, which took the whole process down: a + // single stale interaction (DiscordAPIError 10062 "Unknown interaction") + // killed the bot for a minute. Log and keep running instead. + client.on(Events.Error, (error) => { + payload.logger.error(`[Bot] Discord client error: ${errorMessageOf(error)}`); + }); + let shuttingDown = false; const shutdown = async (signal: NodeJS.Signals): Promise => { if (shuttingDown) { @@ -105,13 +118,15 @@ const main = async () => { try { await execute(interaction, payload); } catch (error) { - const message = error instanceof Error ? error.message : "Unknown error"; - payload.logger.error(`[Bot] Error executing /${interaction.commandName}: ${message}`); + payload.logger.error( + `[Bot] Error executing /${interaction.commandName}: ${errorMessageOf(error)}`, + ); if (!interaction.replied && !interaction.deferred) { - await interaction.reply({ - content: "Something went wrong while running this command.", - flags: MessageFlags.Ephemeral, - }); + await safeEphemeralReply( + interaction, + payload, + "Something went wrong while running this command.", + ); } } }); diff --git a/src/bot/lib/interactions.ts b/src/bot/lib/interactions.ts new file mode 100644 index 00000000..55e095e5 --- /dev/null +++ b/src/bot/lib/interactions.ts @@ -0,0 +1,32 @@ +import { MessageFlags, type RepliableInteraction } from "discord.js"; +import type { Payload } from "payload"; + +const errorMessage = (error: unknown): string => + error instanceof Error ? error.message : "Unknown error"; + +/** + * Reply ephemerally without ever letting the reply itself throw. + * + * Discord invalidates an interaction token once it has been answered (or once + * the 15-minute window closes), so a second reply - or any reply to an + * interaction Discord already dropped - fails with `DiscordAPIError: Unknown + * interaction` (10062). An unguarded reply inside a catch block turns that into + * an unhandled rejection which discord.js re-emits on the client, and the + * missing `client.on(Events.Error)` handler then killed the whole bot process. + * Error paths must never take the bot down with them, so this swallows (and + * logs) delivery failures. + */ +export const safeEphemeralReply = async ( + interaction: RepliableInteraction, + payload: Payload, + content: string, +): Promise => { + const label = interaction.isChatInputCommand() ? `/${interaction.commandName}` : "interaction"; + try { + await interaction.reply({ content, flags: MessageFlags.Ephemeral }); + } catch (error) { + payload.logger.error( + `[Bot] Could not deliver an ephemeral reply for ${label}: ${errorMessage(error)}`, + ); + } +}; diff --git a/tests/int/bot-commands.int.spec.ts b/tests/int/bot-commands.int.spec.ts index 12628455..eecb4a6a 100644 --- a/tests/int/bot-commands.int.spec.ts +++ b/tests/int/bot-commands.int.spec.ts @@ -39,16 +39,19 @@ describe("Bot slash command builders", () => { const { commands } = await import("@/bot/commands"); const registered = new Set(commands.map((c) => c.builder.name)); - const files = fs - .readdirSync(dir) - .filter((file) => file.endsWith(".ts") && file !== "index.ts"); + const files = fs.readdirSync(dir).filter((file) => file.endsWith(".ts") && file !== "index.ts"); expect(files.length).toBeGreaterThanOrEqual(7); for (const file of files) { const mod = (await import(path.join(dir, file))) as Record; for (const value of Object.values(mod)) { const candidate = value as { builder?: { name?: string }; execute?: unknown }; - if (candidate && typeof candidate === "object" && candidate.builder?.name && candidate.execute) { + if ( + candidate && + typeof candidate === "object" && + candidate.builder?.name && + candidate.execute + ) { expect( registered.has(candidate.builder.name), `/${candidate.builder.name} (${file}) is not in the commands registry`, @@ -58,3 +61,78 @@ describe("Bot slash command builders", () => { } }); }); + +/** + * A slash command has three seconds to acknowledge an interaction. Deferring + * after a member fetch and a permission check misses that window often enough + * that Discord drops the token: the command then fails with "This application + * did not respond" and any later reply throws DiscordAPIError 10062, + * "Unknown interaction". That unhandled rejection used to kill the bot process + * (see the 2026-11-03 /rollcall crash). + */ +describe("Bot interaction acknowledgement", () => { + process.env.DISCORD_TOKEN ||= "regression-test-token"; + process.env.DISCORD_GUILD_ID ||= "123456789012345678"; + + const fakePayload = { + logger: { error: () => undefined, info: () => undefined, warn: () => undefined }, + }; + + it("/rollcall defers before the member fetch and permission check", async () => { + const { rollCallCommand } = await import("@/bot/commands/rollcall"); + const calls: string[] = []; + const interaction = { + inGuild: () => true, + guild: { + members: { + fetch: async () => { + calls.push("members.fetch"); + throw new Error("Discord REST call timed out"); + }, + }, + }, + user: { id: "123456789012345678" }, + client: {}, + deferReply: async () => { + calls.push("deferReply"); + }, + editReply: async () => { + calls.push("editReply"); + }, + reply: async () => { + calls.push("reply"); + }, + options: { getString: () => null }, + }; + + await expect( + rollCallCommand.execute(interaction as never, fakePayload as never), + ).rejects.toThrow("Discord REST call timed out"); + + expect(calls[0]).toBe("deferReply"); + expect(calls).not.toContain("reply"); + }); + + it("safeEphemeralReply never rethrows a stale-interaction failure", async () => { + const { safeEphemeralReply } = await import("@/bot/lib/interactions"); + const logged: string[] = []; + const interaction = { + commandName: "rollcall", + isChatInputCommand: () => true, + reply: async () => { + throw new Error("Unknown interaction"); + }, + }; + + await expect( + safeEphemeralReply( + interaction as never, + { + logger: { error: (line: string) => logged.push(line) }, + } as never, + "Something went wrong while running this command.", + ), + ).resolves.toBeUndefined(); + expect(logged.join("\n")).toContain("Unknown interaction"); + }); +});