1
0
Fork 0
polaris-task-force/src/bot/index.ts
Z8MB1E c4cbe43c4f 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.
2026-11-03 12:50:29 -05:00

141 lines
5.2 KiB
TypeScript

import { Client, Events, GatewayIntentBits } from "discord.js";
import { getPayload } from "payload";
import config from "@payload-config";
import { botConfig } from "./config";
import { commands } from "./commands";
import { handleAnnounceModal } from "./commands/announce";
import { handleChangelogEditModal } from "./commands/changelog";
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 });
const client = new Client({
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<void> => {
if (shuttingDown) {
payload.logger.warn(`[Bot] ${signal} received again, forcing exit`);
process.exit(143);
}
shuttingDown = true;
payload.logger.info(`[Bot] ${signal} received, shutting down gracefully`);
try {
if (client.isReady()) {
await client.destroy();
}
payload.logger.info("[Bot] Discord client destroyed");
process.exit(0);
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
payload.logger.error(`[Bot] Error during shutdown: ${message}`);
process.exit(1);
}
};
process.on("SIGTERM", () => void shutdown("SIGTERM"));
process.on("SIGINT", () => void shutdown("SIGINT"));
const commandExecutors = new Map(
commands.map((command) => [command.builder.name, command.execute]),
);
client.once(Events.ClientReady, async (readyClient) => {
payload.logger.info(`[Bot] Logged in as ${readyClient.user.tag}`);
const globalCommands = commands.filter((command) => command.scope === "global");
const guildCommands = commands.filter((command) => command.scope !== "global");
// Guild-scoped commands are never exposed in DMs — /signup and /link must
// be global so they actually appear (and run) in a DM with the bot.
if (globalCommands.length > 0) {
await readyClient.application.commands.set(
globalCommands.map((command) => command.builder.toJSON()),
);
}
if (guildCommands.length > 0) {
await readyClient.application.commands.set(
guildCommands.map((command) => command.builder.toJSON()),
botConfig.guildId,
);
}
payload.logger.info(
`[Bot] Registered ${globalCommands.length} global and ${guildCommands.length} guild command(s)`,
);
for (const start of services) {
await start(readyClient, payload);
}
});
client.on(Events.InteractionCreate, async (interaction) => {
if (interaction.isButton() && interaction.customId.startsWith("ptf-att:")) {
await handleButtonInteraction(interaction, payload);
return;
}
if (
(interaction.isButton() || interaction.isModalSubmit()) &&
interaction.customId.startsWith("ptf-xfer:")
) {
await handleTransferInteraction(interaction, payload);
return;
}
if (interaction.isModalSubmit() && interaction.customId.startsWith("ptf-announce:")) {
await handleAnnounceModal(interaction, payload);
return;
}
if (interaction.isModalSubmit() && interaction.customId.startsWith("ptf-changelog-edit:")) {
await handleChangelogEditModal(interaction, payload);
return;
}
if (interaction.isModalSubmit() && interaction.customId.startsWith("ptf-rp-edit")) {
await handlePresenceModal(interaction, payload);
return;
}
if (!interaction.isChatInputCommand()) {
return;
}
const execute = commandExecutors.get(interaction.commandName);
if (!execute) {
return;
}
try {
await execute(interaction, payload);
} catch (error) {
payload.logger.error(
`[Bot] Error executing /${interaction.commandName}: ${errorMessageOf(error)}`,
);
if (!interaction.replied && !interaction.deferred) {
await safeEphemeralReply(
interaction,
payload,
"Something went wrong while running this command.",
);
}
}
});
await client.login(botConfig.token);
};
main().catch((error) => {
const message = error instanceof Error ? error.message : "Unknown error";
console.error(`[Bot] Failed to start: ${message}`);
process.exit(1);
});