From dee3dbea09bb1c44a4d74dc24dd1fced5560feb0 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Tue, 1 Dec 2026 14:17:44 -0500 Subject: [PATCH] feat(polls): mirror unit polls to Discord with buttons and a reconcile loop Buttons rather than a native Discord poll: native polls (message type 46) show a raw headcount, cannot be edited, and cannot be closed early, so they could not carry weighted tallies, the tie ladder, or a two-way sync. - One button per option (`ptf-poll::`), acknowledged with deferReply before the member lookup, because the interaction token dies at 3s. - Buttons stay neutral on purpose. The message is shared, so highlighting a selection would show one member's ballot to the unit, and on an anonymous poll it would leak exactly what the poll hides. The voter's own ballot comes back ephemerally instead. - `discordPollHash` fingerprints everything the message shows (schema version, status, counts, winner, deadline, public voter names); the reconcile loop edits on drift and stamps the hash back, so it settles in one pass. - A `LISTEN ptf_poll_changed` listener reacts to web-side votes in under a second, and the timer pass is the fallback if a notification is dropped. - `advancePoll` runs inside the reconcile pass, so a poll closes and resolves even when nobody has the page open. A deleted message is never reposted. - `DISCORD_POLL_CHANNEL_ID` sets the channel; unset falls back to ops. --- src/bot/config.ts | 5 + src/bot/events/interactionCreate.ts | 92 +++++++ src/bot/services/index.ts | 2 + src/bot/services/pollEmbeds.ts | 411 ++++++++++++++++++++++++++++ 4 files changed, 510 insertions(+) create mode 100644 src/bot/services/pollEmbeds.ts diff --git a/src/bot/config.ts b/src/bot/config.ts index f8de7d4c..eb76c20b 100644 --- a/src/bot/config.ts +++ b/src/bot/config.ts @@ -10,6 +10,8 @@ export interface BotConfig { changelogChannelId: string | null; announceMentionRoleId: string | null; npcEventChannelId: string | null; + /** Channel unit polls are posted in. Falls back to the ops channel. */ + pollChannelId: string | null; debugChannelId: string | null; attendancePollMs: number; notificationPollMs: number; @@ -20,6 +22,7 @@ export interface BotConfig { achievementPollMs: number; presencePollMs: number; npcEventPollMs: number; + pollPollMs: number; /** Hours before a scheduled operation the modlist buffer reminder fires. */ modlistBufferHours: number; } @@ -77,6 +80,7 @@ export const botConfig: BotConfig = { changelogChannelId: optional("DISCORD_CHANGELOG_CHANNEL_ID"), announceMentionRoleId: optional("DISCORD_ANNOUNCE_MENTION_ROLE_ID"), npcEventChannelId: optional("DISCORD_NPC_EVENT_CHANNEL_ID"), + pollChannelId: optional("DISCORD_POLL_CHANNEL_ID"), debugChannelId: optional("DISCORD_DEBUG_CHANNEL_ID"), attendancePollMs: pollMs("DISCORD_ATTENDANCE_POLL_MS", 60_000), notificationPollMs: pollMs("DISCORD_NOTIFICATION_POLL_MS", 20_000), @@ -87,5 +91,6 @@ export const botConfig: BotConfig = { achievementPollMs: pollMs("DISCORD_ACHIEVEMENT_POLL_MS", 60_000), presencePollMs: pollMs("DISCORD_PRESENCE_POLL_MS", 30_000), npcEventPollMs: pollMs("DISCORD_NPC_EVENT_POLL_MS", 60_000), + pollPollMs: pollMs("DISCORD_POLL_POLL_MS", 60_000), modlistBufferHours: parseHours("DISCORD_MODLIST_BUFFER_HOURS", 8), }; diff --git a/src/bot/events/interactionCreate.ts b/src/bot/events/interactionCreate.ts index a42b7d27..f9880cdf 100644 --- a/src/bot/events/interactionCreate.ts +++ b/src/bot/events/interactionCreate.ts @@ -9,6 +9,8 @@ import { renderAttendanceEmbed, } from "@/bot/services/missionEmbeds"; import { botConfig } from "@/bot/config"; +import { refreshPollMessage } from "@/bot/services/pollEmbeds"; +import { castPollVote, loadPollVoteRows, isPollVotingClosed } from "@/lib/polls/service"; import { attendanceClosedMessage, type AttendanceResponse, @@ -53,6 +55,96 @@ export const handleButtonInteraction = async ( return; } + // 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") { + const pollId = Number(parts[1]); + const optionKey = parts[2]; + if (!Number.isInteger(pollId) || !optionKey) return; + + try { + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + } catch (error) { + payload.logger.error(`[Bot] Poll interaction could not be acknowledged: ${errorMessage(error)}`); + return; + } + + try { + const user = await findUserByDiscordId(payload, interaction.user.id); + if (!user) { + await interaction.editReply("Run /signup or /link first."); + return; + } + + const poll = await payload + .findByID({ collection: "polls", id: pollId, depth: 0, overrideAccess: true }) + .catch(() => null); + if (!poll) { + await interaction.editReply("That poll no longer exists."); + return; + } + if (isPollVotingClosed(poll)) { + await interaction.editReply("This poll has closed."); + return; + } + + // Toggle: pressing your current answer on a single-answer poll retracts it. + const rows = await loadPollVoteRows(payload, poll.id); + const current = rows.find((row) => row.userId === user.id)?.answers ?? []; + const alreadyChosen = current.includes(optionKey); + const answers = poll.multiSelect + ? alreadyChosen + ? current.filter((key) => key !== optionKey) + : [...current, optionKey] + : alreadyChosen + ? [] + : [optionKey]; + + const result = await castPollVote(payload, { + pollId: poll.id, + userId: user.id, + answers, + }); + + if (!result.ok) { + const message = + result.reason === "closed" + ? "This poll has closed." + : result.reason === "ineligible" + ? "You are not eligible to vote in this poll." + : result.reason === "too-many" + ? "This poll takes one answer." + : "That vote could not be recorded."; + await interaction.editReply(message); + return; + } + + await refreshPollMessage(payload, result.poll, interaction.message); + + const labelFor = (key: string) => { + const option = result.poll.options.find((o) => o.key === key); + return option ? `${option.emoji ? `${option.emoji} ` : ""}${option.label}` : key; + }; + await interaction.editReply( + answers.length === 0 + ? "Your vote was withdrawn." + : `Voted: ${answers.map(labelFor).join(", ")}. Press it again to withdraw.`, + ); + } catch (error) { + payload.logger.error( + `[Bot] Poll interaction failed for poll #${pollId}: ${errorMessage(error)}`, + ); + if (!interaction.replied && !interaction.deferred) { + await safeEphemeralReply( + interaction, + payload, + "Something went wrong while recording your vote.", + ); + } + } + return; + } + // Attendance roll-call buttons. if (parts.length !== 3 || parts[0] !== "ptf-att") { return; diff --git a/src/bot/services/index.ts b/src/bot/services/index.ts index b40852a0..89d59a58 100644 --- a/src/bot/services/index.ts +++ b/src/bot/services/index.ts @@ -9,6 +9,7 @@ import { start as startImminentReminders } from "./imminentReminders"; import { start as startFridayOpsNotice } from "./fridayOpsNotice"; import { start as startAchievementAnnouncements } from "./achievementAnnouncements"; import { start as startNpcEventAnnouncements } from "./npcEventAnnouncements"; +import { start as startPolls } from "./pollEmbeds"; import { start as startDiscordPresence } from "./discordPresence"; export type ServiceStarter = (client: Client, payload: Payload) => Promise | void; @@ -23,5 +24,6 @@ export const services: ServiceStarter[] = [ startFridayOpsNotice, startAchievementAnnouncements, startNpcEventAnnouncements, + startPolls, startDiscordPresence, ]; diff --git a/src/bot/services/pollEmbeds.ts b/src/bot/services/pollEmbeds.ts new file mode 100644 index 00000000..d0538191 --- /dev/null +++ b/src/bot/services/pollEmbeds.ts @@ -0,0 +1,411 @@ +import { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + EmbedBuilder, + type Client, + type Message, + type TextBasedChannelFields, +} from "discord.js"; +import type { Payload } from "payload"; +import type { Poll, User } from "@/payload-types"; +import { botConfig } from "@/bot/config"; +import { getOpsChannel } from "@/bot/services/missionEmbeds"; +import { POLL_CHANGED_CHANNEL } from "@/lib/polls/realtime"; +import { + advancePoll, + isPollVotingClosed, + loadPollVoteRows, + readPollOutcome, + tallyPollNow, +} from "@/lib/polls/service"; +import type { PollTally } from "@/lib/polls/tally"; + +/** + * Discord mirror of a unit poll. + * + * Native Discord polls cannot weight votes, cannot be edited, and cannot be + * closed early, so the poll is an embed with one button per option. The + * reconcile loop renders, edits and finalises it; the buttons write through + * the same `castPollVote` the web page uses. + */ + +const POLL_EMBED_SCHEMA_VERSION = 1; +const POLL_EMBED_COLOR = 0x6366f1; +const POLL_CLOSED_COLOR = 0x71717a; +const POLL_TIED_COLOR = 0xf59e0b; + +const errorMessage = (error: unknown): string => + error instanceof Error ? error.message : "Unknown error"; + +const memberName = (user: User): string => user.displayName ?? user.username; + +/** Bars are drawn from the weighted share, in ten steps. */ +const bar = (value: number, max: number): string => { + if (max <= 0 || value <= 0) return ""; + const filled = Math.max(1, Math.round((value / max) * 10)); + return "█".repeat(filled); +}; + +export interface PollRenderInput { + poll: Poll; + tally: PollTally; + /** Voter names, only populated for public polls. */ + votersByOption: Map; + now?: number; +} + +/** + * Fingerprint of everything the message shows. Drift triggers an edit; the + * edit stamps the hash back so the loop settles. The schema version forces one + * re-render when the layout changes. + */ +export const pollHash = (input: PollRenderInput): string => { + const { poll, tally, votersByOption } = input; + return JSON.stringify({ + v: POLL_EMBED_SCHEMA_VERSION, + status: poll.status, + closesAt: poll.closesAt, + multiSelect: poll.multiSelect === true, + anonymity: poll.anonymity, + counts: poll.options.map((option) => [ + option.key, + tally.counts[option.key]?.raw ?? 0, + tally.counts[option.key]?.weighted ?? 0, + ]), + winner: poll.winnerKey ?? null, + method: poll.resolutionMethod ?? null, + deadline: poll.decisionDeadline ?? null, + voters: poll.options.map((option) => [option.key, votersByOption.get(option.key) ?? []]), + }); +}; + +const optionLabel = (option: Poll["options"][number]): string => + `${option.emoji ? `${option.emoji} ` : ""}${option.label}`; + +export const renderPollEmbed = (input: PollRenderInput): EmbedBuilder => { + const { poll, tally, votersByOption } = input; + const now = input.now ?? Date.now(); + const closesUnix = Math.floor(new Date(poll.closesAt).getTime() / 1000); + const pollUrl = `${botConfig.appUrl}/polls/${poll.id}`; + const closed = isPollVotingClosed(poll, now); + const pending = poll.status === "pending_decision"; + const maxWeighted = Math.max(0, ...poll.options.map((o) => tally.counts[o.key]?.weighted ?? 0)); + + const fields = poll.options.map((option) => { + const counts = tally.counts[option.key] ?? { raw: 0, weighted: 0 }; + const weightedText = + counts.weighted === counts.raw + ? `${counts.raw}` + : `${counts.raw} (weight ${counts.weighted % 1 === 0 ? counts.weighted : counts.weighted.toFixed(2)})`; + const barText = bar(counts.weighted, maxWeighted); + const names = votersByOption.get(option.key) ?? []; + const voterText = + poll.anonymity === "public" && names.length > 0 + ? `\n${names.join(", ").slice(0, 900)}` + : ""; + return { + name: `${optionLabel(option)} — ${weightedText}`, + value: `${barText || "—"}${voterText}`.slice(0, 1024), + inline: false, + }; + }); + + const statusLine = pending + ? "**Tied.** Awaiting a superuser decision." + : closed + ? poll.winnerKey + ? `**Closed.** Winner: ${ + optionLabel( + poll.options.find((o) => o.key === poll.winnerKey) ?? { + key: "", + label: poll.winnerKey, + }, + ) || poll.winnerKey + }` + : "**Closed.** No decision." + : `**Closes:** ()`; + + const settings = [ + poll.multiSelect ? "Multiple answers" : "One answer", + poll.anonymity === "anonymous" ? "Anonymous (counts only)" : "Public", + `Weighted votes: ${tally.totalWeight % 1 === 0 ? tally.totalWeight : tally.totalWeight.toFixed(2)}`, + `${tally.totalVotes} voter${tally.totalVotes === 1 ? "" : "s"}`, + ].join(" · "); + + const deadlineUnix = poll.decisionDeadline + ? Math.floor(new Date(poll.decisionDeadline).getTime() / 1000) + : null; + + return new EmbedBuilder() + .setTitle(poll.title) + .setURL(pollUrl) + .setDescription( + [ + ...(poll.body?.trim() ? [poll.body.trim(), ""] : []), + statusLine, + pending && deadlineUnix + ? `A random tied option is chosen if no superuser decides.` + : null, + settings, + ] + .filter((line): line is string => line !== null) + .join("\n"), + ) + .setColor(pending ? POLL_TIED_COLOR : closed ? POLL_CLOSED_COLOR : POLL_EMBED_COLOR) + .addFields(fields) + .setFooter({ text: `Vote here or on the web · ${pollUrl}` }); +}; + +/** + * One row per five options. Every button is neutral: the message is shared, so + * a highlight would show one member's ballot to the whole unit, and on an + * anonymous poll it would leak the very thing the poll hides. The voter gets + * their own confirmation ephemerally instead. Once voting is over every button + * is disabled so the message becomes a stable record. + */ +export const buildPollRows = (poll: Poll): ActionRowBuilder[] => { + const closed = isPollVotingClosed(poll); + const rows: ActionRowBuilder[] = []; + + for (let index = 0; index < poll.options.length; index += 5) { + const chunk = poll.options.slice(index, index + 5); + const row = new ActionRowBuilder(); + for (const option of chunk) { + const button = new ButtonBuilder() + .setCustomId(`ptf-poll:${poll.id}:${option.key}`) + .setStyle(ButtonStyle.Secondary) + .setLabel( + `${option.emoji ? `${option.emoji} ` : ""}${option.label}`.slice(0, 80), + ) + .setDisabled(closed); + row.addComponents(button); + } + rows.push(row); + } + return rows; +}; + +/** Voter names per option, for public polls only. Anonymous polls never name voters here. */ +const loadVoterNames = async ( + payload: Payload, + poll: Poll, +): Promise> => { + const byOption = new Map(); + if (poll.anonymity !== "public") return byOption; + + const rows = await loadPollVoteRows(payload, poll.id); + if (rows.length === 0) return byOption; + + const userIds = [...new Set(rows.map((row) => row.userId))]; + const users = await payload.find({ + collection: "users", + where: { id: { in: userIds } }, + limit: userIds.length, + depth: 0, + overrideAccess: true, + }); + const nameById = new Map( + users.docs.map((doc) => [doc.id, memberName(doc as unknown as User)]), + ); + + for (const row of rows) { + const name = nameById.get(row.userId) ?? `user ${row.userId}`; + for (const key of row.answers) { + const list = byOption.get(key) ?? []; + list.push(name); + byOption.set(key, list); + } + } + for (const [key, names] of byOption) { + byOption.set(key, [...names].sort((a, b) => a.localeCompare(b))); + } + return byOption; +}; + +/** Everything the renderer needs, fetched once per reconcile pass. */ +export const loadPollRender = async ( + payload: Payload, + poll: Poll, +): Promise => { + const { tally } = await tallyPollNow(payload, poll); + return { poll, tally, votersByOption: await loadVoterNames(payload, poll) }; +}; + +const pollChannelId = (): string | null => botConfig.pollChannelId ?? botConfig.opsChannelId; + +const getPollChannel = async (client: Client): Promise => { + const channelId = pollChannelId(); + if (!channelId) return null; + return getOpsChannel(client, channelId); +}; + +/** + * Render, post or edit one poll, then stamp the hash. A deleted message is not + * reposted (one-shot, same rule as the roll-call): the web page remains the + * source of truth. + */ +export const reconcilePoll = async ( + client: Client, + payload: Payload, + pollId: number, +): Promise => { + const channel = await getPollChannel(client); + if (!channel) return; + + // Close or resolve first, so the message never shows a poll that should have + // ended. advancePoll is idempotent and cheap when nothing is due. + const poll = await advancePoll(payload, { pollId }); + if (poll.status === "closed" && !poll.discordMessageId) return; + + const render = await loadPollRender(payload, poll); + const hash = pollHash(render); + + if (!poll.discordMessageId) { + const message = await channel.send({ + embeds: [renderPollEmbed(render)], + components: buildPollRows(poll), + }); + await payload.update({ + collection: "polls", + id: poll.id, + data: { + discordMessageId: message.id, + discordChannelId: message.channelId ?? pollChannelId(), + discordPostedAt: new Date().toISOString(), + discordPollHash: hash, + }, + overrideAccess: true, + }); + payload.logger.info(`[Bot] Posted poll #${poll.id} (${poll.title}).`); + return; + } + + if (poll.discordPollHash === hash) return; + + const message = await channel.messages.fetch(poll.discordMessageId).catch(() => null); + if (!message) { + payload.logger.warn( + `[Bot] Poll #${poll.id} message ${poll.discordMessageId} is gone; leaving it unposted.`, + ); + return; + } + + await message.edit({ + embeds: [renderPollEmbed(render)], + components: buildPollRows(poll), + }); + await payload.update({ + collection: "polls", + id: poll.id, + data: { discordPollHash: hash }, + overrideAccess: true, + }); +}; + +/** Edit a poll message after an in-Discord vote, so the tally moves immediately. */ +export const refreshPollMessage = async ( + payload: Payload, + poll: Poll, + message: Message, +): Promise => { + const render = await loadPollRender(payload, poll); + await message.edit({ + embeds: [renderPollEmbed(render)], + components: buildPollRows(poll), + }); + await payload.update({ + collection: "polls", + id: poll.id, + data: { discordPollHash: pollHash(render) }, + overrideAccess: true, + }); +}; + +/** + * Which polls need a render pass: anything still live, anything posted, and + * anything resolved in the last two weeks (so a closed poll's final message is + * written once). Older history is left alone. + */ +const getReconcilablePolls = async (payload: Payload): Promise => { + const cutoff = new Date(Date.now() - 14 * 24 * 3_600_000).toISOString(); + const res = await payload.find({ + collection: "polls", + where: { + or: [ + { status: { in: ["open", "pending_decision"] } }, + { discordMessageId: { exists: true }, updatedAt: { greater_than: cutoff } }, + ], + }, + limit: 50, + depth: 0, + sort: "-updatedAt", + overrideAccess: true, + }); + return res.docs; +}; + +let reconcileRunning = false; + +export const reconcile = async (client: Client, payload: Payload): Promise => { + if (reconcileRunning) return; + reconcileRunning = true; + try { + if (!pollChannelId()) return; + const polls = await getReconcilablePolls(payload); + for (const poll of polls) { + try { + await reconcilePoll(client, payload, poll.id); + } catch (error) { + payload.logger.error( + `[Bot] Poll reconcile failed for poll #${poll.id}: ${errorMessage(error)}`, + ); + } + } + } catch (error) { + payload.logger.error(`[Bot] Poll reconcile failed: ${errorMessage(error)}`); + } finally { + reconcileRunning = false; + } +}; + +const startPollListener = async (client: Client, payload: Payload): Promise => { + if (!pollChannelId()) return; + + const listener = await payload.db.pool.connect(); + listener.on("notification", (notification) => { + if (notification.channel !== POLL_CHANGED_CHANNEL || !notification.payload) return; + + let pollId: unknown; + try { + pollId = JSON.parse(notification.payload).pollId; + } catch { + payload.logger.warn("[Bot] Ignoring malformed poll change notification."); + return; + } + if (typeof pollId !== "number" || !Number.isInteger(pollId)) return; + + void reconcilePoll(client, payload, pollId).catch((error) => { + payload.logger.error( + `[Bot] Poll change reconcile failed for poll #${pollId}: ${errorMessage(error)}`, + ); + }); + }); + + listener.on("error", (error) => { + payload.logger.error(`[Bot] Poll listener failed: ${errorMessage(error)}`); + }); + await listener.query(`LISTEN ${POLL_CHANGED_CHANNEL}`); + payload.logger.info("[Bot] Poll realtime listener started"); +}; + +export const start = (client: Client, payload: Payload): void => { + payload.logger.info("[Bot] Poll service started"); + void startPollListener(client, payload).catch((error) => { + payload.logger.error(`[Bot] Poll realtime listener failed to start: ${errorMessage(error)}`); + }); + void reconcile(client, payload); + setInterval(() => { + void reconcile(client, payload); + }, botConfig.pollPollMs); +};