fix(bot): route poll buttons to their interaction handler
The InteractionCreate dispatcher in index.ts forwarded only customIds starting with `ptf-att:`, so poll buttons (`ptf-poll:`) were never acknowledged: Discord answered every press with "This interaction failed" and the message looked broken while the same vote worked on the web. The post-op rating button had the same defect and had never worked. The prefix list now lives with the handler (UNIT_BUTTON_PREFIXES / isUnitButtonCustomId) and the dispatcher reads it, so a prefix the handler answers to cannot be filtered out above it. A `ptf-` button nothing claims replies with a toast and logs a warning instead of failing silently. Regression test pins the predicate to the customIds buildPollRows actually generates, so the two halves cannot drift apart again.
This commit is contained in:
parent
528bf83f30
commit
f478f38938
4 changed files with 130 additions and 5 deletions
|
|
@ -98,6 +98,10 @@ An NPC `event` node with the `poll` effect raises a unit-wide poll: `launchDialo
|
|||
|
||||
**Ties**: `tallyPoll` weights votes by the highest matching role tier, then `resolvePollTally` gives a tie to the conversation initiator when exactly one tied option is on their ballot. Otherwise the poll parks in `pending_decision` with the tally frozen, the buttons disable, and a superuser settles it on `/polls/[id]`; `resolveDeadlineTie` picks a random tied option once `tieGraceHours` passes. Only a resolved poll writes its `resultFlag`.
|
||||
|
||||
## Button routing (never-miss)
|
||||
|
||||
The `InteractionCreate` dispatcher in `index.ts` forwards a button only when its customId matches a prefix the handler claims. That list lives with the handler (`UNIT_BUTTON_PREFIXES` / `isUnitButtonCustomId` in `events/interactionCreate.ts`) and the dispatcher reads it, so adding a branch there is enough. Do not re-check a prefix by hand in the dispatcher: poll buttons shipped handled-but-unrouted, which left every press unacknowledged and Discord answered the member with "This interaction failed" while the same vote worked on the web. A `ptf-` button nothing claims now replies with a toast and logs `[Bot] Unhandled button interaction`, so the next gap is loud instead of silent. Any button that runs a database call must `deferReply` first; the interaction token dies at 3 seconds.
|
||||
|
||||
## Feature flow: notifications
|
||||
|
||||
`notificationBridge` polls `user-notifications` (cursor = last seen id; cap 5 DMs/tick). DMs opted-in users (`preferences.discord.enabled`, not in `mutedTypes`). Remaining polish: the web preferences UI does not yet expose the `preferences.discord` toggles — they exist on the Users collection and are read by the bridge, but are currently only settable in the Payload admin panel.
|
||||
|
|
|
|||
|
|
@ -19,6 +19,25 @@ import {
|
|||
setMissionAttendance,
|
||||
} from "@/lib/attendance";
|
||||
|
||||
/**
|
||||
* customId prefixes this handler answers to. The InteractionCreate dispatcher
|
||||
* in `index.ts` routes exactly these here, and it reads this same list, so a
|
||||
* prefix cannot be handled below and unreachable above: an unrouted button is
|
||||
* never acknowledged, and Discord shows the user "This interaction failed".
|
||||
*/
|
||||
const BARE_PREFIX = {
|
||||
attendance: "ptf-att",
|
||||
poll: "ptf-poll",
|
||||
rating: "ptf-rate",
|
||||
} as const;
|
||||
|
||||
export const UNIT_BUTTON_PREFIXES: readonly string[] = Object.values(BARE_PREFIX).map(
|
||||
(prefix) => `${prefix}:`,
|
||||
);
|
||||
|
||||
export const isUnitButtonCustomId = (customId: string): boolean =>
|
||||
UNIT_BUTTON_PREFIXES.some((prefix) => customId.startsWith(prefix));
|
||||
|
||||
const ATTENDANCE_LABELS: Record<AttendanceResponse, string> = {
|
||||
yes: "Yes",
|
||||
no: "No",
|
||||
|
|
@ -38,7 +57,7 @@ export const handleButtonInteraction = async (
|
|||
const parts = interaction.customId.split(":");
|
||||
|
||||
// Post-op survey rating prompt: link back to the mission page to rate.
|
||||
if (parts.length === 3 && parts[0] === "ptf-rate") {
|
||||
if (parts.length === 3 && parts[0] === BARE_PREFIX.rating) {
|
||||
const missionId = Number(parts[1]);
|
||||
if (!Number.isInteger(missionId)) return;
|
||||
try {
|
||||
|
|
@ -57,7 +76,7 @@ export const handleButtonInteraction = async (
|
|||
|
||||
// Unit poll buttons. Acknowledge first: resolving the Discord member to a
|
||||
// Payload user is a database call, and the interaction token dies at 3s.
|
||||
if (parts.length === 3 && parts[0] === "ptf-poll") {
|
||||
if (parts.length === 3 && parts[0] === BARE_PREFIX.poll) {
|
||||
const pollId = Number(parts[1]);
|
||||
const optionKey = parts[2];
|
||||
if (!Number.isInteger(pollId) || !optionKey) return;
|
||||
|
|
@ -146,7 +165,7 @@ export const handleButtonInteraction = async (
|
|||
}
|
||||
|
||||
// Attendance roll-call buttons.
|
||||
if (parts.length !== 3 || parts[0] !== "ptf-att") {
|
||||
if (parts.length !== 3 || parts[0] !== BARE_PREFIX.attendance) {
|
||||
return;
|
||||
}
|
||||
const missionId = Number(parts[1]);
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ 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 { handleButtonInteraction, isUnitButtonCustomId } from "./events/interactionCreate";
|
||||
import { handleTransferInteraction } from "./events/transferInteractions";
|
||||
import { safeEphemeralReply } from "./lib/interactions";
|
||||
|
||||
|
|
@ -85,7 +85,9 @@ const main = async () => {
|
|||
});
|
||||
|
||||
client.on(Events.InteractionCreate, async (interaction) => {
|
||||
if (interaction.isButton() && interaction.customId.startsWith("ptf-att:")) {
|
||||
// The handler owns the prefix list, so a button it answers to can never be
|
||||
// filtered out here first (that silent gap is what made poll buttons fail).
|
||||
if (interaction.isButton() && isUnitButtonCustomId(interaction.customId)) {
|
||||
await handleButtonInteraction(interaction, payload);
|
||||
return;
|
||||
}
|
||||
|
|
@ -108,6 +110,16 @@ const main = async () => {
|
|||
await handlePresenceModal(interaction, payload);
|
||||
return;
|
||||
}
|
||||
// A ptf button no branch above claimed. Acknowledge it so the user sees a
|
||||
// sentence instead of Discord's "This interaction failed", and log the id
|
||||
// so a prefix missing from the routing above is visible instead of silent.
|
||||
if (interaction.isButton() && interaction.customId.startsWith("ptf-")) {
|
||||
payload.logger.warn(
|
||||
`[Bot] Unhandled button interaction: ${interaction.customId.slice(0, 80)}`,
|
||||
);
|
||||
await safeEphemeralReply(interaction, payload, "This button is no longer handled.");
|
||||
return;
|
||||
}
|
||||
if (!interaction.isChatInputCommand()) {
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
90
tests/int/bot-button-routing.int.spec.ts
Normal file
90
tests/int/bot-button-routing.int.spec.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
// The bot modules validate their environment at import time.
|
||||
process.env.DISCORD_TOKEN ||= "routing-test-token";
|
||||
process.env.DISCORD_GUILD_ID ||= "1";
|
||||
process.env.APP_URL ||= "https://polaris.test";
|
||||
|
||||
import type { Poll } from "@/payload-types";
|
||||
|
||||
type InteractionCreate = typeof import("@/bot/events/interactionCreate");
|
||||
type PollEmbeds = typeof import("@/bot/services/pollEmbeds");
|
||||
|
||||
let routing: InteractionCreate;
|
||||
let embeds: PollEmbeds;
|
||||
|
||||
beforeAll(async () => {
|
||||
routing = await import("@/bot/events/interactionCreate");
|
||||
embeds = await import("@/bot/services/pollEmbeds");
|
||||
});
|
||||
|
||||
const poll = (): Poll =>
|
||||
({
|
||||
id: 9,
|
||||
title: "Question",
|
||||
options: [
|
||||
{ key: "agree", label: "Agree", emoji: null, description: null, id: "a" },
|
||||
{ key: "decline", label: "Decline", emoji: null, description: null, id: "b" },
|
||||
],
|
||||
status: "open",
|
||||
closesAt: new Date(Date.now() + 3_600_000).toISOString(),
|
||||
multiSelect: false,
|
||||
anonymity: "public",
|
||||
defaultWeight: 1,
|
||||
weightTiers: [],
|
||||
tieGraceHours: 24,
|
||||
sourceKey: "1:node",
|
||||
openedAt: new Date().toISOString(),
|
||||
initiatedBy: 1,
|
||||
eligibleRoles: [],
|
||||
updatedAt: "",
|
||||
createdAt: "",
|
||||
}) as unknown as Poll;
|
||||
|
||||
/**
|
||||
* The bot dispatcher only forwards buttons whose customId it recognises, and an
|
||||
* unrecognised button is never acknowledged: Discord then tells the member
|
||||
* "This interaction failed". Poll buttons shipped without being added to that
|
||||
* routing list, so they did exactly that in production while the web page kept
|
||||
* working. These cases pin the two halves together.
|
||||
*/
|
||||
describe("Bot button routing", () => {
|
||||
it("routes every prefix the button handler answers to", () => {
|
||||
for (const customId of ["ptf-att:1:yes", "ptf-poll:1:agree", "ptf-rate:112:rate"]) {
|
||||
expect(routing.isUnitButtonCustomId(customId)).toBe(true);
|
||||
}
|
||||
expect(routing.UNIT_BUTTON_PREFIXES).toEqual([
|
||||
"ptf-att:",
|
||||
"ptf-poll:",
|
||||
"ptf-rate:",
|
||||
]);
|
||||
});
|
||||
|
||||
it("routes the exact customIds the poll message builds", () => {
|
||||
const rows = embeds.buildPollRows(poll()).map((row) => row.toJSON());
|
||||
|
||||
const customIds = rows.flatMap((row) =>
|
||||
row.components.map((component) => String((component as { custom_id?: string }).custom_id)),
|
||||
);
|
||||
expect(customIds).toEqual(["ptf-poll:9:agree", "ptf-poll:9:decline"]);
|
||||
for (const customId of customIds) {
|
||||
expect(routing.isUnitButtonCustomId(customId)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves the other handlers' buttons to their own branches", () => {
|
||||
for (const customId of [
|
||||
"ptf-xfer:4:accept",
|
||||
"ptf-announce:compose",
|
||||
"ptf-changelog-edit:abc",
|
||||
"ptf-rp-edit",
|
||||
]) {
|
||||
expect(routing.isUnitButtonCustomId(customId)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("ignores anything without a ptf prefix", () => {
|
||||
expect(routing.isUnitButtonCustomId("something-else")).toBe(false);
|
||||
expect(routing.isUnitButtonCustomId("")).toBe(false);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in a new issue