# 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), `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) 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) 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/ 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. 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: 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 (leaders also get a "rate your subordinates" section). 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 \. 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 `` 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 by `discord:rp:update`) with `action=view|edit|clear`. `edit` opens 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. `clear` disables + blanks every field. Modal submit routes through `bot/index.ts` on the `ptf-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/.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` | ## 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