Skip to content

feat: Discord bot core: connects only when configured, settings tab and Users page link field - #618

Draft
kikootwo wants to merge 7 commits into
mainfrom
reland/231-discord-bot-core
Draft

kikootwo wants to merge 7 commits into
mainfrom
reland/231-discord-bot-core

Conversation

@kikootwo

@kikootwo kikootwo commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

What changed

  • An optional Discord bot. It connects only when an admin turns it on with a bot token and a server ID (Settings → Discord). It has no commands yet: later parts add /request, request cards, /status, Cancel and /delete.
  • Nothing changes for installs that don't configure it. With the bot off, RMAB never loads discord.js and never opens a connection to Discord. App start logs one line (Discord bot not started) and that is all.
  • Lifecycle (src/lib/services/discord/discord-bot.service.ts): started from app init in the background, never waited on, so a slow or unreachable Discord never delays startup. A failed login logs Failed to start the Discord bot, shows the reason on the tab, and never throws. Saving the settings restarts the bot; turning it off stops it.
    • One gateway session per process: a client from an earlier start is destroyed before a new one logs in, and events from a replaced client are ignored.
    • A gateway that closes for good (for example after a token reset) marks the bot failed on the tab. It is not retried on its own; saving the settings again restarts it.
    • Shutdown stops the bot alongside the job drain (at most 0.4 s), without loading discord.js when the bot never ran.
    • Client: Guilds intent only (no privileged intents), allowedMentions: { parse: [] }, error/shardError listeners.
    • On connect it overwrites the server's slash commands with the current list (empty), which also clears commands left by an older build. The tab and the docs say to use an application made only for RMAB, with Public Bot off.
    • Interactions from other servers are dropped. Commands, autocomplete and modals must come from the configured server; from a DM only buttons and menus are accepted.
  • src/lib/services/discord/discord-runtime.ts is the only Discord module core code imports. A unit test walks the import graphs (static imports, import() and require()) of the request accept/deny, cancel and delete routes, their services, app init and the shutdown coordinator, and fails if discord.js or the bot module appears.
  • Settings → Discord tab: enable switch, bot token (stored encrypted, never sent back: the form shows a mask), server ID, request channel, admin role, admin notification channel, a status pill, Test and Save.
    • Opening the tab makes one call, to RMAB. Discord is contacted only when the admin clicks Test.
    • If that call fails, the tab shows an error and Retry instead of the form, so an empty form can never be saved over the stored settings.
    • Token rule on save: an empty field or the mask keeps the saved token, a new value replaces it, and only clearing a saved token on purpose removes it (clearBotToken). A leading Bot or Bearer is dropped on save and on Test.
    • After Save the tab checks the status a few times so it shows Online or the reason it failed.
    • Test checks the token and IDs against Discord (10 s timeout per call, no retries; a Discord rate limit answers at once with "try again in a minute") and returns the bot's name, its servers, the names of the channels and role, warnings, and an invite link with fixed permissions 84992 (View Channels, Send Messages, Embed Links, Read Message History; never Administrator).
    • IDs are checked (15 to 20 digits) before anything is sent.
  • Users page: when the bot is configured, each user's permissions dialog has a Discord user ID field (it saves through the link route from feat: link a Discord user ID to an account (groundwork for the Discord bot) #612), and a linked user shows Discord: <id> under their name. Without a configured bot the page is unchanged.
  • New routes (admin session only; not on the API-token allowlist): GET/PUT /api/admin/settings/discord, POST /api/admin/settings/test-discord.
  • Request cards default to DMs (discord.request_card_mode reads dm when unset). The setting has no control on the tab yet; it arrives with the cards.
  • Docs: documentation/integrations/discord-bot.md (new), settings pages, admin dashboard, scheduler, auth, table of contents, e2e harness.

Why

