# Discord

A Discord bot's back end: messages with embeds, buttons and selects,
channels and threads, a server's members and roles, webhooks, and slash
commands registered, over Discord's HTTP API (v10); and Discord's
Interactions Endpoint (commands, buttons, selects, modals, autocomplete) as
one route that checks Discord's Ed25519 signature, answers within its three
seconds, and does deferred work in a [job](back-end.md#later-job-fn). An
[extension](../extensions/README.md): `extensions/discord/`. A line to a
channel through a webhook alone is [alert](alert.md). Back to the
[map](README.md).

```mote
use "pkg:discord/interactions.mote"

server start
  discordRegister([discordSlash("deploy", "Ship a build", [discordOptionOf("string", "build", "Which build", true)]), discordSlash("ping", "Is it there?", [])], "", "") else err => log.warn("discord: commands not registered", {why: `${err}`})

// /ping is answered at once; /deploy says "thinking…", and its job's message takes its place.
fn discordCommandNow(i: DiscordInteraction): DiscordAnswer
  if i.name == "ping" return discordReplyNow({content: "pong", hidden: true})
  return discordDefer(false)

fn discordCommand(i: DiscordInteraction): DiscordOut
  let build = `${i.options.build}`
  shipIt(build)?
  return {content: `Deployed ${build}`, embeds: [{...discordEmbed("Deploy", build), color: 0x57f287}], components: [discordRow([discordButton("Roll back", `rollback:${build}`, "danger")])]}

// The button: the message it was on, changed.
fn discordComponent(i: DiscordInteraction): DiscordOut
  rollBack(i.name.split(":")[1])?
  return {content: `Rolled back by ${i.user.name}`, components: []}
```

```sh
DISCORD_BOT_TOKEN=… DISCORD_APP_ID=… DISCORD_PUBLIC_KEY=… bun dist/server/main.js
```

**Not met Discord.** Written from Discord's API reference as of 2026 and run
against a stand-in (`tests/svc_standin.mjs chat`). Ed25519 is the back
end's own `crypto.verify(…, {alg: "EdDSA"})`, checked against the three
test vectors of RFC 8032 (section 7.1, both signing and checking); the
stand-in run signs interactions with the first of them. The steps to check
it with a real bot are [below](#checking-it-against-discord).

## The settings

| | |
|---|---|
| `DISCORD_BOT_TOKEN` | Bot → Reset Token, a [secret](back-end.md#secrets). Every call takes a `token`: `""` for the bot, or `"Bearer …"` (a person's OAuth token, for the calls Discord lets one make; getting it is not this extension's). |
| `DISCORD_APP_ID` | General Information → Application ID: commands and interaction replies use it. |
| `DISCORD_PUBLIC_KEY` | General Information → Public Key: 64 hex digits. Not a secret. |
| `DISCORD_WAIT` | The longest a limit is waited out, in seconds: 30 unsaid. |
| `DISCORD_TOLERANCE` | How far an interaction's timestamp may be from now, in seconds: 300 unsaid. |
| `DISCORD_API` | Another address for the API (a stand-in). |

At discord.com/developers: General Information → Interactions Endpoint URL
`<site>/discord/interactions` (Discord sends a PING and a wrongly signed
request when it is saved, and keeps the address only if the first is
answered and the second refused: the route does both). Installation → the
`bot` and `applications.commands` scopes, with the permissions the calls
need (Send Messages, Embed Links, Attach Files, Add Reactions, Create
Public Threads, Manage Roles); Bot → Server Members Intent for
`discordMembers`.

## The calls

`use "pkg:discord/discord.mote"` (`interactions.mote` takes it). Each is
the back end's, can fail, and takes the `token` last.

| | |
|---|---|
| `discordPost(channel, m, token)` · `discordSay(channel, text, token)` | A message: a `DiscordMessage` (`id`, `channel`, `content`, `author`, `at`, `edited`, `embeds`, `components`, `attachments`, `webhook`). |
| `discordReplyTo(channel, id, m, token)` · `discordEdit(…)` · `discordDelete(channel, id, token)` | |
| `discordReact(channel, id, "👍", token)` | A server's own emoji as `"name:id"`. |
| `discordMessages(channel, before, limit, token)` | A page, newest first; the next is before the last one's id. |
| `discordDm(user, m, token)` | To a person, in their DM with the bot. |
| `discordChannel(id, token)` · `discordChannels(guild, token)` · `discordThread(channel, message, name, minutes, token)` | `DiscordChannel`: `id`, `type`, `name`, `guild`, `parent`, `topic`, `position`. |
| `discordMember(guild, user, token)` · `discordMembers(guild, after, limit, token)` · `discordAllMembers(guild, most, token)` | `DiscordMember`: `user`, `nick`, `roles`, `joined`. A page is those after an id. |
| `discordRoles(guild, token)` · `discordAddRole(guild, user, role, reason, token)` · `discordRemoveRole(…)` | `reason` goes in the server's audit log. |
| `discordWebhook(address, m)` | Through a channel's webhook (its whole address is its secret), waited for and given back. |
| `discordRegister(commands, guild, token)` | The application's commands made exactly these (Discord's bulk overwrite, safe at every start). `guild` `""`: everywhere; a server's id: there only, at once (for trying them). |
| `discordEditReply(token, m)` · `discordFollowUp(token, m)` | After an interaction (its token, fifteen minutes): its first answer changed, or another message. |
| `discordSend(method, path, body, multipart, token, reason)` | Any other request, through the same limits. |

A message to send is a `DiscordOut`: `content`, `embeds`, `components`,
`files` (`{name, data, type?}`: sent as parts, `payload_json` and
`files[n]`), `reply` (the id it answers), `hidden` (only the person, in an
interaction's answer), `quiet` (no link embeds), `mentions`, `username` and
`avatar_url` (a webhook's). **Nobody is pinged unless `mentions` says who
may be** (`["users"]`, `["roles"]`, `["everyone"]`): a bot that repeats what
someone typed does not ping @everyone.

Shapes with Discord's own field names, and fns that make them:
`discordEmbed(title, description)` (a `DiscordEmbed`: `color`, `fields`,
`footer`, `author`, `image`, `thumbnail`, `timestamp`, `url`),
`discordField(name, value, inline)`, `discordRow([components])`,
`discordButton(label, id, style)` (`"primary"`, `"secondary"`, `"success"`,
`"danger"`), `discordLinkButton(label, url)`, `discordSelect(id,
placeholder, [discordOption(label, value)…])`, `discordTextInput(id,
label, long, required)`, `discordModal(id, title, rows)`;
`discordSlash(name, description, options)` and `discordOptionOf(kind,
name, description, required)` (`"string"`, `"integer"`, `"number"`,
`"boolean"`, `"user"`, `"channel"`, `"role"`, `"attachment"`,
`"subcommand"`) for commands.

**Failures** say Discord's message (`Discord refused POST
/channels/1/messages: Missing Permissions`), with a kind: `"auth"`,
`"refused"` (403), `"missing"`, `"invalid"` (`data.errors` says which
field), `"limited"`, `"discord"`, `"offline"`; `data.code` is Discord's JSON
error code (`50013`).

**Limits.** Each route (its method and path, per channel, server or
webhook) has a bucket; each answer says what is left of it
(`X-RateLimit-Remaining`) and when it is full again
(`X-RateLimit-Reset-After`). A bucket that is spent is kept (the
`DiscordBucket` model) and waited out before its route is asked again, by
every caller; the others go on. A 429 says how long (`retry_after`) and
whether the limit is the bot's global one (50 a second): that is kept as
the global bucket, which every route waits for. A 429 is waited out and
asked again, twice at most; a wait longer than `DISCORD_WAIT` is a failure
of kind `"limited"` with `data.retryAfter`.

## The Interactions Endpoint

`use "pkg:discord/interactions.mote"`: `POST /discord/interactions` checks
`X-Signature-Ed25519` (Discord's signature of `X-Signature-Timestamp` and
the body) under `DISCORD_PUBLIC_KEY` first, and refuses a timestamp more
than five minutes away. A PING is answered; the rest go to the program's
hooks, each optional:

| | |
|---|---|
| `fn discordCommandNow(i): DiscordAnswer` | In the answer: `discordReplyNow(m)`, `discordOpenModal(modal)`, or `discordDefer(hidden)` (unsaid: deferred, "thinking…", seen by all). |
| `fn discordCommand(i): DiscordOut` | In a job, when deferred: the message that takes the place of "thinking…". If it fails, its words do. |
| `fn discordComponentNow(i): DiscordAnswer` | A button, a select, a modal submitted: `discordUpdateNow(m)` (the message it was on, changed), a message, a modal, or deferred (unsaid). |
| `fn discordComponent(i): DiscordOut` | In a job, when deferred: the message it was on, changed; nothing in it, left as it was; `hidden`, a new message only the person sees. |
| `fn discordAutocomplete(i): DiscordChoice[]` | In the answer: the choices for what is being typed (`i.focused`, `i.typed`), 25 at most. |

A `DiscordInteraction` is `id`, `type` (`"command"`, `"component"`,
`"modal"`, `"autocomplete"`), `name` (a command's, with its subcommand:
`"deploy prod"`; a component's or a modal's custom_id), `options` (by
name), `values` (a select's), `fields` (a modal's, by custom_id), `user`,
`roles`, `guild`, `channel`, `message`, `locale`, `token`, and `raw`.

`discordVerify(signature, timestamp, body, key)` is the check by itself,
and `discordKeyOf(hex)` the public key as the JWK that `crypto.verify`
takes.

## Left out

- **The Gateway** (a WebSocket: messages as they are posted, presence,
  voice): the back end's WebSocket client is there now
  ([`ws.open`](back-end.md#connections-of-its-own)); what remains is the
  Gateway's protocol on it (identify, heartbeats, resume, intents, shards). A bot here hears
  people through interactions, which is what Discord recommends for
  commands; reading every message of a channel needs the Gateway.
- OAuth (adding the bot, a person's token): another extension's.
- Voice, stickers, scheduled events, auto-moderation, forum tags,
  application emoji, monetization (SKUs, entitlements), the newer
  "components v2" layouts.

## Checking it against Discord

1. A new application at discord.com/developers; under Bot, reset the token
   (`DISCORD_BOT_TOKEN`); `DISCORD_APP_ID` and `DISCORD_PUBLIC_KEY` from
   General Information. Invite it to a server of your own with the `bot`
   and `applications.commands` scopes (Installation → the install link).
2. Run the program where Discord reaches it (a tunnel), and save
   `<site>/discord/interactions` as the Interactions Endpoint URL: Discord
   saves it only if the signature check is right.
3. `discordRegister([…], "<your server's id>", "")`: the commands show in
   that server at once. `/ping` answers; `/deploy` shows "thinking…", then
   the job's message; its button changes it.
4. `discordSay("<channel id>", "hello", "")`: the message shows. Without
   Send Messages in that channel, the failure is `Missing Permissions`,
   kind `"refused"`, code 50013.
5. Many messages to one channel at once (twenty from a job): none fails;
   the log shows no 429 after the first wait.

Recorded in `tests/expect/real_svc_chat.txt` (`tests/all.sh real_svc_chat`):
a PING, and requests unsigned, signed for another body and old refused; a
command answered at once, one with a modal, one deferred and its message
from the job; autocomplete; a button and a modal submitted; commands
registered; a spent bucket waited out; a global 429 waited out; members in
two pages; a file as parts; a webhook; a refusal's words; and the
extension's own `mote test`.
