fix(bot): survive a stale Discord interaction instead of crashing
A manual /rollcall took the bot down: the command fetched the guild member and ran the staff check before acknowledging, missed Discord's 3 second ack window, then died on "Unknown interaction" when it tried to defer (and again when the error path tried to reply). discord.js re-emits a rejected event listener on the client as an 'error' event, and with no handler attached Node threw and exited the process. Ack first, protect the error paths: - /rollcall, /remind-evaluations and /debug defer immediately and report permission denials through editReply. - safeEphemeralReply (bot/lib/interactions.ts) never rethrows, and the RSVP and transfer handlers use the same guarded behaviour. - client.on(Events.Error) logs instead of exiting. The entrypoint restarts a dead bot after 5 seconds, so the previous symptom was a silent gap.
This commit is contained in:
parent
8fff9c3f92
commit
c4cbe43c4f
8 changed files with 180 additions and 52 deletions
|
|
@ -171,9 +171,7 @@ const runDelete = async (
|
||||||
const runList = (): string =>
|
const runList = (): string =>
|
||||||
debugActions
|
debugActions
|
||||||
.map((action) => {
|
.map((action) => {
|
||||||
const modes = ["preview", action.live ? "live" : null, "sandbox"]
|
const modes = ["preview", action.live ? "live" : null, "sandbox"].filter(Boolean).join(", ");
|
||||||
.filter(Boolean)
|
|
||||||
.join(", ");
|
|
||||||
return `**${action.name}**: ${action.description}\n target: ${action.targetHint}\n modes: ${modes}`;
|
return `**${action.name}**: ${action.description}\n target: ${action.targetHint}\n modes: ${modes}`;
|
||||||
})
|
})
|
||||||
.join("\n\n");
|
.join("\n\n");
|
||||||
|
|
@ -188,9 +186,7 @@ export const debugCommand: BotCommand = {
|
||||||
builder: new SlashCommandBuilder()
|
builder: new SlashCommandBuilder()
|
||||||
.setName("debug")
|
.setName("debug")
|
||||||
.setDescription("Preview, sandbox, or live-repost bot messages (staff only)")
|
.setDescription("Preview, sandbox, or live-repost bot messages (staff only)")
|
||||||
.addSubcommand((sub) =>
|
.addSubcommand((sub) => sub.setName("list").setDescription("List the debuggable bot actions"))
|
||||||
sub.setName("list").setDescription("List the debuggable bot actions"),
|
|
||||||
)
|
|
||||||
.addSubcommand((sub) =>
|
.addSubcommand((sub) =>
|
||||||
sub
|
sub
|
||||||
.setName("run")
|
.setName("run")
|
||||||
|
|
@ -221,10 +217,7 @@ export const debugCommand: BotCommand = {
|
||||||
option
|
option
|
||||||
.setName("method")
|
.setName("method")
|
||||||
.setDescription("Live roll-call only: edit the existing message, or repost a fresh one")
|
.setDescription("Live roll-call only: edit the existing message, or repost a fresh one")
|
||||||
.addChoices(
|
.addChoices({ name: "edit", value: "edit" }, { name: "repost", value: "repost" }),
|
||||||
{ name: "edit", value: "edit" },
|
|
||||||
{ name: "repost", value: "repost" },
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.addSubcommand((sub) =>
|
.addSubcommand((sub) =>
|
||||||
|
|
@ -262,22 +255,22 @@ export const debugCommand: BotCommand = {
|
||||||
return;
|
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);
|
const member = await interaction.guild.members.fetch(interaction.user.id);
|
||||||
if (!(await isStaff(member, payload))) {
|
if (!(await isStaff(member, payload))) {
|
||||||
await interaction.reply({
|
await interaction.editReply("You don't have permission to use debug.");
|
||||||
content: "You don't have permission to use debug.",
|
|
||||||
flags: MessageFlags.Ephemeral,
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const subcommand = interaction.options.getSubcommand();
|
const subcommand = interaction.options.getSubcommand();
|
||||||
if (subcommand === "list") {
|
if (subcommand === "list") {
|
||||||
await interaction.reply({ content: runList(), flags: MessageFlags.Ephemeral });
|
await interaction.editReply({ content: runList() });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
|
||||||
const client = interaction.client as Client;
|
const client = interaction.client as Client;
|
||||||
const actionName = interaction.options.getString("action", true);
|
const actionName = interaction.options.getString("action", true);
|
||||||
const target = interaction.options.getString("target")?.trim() || undefined;
|
const target = interaction.options.getString("target")?.trim() || undefined;
|
||||||
|
|
@ -300,9 +293,7 @@ export const debugCommand: BotCommand = {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const state = await action.inspect(payload, target);
|
const state = await action.inspect(payload, target);
|
||||||
await interaction.editReply(
|
await interaction.editReply("```json\n" + JSON.stringify(state, null, 2) + "\n```");
|
||||||
"```json\n" + JSON.stringify(state, null, 2) + "\n```",
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -64,17 +64,16 @@ export const remindEvaluationsCommand: BotCommand = {
|
||||||
return;
|
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);
|
const member = await interaction.guild.members.fetch(interaction.user.id);
|
||||||
if (!(await isStaff(member, payload))) {
|
if (!(await isStaff(member, payload))) {
|
||||||
await interaction.reply({
|
await interaction.editReply("You don't have permission to trigger evaluation reminders.");
|
||||||
content: "You don't have permission to trigger evaluation reminders.",
|
|
||||||
flags: MessageFlags.Ephemeral,
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
|
||||||
|
|
||||||
const client = interaction.client as Client;
|
const client = interaction.client as Client;
|
||||||
const missionInput = interaction.options.getString("mission")?.trim();
|
const missionInput = interaction.options.getString("mission")?.trim();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -31,17 +31,17 @@ export const rollCallCommand: BotCommand = {
|
||||||
return;
|
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);
|
const member = await interaction.guild.members.fetch(interaction.user.id);
|
||||||
if (!(await isStaff(member, payload))) {
|
if (!(await isStaff(member, payload))) {
|
||||||
await interaction.reply({
|
await interaction.editReply("You don't have permission to trigger roll-calls.");
|
||||||
content: "You don't have permission to trigger roll-calls.",
|
|
||||||
flags: MessageFlags.Ephemeral,
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
|
||||||
|
|
||||||
const client = interaction.client as Client;
|
const client = interaction.client as Client;
|
||||||
const missionInput = interaction.options.getString("mission")?.trim();
|
const missionInput = interaction.options.getString("mission")?.trim();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { type ButtonInteraction, MessageFlags } from "discord.js";
|
import { type ButtonInteraction, MessageFlags } from "discord.js";
|
||||||
import type { Payload } from "payload";
|
import type { Payload } from "payload";
|
||||||
import { findUserByDiscordId } from "@/bot/lib/resolve";
|
import { findUserByDiscordId } from "@/bot/lib/resolve";
|
||||||
|
import { safeEphemeralReply } from "@/bot/lib/interactions";
|
||||||
import {
|
import {
|
||||||
attendanceHash,
|
attendanceHash,
|
||||||
buildAttendanceRow,
|
buildAttendanceRow,
|
||||||
|
|
@ -112,10 +113,11 @@ export const handleButtonInteraction = async (
|
||||||
`[Bot] RSVP interaction failed for mission #${missionId}: ${errorMessage(error)}`,
|
`[Bot] RSVP interaction failed for mission #${missionId}: ${errorMessage(error)}`,
|
||||||
);
|
);
|
||||||
if (!interaction.replied && !interaction.deferred) {
|
if (!interaction.replied && !interaction.deferred) {
|
||||||
await interaction.reply({
|
await safeEphemeralReply(
|
||||||
content: "Something went wrong while updating your attendance.",
|
interaction,
|
||||||
flags: MessageFlags.Ephemeral,
|
payload,
|
||||||
});
|
"Something went wrong while updating your attendance.",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -43,8 +43,18 @@ const parseTransferInteraction = (customId: string): ParsedTransferInteraction |
|
||||||
return { requestId, action };
|
return { requestId, action };
|
||||||
};
|
};
|
||||||
|
|
||||||
const replyEphemeral = (interaction: TransferInteraction, content: string): Promise<unknown> =>
|
// Interaction replies fail with DiscordAPIError 10062 "Unknown interaction" once
|
||||||
interaction.reply({ content, flags: MessageFlags.Ephemeral });
|
// 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<void> => {
|
||||||
|
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 (
|
const currentLeaderSide = async (
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
|
|
@ -102,16 +112,17 @@ const editOutcome = async ({
|
||||||
}: OutcomeEdit): Promise<void> => {
|
}: OutcomeEdit): Promise<void> => {
|
||||||
if (!interaction.message) return;
|
if (!interaction.message) return;
|
||||||
const row =
|
const row =
|
||||||
outcome === "appealed"
|
outcome === "appealed" ? appealRow(requestId, true) : transferDecisionRow(requestId, true);
|
||||||
? appealRow(requestId, true)
|
|
||||||
: transferDecisionRow(requestId, true);
|
|
||||||
await interaction.message.edit({
|
await interaction.message.edit({
|
||||||
embeds: [decisionOutcomeEmbed(outcome, status, reason)],
|
embeds: [decisionOutcomeEmbed(outcome, status, reason)],
|
||||||
components: [row],
|
components: [row],
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const showRejectModal = async (interaction: ButtonInteraction, requestId: number): Promise<void> => {
|
const showRejectModal = async (
|
||||||
|
interaction: ButtonInteraction,
|
||||||
|
requestId: number,
|
||||||
|
): Promise<void> => {
|
||||||
const reason = new TextInputBuilder()
|
const reason = new TextInputBuilder()
|
||||||
.setCustomId(REJECTION_REASON_ID)
|
.setCustomId(REJECTION_REASON_ID)
|
||||||
.setStyle(TextInputStyle.Paragraph)
|
.setStyle(TextInputStyle.Paragraph)
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { Client, Events, GatewayIntentBits, MessageFlags } from "discord.js";
|
import { Client, Events, GatewayIntentBits } from "discord.js";
|
||||||
import { getPayload } from "payload";
|
import { getPayload } from "payload";
|
||||||
import config from "@payload-config";
|
import config from "@payload-config";
|
||||||
import { botConfig } from "./config";
|
import { botConfig } from "./config";
|
||||||
|
|
@ -9,9 +9,13 @@ import { handlePresenceModal } from "./commands/discordPresence";
|
||||||
import { services } from "./services";
|
import { services } from "./services";
|
||||||
import { handleButtonInteraction } from "./events/interactionCreate";
|
import { handleButtonInteraction } from "./events/interactionCreate";
|
||||||
import { handleTransferInteraction } from "./events/transferInteractions";
|
import { handleTransferInteraction } from "./events/transferInteractions";
|
||||||
|
import { safeEphemeralReply } from "./lib/interactions";
|
||||||
|
|
||||||
// Usage: `bun run bot`. Standalone long-running process; connects to Discord
|
// Usage: `bun run bot`. Standalone long-running process; connects to Discord
|
||||||
// and shares the Postgres database with the web app via the Payload config.
|
// 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 main = async () => {
|
||||||
const payload = await getPayload({ config });
|
const payload = await getPayload({ config });
|
||||||
|
|
||||||
|
|
@ -19,6 +23,15 @@ const main = async () => {
|
||||||
intents: [GatewayIntentBits.Guilds],
|
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;
|
let shuttingDown = false;
|
||||||
const shutdown = async (signal: NodeJS.Signals): Promise<void> => {
|
const shutdown = async (signal: NodeJS.Signals): Promise<void> => {
|
||||||
if (shuttingDown) {
|
if (shuttingDown) {
|
||||||
|
|
@ -105,13 +118,15 @@ const main = async () => {
|
||||||
try {
|
try {
|
||||||
await execute(interaction, payload);
|
await execute(interaction, payload);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : "Unknown error";
|
payload.logger.error(
|
||||||
payload.logger.error(`[Bot] Error executing /${interaction.commandName}: ${message}`);
|
`[Bot] Error executing /${interaction.commandName}: ${errorMessageOf(error)}`,
|
||||||
|
);
|
||||||
if (!interaction.replied && !interaction.deferred) {
|
if (!interaction.replied && !interaction.deferred) {
|
||||||
await interaction.reply({
|
await safeEphemeralReply(
|
||||||
content: "Something went wrong while running this command.",
|
interaction,
|
||||||
flags: MessageFlags.Ephemeral,
|
payload,
|
||||||
});
|
"Something went wrong while running this command.",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
|
||||||
32
src/bot/lib/interactions.ts
Normal file
32
src/bot/lib/interactions.ts
Normal file
|
|
@ -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<void> => {
|
||||||
|
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)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -39,16 +39,19 @@ describe("Bot slash command builders", () => {
|
||||||
const { commands } = await import("@/bot/commands");
|
const { commands } = await import("@/bot/commands");
|
||||||
const registered = new Set(commands.map((c) => c.builder.name));
|
const registered = new Set(commands.map((c) => c.builder.name));
|
||||||
|
|
||||||
const files = fs
|
const files = fs.readdirSync(dir).filter((file) => file.endsWith(".ts") && file !== "index.ts");
|
||||||
.readdirSync(dir)
|
|
||||||
.filter((file) => file.endsWith(".ts") && file !== "index.ts");
|
|
||||||
expect(files.length).toBeGreaterThanOrEqual(7);
|
expect(files.length).toBeGreaterThanOrEqual(7);
|
||||||
|
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
const mod = (await import(path.join(dir, file))) as Record<string, unknown>;
|
const mod = (await import(path.join(dir, file))) as Record<string, unknown>;
|
||||||
for (const value of Object.values(mod)) {
|
for (const value of Object.values(mod)) {
|
||||||
const candidate = value as { builder?: { name?: string }; execute?: unknown };
|
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(
|
expect(
|
||||||
registered.has(candidate.builder.name),
|
registered.has(candidate.builder.name),
|
||||||
`/${candidate.builder.name} (${file}) is not in the commands registry`,
|
`/${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");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue