19 KiB
AGENTS.md — Discord Bot
Parent:
../../AGENTS.md— env vars (DISCORD_TOKEN,DISCORD_GUILD_ID), deployment, Payload config.
Overview
Standalone long-running process (bun run bot). Imports @payload-config directly (same pattern as src/scripts/ and src/tools/seed/), shares PostgreSQL with web app. Under active development. Full product requirements live in docs/bot/context.md; the approved implementation design is in docs/bot/design.md. Read both before touching bot code.
Env
Required: DISCORD_TOKEN, DISCORD_GUILD_ID (fail-fast on missing vars in config.ts). Optional: DISCORD_OPS_CHANNEL_ID, DISCORD_ANNOUNCE_CHANNEL_ID, DISCORD_CHANGELOG_CHANNEL_ID (dedicated #releases channel for /changelog; falls back to the announce channel), DISCORD_STAFF_ROLE_IDS, DISCORD_SIDE_OPS_CHANNEL_ID (Friday open-slot notice channel), DISCORD_COMMUNITY_ZEUS_ROLE_ID (role ping for that notice), DISCORD_NPC_EVENT_CHANNEL_ID (NPC dispatch channel for dialogue events; unset disables posting), DISCORD_DEBUG_CHANNEL_ID (sandbox channel for /debug run ... mode:sandbox; unset disables sandbox), APP_URL, plus poll intervals DISCORD_ATTENDANCE_POLL_MS (default 60s), DISCORD_NOTIFICATION_POLL_MS (default 20s), DISCORD_EVALUATION_POLL_MS (default 60s), DISCORD_IMMINENT_POLL_MS (default 60s), DISCORD_SIDE_OPS_POLL_MS (default 30 min), DISCORD_PRESENCE_POLL_MS (default 30s), DISCORD_NPC_EVENT_POLL_MS (default 60s). Logs through payload.logger.
Structure
bot/
index.ts # Entry point
config.ts # Env validation (fail-fast on missing required vars)
commands/
index.ts # Command registry (global vs guild scope)
ping.ts # /ping (global, DM-usable)
signup.ts # /signup (DM-only, creates Payload user with temp password)
link.ts # /link (global, links discordId to existing user)
announce.ts # /announce (guild-only, staff only; message omitted = compose modal with channel picker, handler in this file)
changelog.ts # /changelog (guild-only, staff only; posts a CHANGELOG.md entry to #releases, native markdown, splits long entries; edit=true opens a prefilled modal to tweak the copy before posting)
remindEvaluations.ts # /remind-evaluations (guild-only, staff only, manual evaluation-reminder trigger)
rollcall.ts # /rollcall (guild-only, staff only, force-send/refresh a roll-call)
discordPresence.ts # /discord-presence (guild-only, discord:rp:update; view/edit/clear the bot's Rich Presence via a prefilled modal)
debug.ts # /debug (guild-only, staff only; list | run preview|sandbox|live | inspect | delete, see "Feature flow: debug")
events/
interactionCreate.ts # Routes ptf-att: RSVP button interactions
transferInteractions.ts # Handles transfer decision buttons (approve/deny/appeal)
services/
index.ts # Service registry
missionEmbeds.ts # Attendance embed lifecycle + reconcile loop (poll tick)
notificationBridge.ts # Poll user-notifications → Discord DMs
evaluationReminders.ts # Post-mission evaluation reminder DMs (one-shot marker on Missions)
imminentReminders.ts # Pre-op reminder: thread on the roll-call message + attendee pings (one-shot marker on Missions)
fridayOpsNotice.ts # Weekly notice: pings Community Zeus in #side-ops when the upcoming Friday has no op
npcEventAnnouncements.ts # Poll game-event-logs flagged discordRequested → post amber "NPC Dispatch" embeds, stamp discordAnnouncedAt + discordMessageId
signup.ts # Signup service logic
transferRequests.ts # Polls assignment transfer requests awaiting leader decision
transferDelivery.ts # Transfer leader-request / rejection / info delivery DMs
discordPresence.ts # Poll the discord-presence Global → reconcile the bot's live Rich Presence (in-memory last-applied diff)
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
presence.ts # applyPresence: map the discord-presence Global → a discord.js activity (idle when disabled/blank)
Command registration scope
- Global (DM-usable):
signup,link,ping - Guild-only:
announce,remind-evaluations,rollcall,discord-presence(guild-scoped commands never appear in DMs)
Feature flow: signup/link
/signup is DM-only. Creates Payload user with username = discordUsername = caller's Discord username. Ephemeral reply carries temp password (guaranteed delivery path); interaction.user.send() is best-effort persistent copy, so a blocked DM never orphans the account. /link works in servers and DMs — matches discordUsername → sets discordId. DM gotcha: a user with "Allow direct messages from server members" off in Discord privacy settings can neither receive the bot's DMs nor open a DM with the bot; the /signup rejection message explains how to enable it.
Feature flow: changelogs
/changelog (guild-only, staff only) posts a CHANGELOG.md release entry to the releases channel (DISCORD_CHANGELOG_CHANNEL_ID, falling back to DISCORD_ANNOUNCE_CHANNEL_ID). /changelog targets the newest entry; /changelog v0.4.0 targets a specific version (for catching up on missed posts); /changelog v0.3.0..v0.5.0 targets a range (inclusive slice, output oldest-to-newest). Either range end is open (v0.3.0.. to the latest, ..v0.5.0 from the oldest) and a reversed range is normalized. Edit mode (edit=true): instead of posting, opens a modal prefilled with the target entry's raw markdown so staff can make last-minute copy tweaks right in Discord; submit renders the edited text through the same pipeline and posts it. One-shot by design: the edit shapes only the post about to happen, CHANGELOG.md (baked into the deployed image) is never written back. Single-version targets only (ranges are rejected ephemerally), entries over the 4000-char modal input cap refuse edit mode with a pointer to the file. The modal must be the first response, so the edit path checks staff and shows the modal WITHOUT deferring (same pattern as /announce); submits route through bot/index.ts on the ptf-changelog-edit: custom-id prefix and re-check staff. Rendering lives in bot/lib/changelogRender.ts (pure, no Discord/Payload deps): entries are split on # vX.Y.Z headers, ### sections become Discord markdown headings (### , the deepest level Discord renders), bullets become •, and entries over Discord's 4096-char limit are split across messages at section boundaries. The command reads CHANGELOG.md from the repo root relative to the file (works from the deploy server) and posts each version as its own amber embed, the first message of each version carrying the Changelog vX.Y.Z title and multi-message versions adding a page footer. Ranges spanning more than WIDE_RANGE_THRESHOLD (10) versions post an ephemeral warning but proceed. Idempotency ("don't repost") is intentionally out of scope for the manual command; the same rendering can be reused by a future automatic trigger.
Feature flow: debug
/debug (guild-only, isStaff) re-renders or re-sends bot messages through the production render and send code, so a test exercises what actually ships. Subcommands: list, run action target mode, inspect action target, delete action target.
- preview (default): ephemeral. Shows the exact embed, with buttons stripped. Writes nothing.
- sandbox: posts to
DISCORD_DEBUG_CHANNEL_IDwith mentions suppressed. Writes nothing. Refused with a message when that env var is unset. - live: posts to the real channel after a Confirm button (30s timeout). Supported by
rollcall(method=editedits the stored message in place,method=repostposts fresh and links it),modlist,npc-dispatch,achievement, andchangelog(posts to the releases channel). Live posts do not change one-shot markers or hashes except through the rollcall path. - delete: removes the tracked message after Confirm and clears its stored id. Keeps the one-shot markers, so a deleted message is not reposted automatically.
Preview-only actions (no live send): imminent (live thread pings would reach attendees), ready-reminders, friday-notice (a live post would create a real dedup token), evaluations (shows the first recipient's DM with a recipient count), notification, and transfer. Preview omits buttons, so debug output never exposes a live decision control.
Actions live in bot/lib/debugActions.ts. Each build receives the client and returns the message the production path sends. The render helpers they reuse are exported from services/missionEmbeds.ts, services/npcEventAnnouncements.ts, services/imminentReminders.ts, services/readyReminders.ts, services/evaluationReminders.ts, services/notificationBridge.ts, services/fridayOpsNotice.ts, services/transferDelivery.ts, and commands/changelog.ts.
Feature flow: attendance
Bot posts RSVP embeds (Yes/Tentative/No) for future, Scheduled, visibility:"unit" missions into ops channel. Stores discordMessageId + discordAttendanceHash on mission. Reconciles hash changes every poll tick (web ↔ Discord two-way sync, loop-safe). The embed title links to the mission page, a mission summary sits under the title (truncated to 300 characters with an ellipsis), and an "Open the op" field carries the URL; attendanceHash includes an embed schema version so layout-only changes re-render live roll-calls once (idempotent). Web UI: MissionAttendance component. Weekly main missions are cloned by bun run payload generate-mission (a payload bin, see src/scripts/AGENTS.md). Staff can force one outside the lead-time window with /rollcall [mission] (ID, name, or code name; omit to target the next upcoming Scheduled unit op): forceRollCall in missionEmbeds.ts re-renders the live message or posts a fresh one (even after a manual deletion), bypassing only the 3-day gate; target lookup/validation lives in src/lib/intelligence/rollCall.ts.
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.
Feature flow: evaluation reminders
Once a mission is evaluable (Completed, or Scheduled/Active past its start), sends a one-shot DM per linked user asking them to rate their leadership (juniors get a "rate your seniors" list; seniors get a "rate your subordinates" section). Pairing is rank-based among the mission's yes-RSVP participants: every strict-rank-gap attendee pair is reminded in both directions; same-rank peers and rankless participants form no pairs. Recipient plan: computeEvaluationReminderPlan in src/lib/evaluations/reminders.ts; state marker evaluationRemindersSentAt on Missions (withheld if the 40-DM/tick cap is hit - retries next tick). DMs ignore preferences.discord.enabled (defaults false, not yet exposed in web UI). Staff can re-send manually via /remind-evaluations.
Feature flow: imminent op reminder
15 minutes before a posted op starts (visibility: "unit", Scheduled, live roll-call message), imminentReminders opens a thread on the roll-call message ("Op starting soon: ") and pings every yes-RSVP via <@discordId> (pings ignore preferences.discord.enabled, same exception as evaluation reminders). One-shot via the imminentReminderSentAt marker on Missions; the cancel flow clears it so a rescheduled op re-reminds. Grace bound: a missed reminder still fires within 15 minutes after the start, never later. Query: src/lib/intelligence/imminentReminders.ts (window constants + getImminentReminderMissions).
Feature flow: Friday open-slot notice
At 8 PM Eastern on Wednesday (America/New_York, evaluated via isNoticeDue in src/lib/intelligence/fridayOpsNotice.ts; catch-up until ET midnight, a fully missed Wednesday skips to next week), if no non-cancelled mission starts on that week's upcoming Friday, fridayOpsNotice posts once in #side-ops pinging the Community Zeus role: the slot is open, hosting is welcome, and if nobody picks it up the slot stays empty or Jason hosts it himself. The slot window is Friday 00:00–23:59:59.999 America/New_York computed from the Eastern calendar date, never the server clock (the UTC deploy container once treated Wed 8 PM ET as Thursday and missed Friday-evening ops entirely); when it is already Friday Eastern, that day itself is the slot, so the dedup token stays stable from Wednesday through the op day and late claims still credit. When a non-superuser creator later claims the slot (getFridayClaimant, earliest-created mission wins; superuser/staff-created missions never claim), the notice is edited to append "This slot was claimed by <user>. Thank you for hosting for our community!"; if that op is later cancelled or deleted, the claim line is stripped and the notice reverts to the open-slot state (a between-polls claim swap re-credits the new claimant). Role: DISCORD_COMMUNITY_ZEUS_ROLE_ID or resolved by name in the guild; channel: DISCORD_SIDE_OPS_CHANNEL_ID. Dedup without DB state: the message embeds a stable per-Friday <t:epoch:D> token and the service scans recent channel messages for it (claim idempotency via a marker in the message content). Drafts (Concept) count as the slot being taken.
Feature flow: assignment transfers
transferRequests polls assignment-transfers for requests awaiting leader decision; leaders approve/deny via buttons handled in transferInteractions.ts; DMs are built by lib/transferMessaging.ts and sent through transferDelivery.ts (leader request, requester rejection notice, decision info). Web side: src/lib/transfers/ + /transfers page.
Feature flow: Discord Rich Presence
The bot's Discord activity (state/details/timestamps/images/party/join secret) has ONE source of truth: the discord-presence Payload Global (src/collections/discord/DiscordPresence.ts). Two independent writers update it and either takes effect live:
- CMS: edit the "Discord Rich Presence" global in the admin panel (gated by
discord:rp:update). - Command:
/discord-presence(guild-only, gated bydiscord:rp:update) withaction=view|edit|clear.editopens a prefilled modal (all fields as text inputs, since this discord.js build cannot preselect modal select-menu defaults); submit writes the Global then applies immediately.cleardisables + blanks every field. Modal submit routes throughbot/index.tson theptf-rp-edit:custom-id prefix →handlePresenceModal.
A poll loop (services/discordPresence.ts, DISCORD_PRESENCE_POLL_MS, default 30s) reconciles Discord's live presence with the stored Global so CMS edits propagate without a restart; it holds an in-memory last-applied signature so a command edit isn't re-applied. applyPresence (lib/presence.ts) maps the Global to a discord.js activity: state→bold title (name), details→details line, timestamps are epoch ms, partySize/partyMax→party.size [current,max], image keys are freeform (asset id or data:image/... URI). When disabled OR every field is blank the bot goes idle with no activity. The bot reads/writes the Global with overrideAccess: true (trusted internal process). Permissions discord:rp:read/discord:rp:update live in the "Discord Bot" group.
Where to look
| Task | Path |
|---|---|
| Add new slash command | bot/commands/<name>.ts + register in bot/commands/index.ts |
| Changelog rendering/splitting | bot/lib/changelogRender.ts |
| Add button interaction | bot/events/interactionCreate.ts (RSVP) or transferInteractions.ts (transfers) |
| Modify embed lifecycle | bot/services/missionEmbeds.ts |
| Force a roll-call manually | bot/commands/rollcall.ts + src/lib/intelligence/rollCall.ts |
| Change DM bridging | bot/services/notificationBridge.ts |
| Evaluation reminder logic | bot/services/evaluationReminders.ts + src/lib/evaluations/reminders.ts |
| Imminent-op reminder logic | bot/services/imminentReminders.ts + src/lib/intelligence/imminentReminders.ts |
| Friday open-slot notice | bot/services/fridayOpsNotice.ts + src/lib/intelligence/fridayOpsNotice.ts |
| NPC dispatch posting (dialogue events) | bot/services/npcEventAnnouncements.ts + discordRequested/discordAnnouncedAt on game-event-logs |
| Transfer workflow | bot/services/transferRequests.ts + lib/transferMessaging.ts |
| User lookup patterns | bot/lib/resolve.ts |
| 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:
- Ack first, then work. Guild commands must
deferReplyas their first Discord call, beforeguild.members.fetch()andisStaff()./rollcall,/remind-evaluations, and/debugdefer up front and report permission denials througheditReply. 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. - Error paths never reply unguarded. A reply inside a
catchthrows whenever the interaction is already dead, and that rejection is what crashed the process on 2026-11-03. UsesafeEphemeralReply()(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 —
/signupuses ephemeral reply as primary delivery path - NEVER modify
discordIddirectly in Payload admin — use the/linkcommand or the resolve helper - NEVER fetch the guild member or run
isStaffbeforedeferReplyon 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; usesafeEphemeralReplyso a stale interaction (10062) cannot take the bot down