Compare commits
No commits in common. "9f192a8159e5a3ee1030c124a90a7b5aa5d134e0" and "8fff9c3f924a2a53bd41afba35cf0dfa46cd24f1" have entirely different histories.
9f192a8159
...
8fff9c3f92
11 changed files with 53 additions and 202 deletions
|
|
@ -1,14 +1,5 @@
|
|||
# Changelog
|
||||
|
||||
# v0.15.1
|
||||
|
||||
### Fixes
|
||||
|
||||
- Roll-call buttons and Discord DMs no longer go quiet when a bot command fails.
|
||||
- Various bug fixes and improvements.
|
||||
|
||||
---
|
||||
|
||||
# v0.15.0
|
||||
|
||||
Mission detail is restyled as bordered dossier cards with classification strips, a new command-chain editor lets staff assign command hierarchy and drive command reviews, and faction chips become links with cover-image backgrounds.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "polaris-task-force",
|
||||
"version": "0.15.1",
|
||||
"version": "0.15.0",
|
||||
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
|
|
|||
|
|
@ -48,7 +48,6 @@ bot/
|
|||
|
||||
lib/
|
||||
debugActions.ts # /debug action registry: each action builds the production message and sends it live
|
||||
interactions.ts # safeEphemeralReply: error-path reply that never throws (stale interaction = 10062)
|
||||
roles.ts # isStaff check
|
||||
resolve.ts # discordId ↔ Payload user lookups
|
||||
transferMessaging.ts # Transfer embed builders + delivery keys
|
||||
|
|
@ -133,20 +132,9 @@ A poll loop (`services/discordPresence.ts`, `DISCORD_PRESENCE_POLL_MS`, default
|
|||
| Edit bot Rich Presence (command) | `bot/commands/discordPresence.ts` (+ Global `src/collections/discord/DiscordPresence.ts`) |
|
||||
| Rich Presence reconcile loop / mapping | `bot/services/discordPresence.ts` + `bot/lib/presence.ts` |
|
||||
|
||||
## Interaction reliability
|
||||
|
||||
Discord kills an interaction token that is not acknowledged within **3 seconds**: the user sees "The application did not respond", and every later reply (`deferReply` included) fails with `DiscordAPIError: Unknown interaction` (10062). Two rules follow, both enforced by `tests/int/bot-commands.int.spec.ts`:
|
||||
|
||||
1. **Ack first, then work.** Guild commands must `deferReply` as their first Discord call, before `guild.members.fetch()` and `isStaff()`. `/rollcall`, `/remind-evaluations`, and `/debug` defer up front and report permission denials through `editReply`. Commands that must open a modal (`/announce`, `/changelog edit=true`, `/discord-presence edit`) cannot defer, so their staff check runs before the modal and the modal is the very next call.
|
||||
2. **Error paths never reply unguarded.** A reply inside a `catch` throws whenever the interaction is already dead, and that rejection is what crashed the process on 2026-11-03. Use `safeEphemeralReply()` (`lib/interactions.ts`) or a local try/catch.
|
||||
|
||||
`client.on(Events.Error)` in `index.ts` is the last line of defence: discord.js re-emits any rejected event listener on the client, and without a handler Node throws and the whole bot exits (the entrypoint then restarts it after 5s, so the symptom is a silent gap, not a visible crash).
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- **NEVER** run bot and web app with separate database connections without connection pooling — they share PostgreSQL
|
||||
- **NEVER** register guild-only commands if the command needs to work in DMs (signup, link, ping must be global)
|
||||
- **NEVER** assume DM delivery succeeded — `/signup` uses ephemeral reply as primary delivery path
|
||||
- **NEVER** modify `discordId` directly in Payload admin — use the `/link` command or the resolve helper
|
||||
- **NEVER** fetch the guild member or run `isStaff` before `deferReply` on a guild command; that is a 3-second ack race and produces "The application did not respond"
|
||||
- **NEVER** `await interaction.reply(...)` directly inside a catch block; use `safeEphemeralReply` so a stale interaction (10062) cannot take the bot down
|
||||
|
|
|
|||
|
|
@ -171,7 +171,9 @@ 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");
|
||||
|
|
@ -186,7 +188,9 @@ 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")
|
||||
|
|
@ -217,7 +221,10 @@ 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) =>
|
||||
|
|
@ -255,22 +262,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.editReply("You don't have permission to use debug.");
|
||||
await interaction.reply({
|
||||
content: "You don't have permission to use debug.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
if (subcommand === "list") {
|
||||
await interaction.editReply({ content: runList() });
|
||||
await interaction.reply({ content: runList(), flags: MessageFlags.Ephemeral });
|
||||
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;
|
||||
|
|
@ -293,7 +300,9 @@ 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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -64,16 +64,17 @@ 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.editReply("You don't have permission to trigger evaluation reminders.");
|
||||
await interaction.reply({
|
||||
content: "You don't have permission to trigger evaluation reminders.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
|
||||
const client = interaction.client as Client;
|
||||
const missionInput = interaction.options.getString("mission")?.trim();
|
||||
|
||||
|
|
|
|||
|
|
@ -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.editReply("You don't have permission to trigger roll-calls.");
|
||||
await interaction.reply({
|
||||
content: "You don't have permission to trigger roll-calls.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
|
||||
const client = interaction.client as Client;
|
||||
const missionInput = interaction.options.getString("mission")?.trim();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
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,
|
||||
|
|
@ -113,11 +112,10 @@ export const handleButtonInteraction = async (
|
|||
`[Bot] RSVP interaction failed for mission #${missionId}: ${errorMessage(error)}`,
|
||||
);
|
||||
if (!interaction.replied && !interaction.deferred) {
|
||||
await safeEphemeralReply(
|
||||
interaction,
|
||||
payload,
|
||||
"Something went wrong while updating your attendance.",
|
||||
);
|
||||
await interaction.reply({
|
||||
content: "Something went wrong while updating your attendance.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -43,18 +43,8 @@ const parseTransferInteraction = (customId: string): ParsedTransferInteraction |
|
|||
return { requestId, action };
|
||||
};
|
||||
|
||||
// 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<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 replyEphemeral = (interaction: TransferInteraction, content: string): Promise<unknown> =>
|
||||
interaction.reply({ content, flags: MessageFlags.Ephemeral });
|
||||
|
||||
const currentLeaderSide = async (
|
||||
payload: Payload,
|
||||
|
|
@ -112,17 +102,16 @@ const editOutcome = async ({
|
|||
}: OutcomeEdit): Promise<void> => {
|
||||
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<void> => {
|
||||
const showRejectModal = async (interaction: ButtonInteraction, requestId: number): Promise<void> => {
|
||||
const reason = new TextInputBuilder()
|
||||
.setCustomId(REJECTION_REASON_ID)
|
||||
.setStyle(TextInputStyle.Paragraph)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { Client, Events, GatewayIntentBits } from "discord.js";
|
||||
import { Client, Events, GatewayIntentBits, MessageFlags } from "discord.js";
|
||||
import { getPayload } from "payload";
|
||||
import config from "@payload-config";
|
||||
import { botConfig } from "./config";
|
||||
|
|
@ -9,13 +9,9 @@ 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 });
|
||||
|
||||
|
|
@ -23,15 +19,6 @@ 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<void> => {
|
||||
if (shuttingDown) {
|
||||
|
|
@ -118,15 +105,13 @@ const main = async () => {
|
|||
try {
|
||||
await execute(interaction, payload);
|
||||
} catch (error) {
|
||||
payload.logger.error(
|
||||
`[Bot] Error executing /${interaction.commandName}: ${errorMessageOf(error)}`,
|
||||
);
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
payload.logger.error(`[Bot] Error executing /${interaction.commandName}: ${message}`);
|
||||
if (!interaction.replied && !interaction.deferred) {
|
||||
await safeEphemeralReply(
|
||||
interaction,
|
||||
payload,
|
||||
"Something went wrong while running this command.",
|
||||
);
|
||||
await interaction.reply({
|
||||
content: "Something went wrong while running this command.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,32 +0,0 @@
|
|||
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,19 +39,16 @@ 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<string, unknown>;
|
||||
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`,
|
||||
|
|
@ -61,78 +58,3 @@ 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