Part 2 of 5 of #231 by @NichCodes, rebuilt on current main. Thanks to NichCodes for the design: the bot service, the settings tab with a connection test and invite link, and the account link on the Users page all follow #231. This part covers the bot-core commits of #231: d5234a1, dc8bdf1, dfcb19e, 829ef04, 489f027, 3db5f10, 555b22d, 54344f6, 4fac28f and b985049. Changes from #231:

  • discord.js loads only after the settings say the bot is configured, and app init does not wait for it.
  • The settings save is one transaction, and the token never leaves the server once saved.
  • The Discord settings have their own route instead of a section in the main settings call.

Dependency

  • discord.js 14.28.1, exact (no caret).
  • Not 14.28.0: it is deprecated upstream for a fix to channel permission resolution (discord.js PR 11680).
  • The lockfile was resolved with npm install --save-exact --before=2026-11-04 (npm 11, the major that wrote main's lockfile, so no unrelated fields change). Every added entry is therefore at least 14 days old on 2026-11-18. It avoided the newer ws 8.23.0 and discord-api-types 0.38.59.
  • No package in the tree has an install script.

Lockfile diff (checked by script against main: 21 added, 0 removed, 2 changed; every added entry resolves from registry.npmjs.org with an integrity hash):

Package Version
discord.js 14.28.1
@discordjs/builders 1.15.0
@discordjs/collection 1.5.3 (+ 2.1.1 nested in @discordjs/rest and @discordjs/ws)
@discordjs/formatters 0.6.2
@discordjs/rest 2.6.3
@discordjs/util 1.2.0
@discordjs/ws 1.2.3
@sapphire/async-queue 1.5.5
@sapphire/shapeshift 4.0.0
@sapphire/snowflake 3.5.5
@types/ws 8.18.2
@vladfrangu/async_event_emitter 2.4.7
discord-api-types 0.38.57
undici 6.29.1 (nested in discord.js and @discordjs/rest; main's top-level 7.30.1 is unchanged)
lodash.snakecase 4.1.1
magic-bytes.js 1.13.1
ts-mixer 6.0.4
ws 8.22.1

Changed: the root dependencies gain discord.js; fast-deep-equal 3.1.3 loses its dev flag (now also a runtime dependency), with no version change.

Publishers (npm usernames):

Packages Published by Provenance
discord.js, @discordjs/* crawl yes (except @discordjs/collection 1.5.3)
@sapphire/async-queue, @sapphire/snowflake, @vladfrangu/async_event_emitter vladfrangu no
@sapphire/shapeshift favna no
@types/ws types no
discord-api-types GitHub Actions yes
undici GitHub Actions yes
lodash.snakecase jdalton no
magic-bytes.js larskoelpin no
ts-mixer tannerntannern no
ws lpinca no

Audit: npm audit --omit=dev reports the same 9 advisories on main and on this branch, all in packages already on main. None is in a package this PR adds. Both nested undici copies are 6.29.1 and ws is 8.22.1, at or above every published fix. GitHub lists no advisories for discord.js, @discordjs/rest or @discordjs/ws.

Image size: 2,043,060,510 bytes against 2,037,965,105 for main (+5.1 MB, +0.25%). docker run --rm --entrypoint node <image> -e "import('discord.js').then(m=>console.log(typeof m.Client))" prints function, so the standalone build ships discord.js.

Checks

  • New unit tests, written first and failing before the code (53 failed on the base): bot lifecycle (start, failure, restart, superseded starts, listeners, client options, command overwrite), config, the interaction router, the import-graph check, both new routes, init not waiting on the bot, the Discord tab, and the Users page field.
  • More tests for the settings token rule, the load error, one gateway session, a gateway closed for good, rate limits, the token prefix, the DM rule, the shutdown step and the status re-check (26 more, each failing on the earlier commit of this branch).
  • npm run test: 653 files, 12032 passed, 9 skipped, 0 failed (local, before the last commit, which adds 2 tests: the route and tab test files pass 32/32). CI on the head: 663 files, 12120 passed, 3 skipped.
  • npx tsc --noEmit and npx tsc -p e2e --noEmit: clean. ESLint on the changed files: no new findings (the remaining ones are on main already).
  • npm run e2e:selftest: 81/81 (includes the new sinkhole tests: SNI recorded from a TLS hello, empty host for plain TCP).
  • docker compose build readmeabook exits 0 (the compose file's build section is commented out, so it builds nothing); the image itself was built from dockerfile.unified as above.
  • e2e, the new fake-arr sinkhole: every connection RMAB makes to discord.com, gateway.discord.gg, cdn.discordapp.com or discordapp.com lands on fake-arr :443 and is recorded with its TLS server name. The spec 231-zero-footprint ran on this branch and on main, and again on the branch after the settings and lifecycle fixes with the same results:
    • Bot never configured (branch): 0 sinkhole records; the log has Discord bot not started once and no other Discord line; no discord_user_id set; the Users page dialog has no Discord field (1280 light, 375 dark).
    • The same flows on both images give identical answers: accept from the dashboard card and over the API (200, waits for release), deny (200, then 400 on a second deny), cancel by PATCH and by POST /cancel (200), admin delete (200, then 404).
    • Startup init (Initializing application services... to the init route's 200): 4259 ms on the branch, 4260 ms on main.
    • Fake token and server ID saved through the settings API: 4 sinkhole records, all with server name discord.com; the tab shows "Could not connect"; Failed to start the Discord bot is logged; the token is stored encrypted and appears nowhere in the whole RMAB log; accepting a request on the web still answers 200; the Users page shows the field and the Discord: <id> line.
    • Turned off with the token kept: no new record in the next 15 s, status "Not running". Opening Settings → Discord at 1280 light and 375 dark with the token saved and the bot off: 0 records. With the settings call failing, the tab shows Retry and no Save or Test, and the token stays saved.
  • e2e smoke with default flags: passed on the first branch image, before the settings and lifecycle fixes (request, grab, download, organize, in the library); its log has the single Discord bot not started line and no sinkhole record.

Screenshots

From the test stack (fake token and made-up IDs; Discord hosts go to the local sinkhole).

Discord tab at 1280 px, light: bot on with a fake token, status Could not connect Discord tab at 375 px, dark: token saved, bot off

Discord tab when the saved settings fail to load: error and Retry, no form Users page with the bot configured: Discord line and the Discord user ID field

Risk and rollback

  • Off by default. An install that never opens the Discord tab runs the same code paths as before, apart from one log line at start.
  • To stop the bot: Settings → Discord → turn it off → Save. The token stays saved (encrypted). Clearing the token field and saving removes it.
  • Downgrade: an older image ignores the discord.* settings, so the bot is simply gone. Turn the bot off first so the old and new images never both use the token. No schema change in this PR.
  • One RMAB server per bot token: two servers on one token would both answer.

To try it with a real bot

  1. In the Discord Developer Portal, create an application, add a bot, and copy its token (Bot → Reset Token). No privileged intents are needed.
  2. In Discord, turn on Developer Mode (User Settings → Advanced), then right-click your server → Copy Server ID.
  3. In RMAB, open Settings → Discord, paste the token and the server ID, click Test. Expect the bot's name, a warning that it is not in the server yet, and an invite link.
  4. Open the invite link and add the bot to the server. Click Test again: the warning is gone and the server name shows.
  5. Optionally fill in a channel ID and a role ID and click Test: their names show; a wrong ID shows "was not found in this server".
  6. Turn on the switch and click Save. The pill reads "Online as " within a few seconds, and the bot shows online in the server. It has no slash commands yet.
  7. Open the Users page, open a user's permissions, paste their Discord user ID and save: the row shows Discord: <id>.
  8. Turn the switch off and save: the bot goes offline.
  9. Save a wrong token with the switch on: the pill reads "Could not connect" and the reason shows on the tab.

🤖 Generated with Claude Code

kikootwo and others added 7 commits November 15, 2026 20:39
The bot connects only when an admin enables it with a token and a server
ID; it registers no commands yet. Installs that never configure Discord
load no Discord code and make no Discord connection.

- discord.js 14.28.1 (exact), loaded with import() only after the
  settings say the bot is configured, once per process
- Bot lifecycle: one client per process, start/stop/restart safe to
  interleave (generation counter), Guilds intent only, no mentions
  parsed by default, client error and shardError listeners, interactions
  from other servers ignored, an empty command list registered per server
- Startup starts the bot in the background; init never waits for Discord
- Running-check facade (discord-runtime) for core code: no import while
  the bot is off, never throws or blocks its caller
- Settings: GET/PUT /api/admin/settings/discord (token encrypted and
  masked, one transaction, bot restarted in the background) and
  POST /api/admin/settings/test-discord (bot identity, servers, names for
  the entered IDs, invite link with permissions 84992); IDs validated as
  snowflakes, Discord paths built with Routes
- Discord settings tab: reads RMAB's saved settings on load; Discord is
  contacted only on Test
- Users page: a Discord user ID field (link, unlink) and the linked ID,
  shown only when the bot is configured

Builds on the original #231 commits d5234a1, dc8bdf1, dfcb19e, 829ef04,
489f027, 3db5f10, 555b22d, 54344f6, 4fac28f and b985049 by NichCodes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: NichCodes <90598280+NichCodes@users.noreply.github.com>
…rint spec

- documentation/integrations/discord-bot.md: settings keys, lifecycle, router, API, UI, build, downgrade
- fake-arr :443 sinkhole records each connection's TLS SNI; the stack aliases send discord.com,
  gateway.discord.gg, cdn.discordapp.com and discordapp.com there
- 231-zero-footprint.spec.ts: bot off = no Discord connection and web flows unchanged; a fake token
  reaches the sinkhole; disabled = silent again

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ate in effects

- useDiscordSettings: one GET on mount in a promise chain (ignored after unmount); the Test body
  lists its five fields; the unused reload is gone
- DiscordAccountField: keyed by user and saved ID instead of an effect that reset its state
- tests: no explicit any

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ole)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…bounded Test

- Discord tab: a failed settings load shows an error with Retry; Test and Save stay
  off until a load works. After a Save that enables the bot, the status is read up to
  5 times (1 s apart) until running or failed. Editing an ID or the token clears the
  last Test result. Help text says Test still reaches Discord while the bot is off,
  and asks for an application made only for RMAB with Public Bot off.
- Settings PUT: the mask or '' keeps the saved token; only clearBotToken: true
  removes it. A pasted "Bot " / "Bearer " prefix is dropped on save and on Test.
- Bot service: a start destroys a client left by an earlier start before logging in;
  interactions from a superseded client are ignored. Invalidated, or a shard closed
  for good (e.g. 4004), sets status failed, clears the running flag and destroys the
  client (no automatic retry).
- Test REST client: a 429 fails at once with a fixed message (429); no sweeper timers;
  no server lookup when the server list already has it; "not in this server" only on
  403/404, otherwise "could not check the server".
- Interaction router: from a DM only buttons and select menus pass.
- Shutdown: the coordinator stops the bot (peeked state, never loads discord.js)
  alongside the drain, within one step limit.
- One shared snowflake check for the tab, the Users page field and the actor resolver.
- Zero-footprint import walk also follows require() and plain template-literal imports,
  and covers the shutdown coordinator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g token check

- discord-bot.md: dedicated application with Public Bot off (connecting replaces its
  server commands), clearBotToken, 429 / sweepers / server lookup, DM rule, gateway
  closed for good, shutdown stop, the shared ID check
- settings-pages.md, unified.md: load error + Retry, status re-reads, bot stop step
- 231 e2e run B: the fake token must be absent from the whole RMAB log; the tab with a
  failing settings GET shows Retry and no Save or Test (screenshots); cleanup clears
  the token with clearBotToken

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The settings PUT clears the saved token only when clearBotToken is true and botToken
is '' or the mask; a new value is saved even when clearBotToken is set. Tests: the
route saves the new token, and the tab never sends clearBotToken with a typed token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant