Skip to main content

Discord: how it works

Discord is a messaging platform; Taji uses it as a channel, a direct message between you and a bot you create, both ways. Taji sends your alerts, trading events and your agent's answers to your Discord DMs, and hears what you type back to the bot. The crate is taji-discord (plugins/discord/), one Channel arm with two halves: REST over https://discord.com/api/v10 for everything out, and the Gateway WebSocket for everything in. It serves no data and places no orders: its trace is one message in and one out.

The vendor​

Hosts and environments. Taji calls one environment, Discord itself; the crate names no other. REST lives at https://discord.com/api, versioned in the path; Taji pins v10, which the API reference lists as available, with v8 to v6 deprecated (API reference, fetched 2026-12-02). The Gateway URL is not fixed: GET /gateway/bot answers it with the bot's session-start budget, and you connect with ?v=10&encoding=json (Gateway, fetched 2026-12-02).

Auth model. An application in the Developer Portal owns a bot user. The bot token comes from the Bot page's Reset Token and is shown once (Getting started, fetched 2026-12-02). Discord also resets it when a bot hits its daily Identify limit (see Constraints). Every REST call but the interaction callback carries Authorization: Bot and the token, and a User-Agent of the form DiscordBot ($url, $versionNumber); Discord may block a request without one (API reference). The Gateway authenticates once per session, with the token in its Identify or Resume payload.

Account and entitlement model. A bot is a user owned by an application. It can DM a person only once it has a DM channel with them: POST /users/@me/channels {recipient_id} creates one or answers the existing one (User, fetched 2026-12-02). Discord refuses with JSON error 50007, "Cannot send messages to this user" (Opcodes and status codes, fetched 2026-12-02); Taji's record is that this happens when you share no server with the bot, which is why the link's install step adds it to one (plugins/discord/taji-plugin.toml). Installing to a server (Guild Install) needs the bot scope and a member with MANAGE_GUILD (Getting started).

The API families Taji calls.

FamilyCallsDoc (fetched 2026-12-02)
UsersGET /users/@me (proves the token); POST /users/@me/channels (Create DM)User
MessagesPOST /channels/{id}/messages: JSON content, embeds, components; or multipart/form-data with payload_json and files[0]Message, uploading files
ChannelsPOST /channels/{id}/typing, a 204; the indicator lasts 10 secondsChannel
Componentsan Action Row (type 1) of Buttons (type 2), styles 2 Secondary, 3 Success, 4 DangerComponents
InteractionsGateway INTERACTION_CREATE of type 3 (MESSAGE_COMPONENT); POST /interactions/{id}/{token}/callback with type 7 (UPDATE_MESSAGE)Receiving and responding
GatewayGET /gateway/bot: url and session_start_limit (total, remaining, reset_after in ms, max_concurrency); Hello (op 10), Identify (op 2), Heartbeat (op 1) and its ACK (op 11), Dispatch (op 0: READY, MESSAGE_CREATE, INTERACTION_CREATE), Resume (op 6), Reconnect (op 7), Invalid Session (op 9)Gateway, Gateway events

The Gateway's protocol, as Discord states it: Hello carries heartbeat_interval in milliseconds; the first heartbeat waits interval × jitter (jitter in 0 to 1), each after that every interval, carrying the last sequence s seen; a missing ACK between two heartbeats marks the connection zombied, to be closed and resumed. READY carries session_id and resume_gateway_url; a resume connects to that URL and sends op 6 {token, session_id, seq}, and Discord replays what you missed. Op 9 with d: true resumes; with d: false you identify afresh. Close codes 4004 and 4010 to 4014 say do not reconnect; 1000 and 1001 invalidate the session (Gateway, close codes).

Intents filter what the Gateway sends. DIRECT_MESSAGES is 1 << 12 (4096). MESSAGE_CONTENT (1 << 15) is privileged, but an app receives content in DMs with itself without it (Gateway). Interactions reach an app either on the Gateway or at an Interactions Endpoint URL, never both (Receiving and responding). A message id is a snowflake whose top bits are milliseconds since the Discord epoch, 1420070400000 (API reference).

The vendor's stated limits. These are under Constraints and limits, with what Taji does about each.

What Taji does not use, and why.

CapabilityWhy not
Server channels, guild messages, GUILD_* intentsTaji reads only your DMs with the bot; the link's brief says it never reads a server's channels (plugins/discord/taji-plugin.toml)
MESSAGE_CONTENTNot needed: DM content arrives without it, so you toggle nothing on the Bot page
An Interactions Endpoint URLTaji's channels take inbound with no public URL; the Gateway carries button presses instead
User InstallNot yet built; whether it drops the shared-server need is unmeasured
Slash commands (application commands)Not yet built; you type taji new as text, and how Discord treats an unregistered /taji new is unmeasured
Components V2 (IS_COMPONENTS_V2), embed colours, a pressed card showing the answer givenNot yet built
Pictures or files you send to the botNot yet built
Editing, deleting or reacting to messages; threads; voiceNot yet built
Gateway compression (zlib-stream, zstd-stream), ETF encoding, shardingNot yet built

Code map​

  • plugins/discord/Cargo.toml: the crate, reqwest with multipart for a picture upload, tokio-tungstenite for the Gateway, wiremock for tests.
  • plugins/discord/taji-plugin.toml: the manifest; its [[link]] is the form discord, its two steps, the token field and the refusal words invalid_key and no_dm.
  • plugins/discord/src/lib.rs: the Discord struct, Plugin (build registers the arm with Build::channel) and Channel; every REST call. Read Discord::call first: it attaches the token and maps every answer to a Failed.
  • plugins/discord/src/gateway.rs: the inbound half. Read Discord::listen, then identify_url (the one place a new session is allowed: Gate), then connection (one socket: Hello, Identify or Resume, heartbeats, the op loop), then direct_message and pressed, the two filters that decide what reaches the kernel.
  • plugins/discord/README.md: the page for the person linking an account.
  • plugins/discord/ui/mark.svg: the plugin's mark.

There is no tests/ directory: every test is a #[cfg(test)] module in the two source files.

How it plugs into Taji​

The trait. Discord implements taji_plugin::channel::Channel (engine/crates/taji-plugin/src/channel.rs); docs/plugins/channel.md is the contract.

MethodDiscord's answer
id, name, fieldsdiscord, Discord, ["token"]
capsinbound: true, images: true, text_limit: 2000, Discord's content limit
markupMarkup::Discord: the kernel renders Markdown into Discord's own markup (engine/crates/taji/src/wire/markup.rs)
linkGET /users/@me; a refusal becomes invalid_key; answers owner: None, so the kernel pairs by code
sendCreate DM on the first send to the owner since the link, then Create Message: JSON for text, multipart with taji.png for a picture
send_framedthe frame's title as content, its body as one embed's description, a button per reply
typingCreate DM if none is open yet, then Trigger Typing
runlisten: the Gateway until a close it cannot resume

It has no FACTS, VenueFacts or OFFER statics, no hub product and no coverage page: those belong to data sources and brokerages. The binary composes it in engine/crates/taji-open/src/lib.rs (.add(taji_discord::Discord::default)), and engine/crates/taji/src/wire/fixture.rs registers it for the wire fixture.

The link form. The manifest has one form, discord, of kind fields in group Channels, with pairs = true; its steps are the manifest's own. The kernel serves it on GET /read/link/forms posting channels/link {"channel":"discord"} (engine/crates/taji/tests/fixtures/wire/link-forms.json), and as the guided flow discord on GET /read/flows, whose last step, pair, is the kernel's.

What the kernel does around the arm. engine/crates/taji/src/wire/channels.rs holds everything stateful; the arm keeps only its Gateway Gate, its owner's DM channel and a 429's hold (see Design).

  • It seals the token under vault record channel_discord; the row reads locked until the vault opens (ADR 0005).
  • It mints the pairing code, eight letters of [a-km-z], void after ten minutes or five other messages, and binds the first sender whose whole message is the code as the owner, in <state dir>/channels.json.
  • It runs the owner rule (owner_rule) on every inbound: anyone else's message is dropped unanswered. Then it drops a message id seen before, answers one older than 120 seconds "Not run: Taji heard this late.", and routes the rest to a card answer, a taji command or the desk's Agent chat.
  • It renders Markdown with render(text, Markup::Discord) and cuts it into pieces of at most 2,000 characters with chunk; a one-piece message with a frame and no image goes by send_framed.
  • It calls typing every 8 seconds while a question waits on the agent, and not while one of its cards waits on you.
  • It reruns run 5 seconds after it ends Unreached; after Refused or a word, the row keeps the error until you link again.
Taji surfaceDiscord call behind itFile
POST /verb/channels/linkGET /users/@meplugins/discord/src/lib.rs link
GET /read/channels row discordnone: the kernel's own stateengine/crates/taji/src/wire/channels.rs
POST /verb/channels/send (text, pane)POST /users/@me/channels (once per link), POST /channels/{id}/messagesplugins/discord/src/lib.rs send
An alert's desk note, an events row, an agent cardthe same two, the second with embeds and componentsplugins/discord/src/lib.rs send_framed
A question pending on the agentPOST /users/@me/channels (once per link), POST /channels/{id}/typingplugins/discord/src/lib.rs typing
Your DM to the botGateway MESSAGE_CREATEplugins/discord/src/gateway.rs direct_message
Your press of a card's buttonGateway INTERACTION_CREATE, then POST /interactions/{id}/{token}/callbackplugins/discord/src/gateway.rs pressed, ack_interaction
POST /verb/channels/unlinknone: the kernel drops the run's future, which closes the socketengine/crates/taji/src/wire/channels.rs

The routes' full contracts are the channels rows of the //! header of engine/crates/taji/src/wire/mod.rs.

One message in, one out. You DM the bot "What is AAPL at?":

  1. Discord dispatches MESSAGE_CREATE on the Gateway socket run holds. Discord::dispatch records its sequence and calls direct_message, which keeps it only with no guild_id, an author that is not a bot and non-empty content, and takes at_utc from the message id's snowflake.
  2. Inbox::heard hands it to Channels::heard: the owner rule passes it, it is new and fresh, it is no card answer and no command, so it becomes Job::Ask on a blocking thread.
  3. Channels::ask asks it on the attached desk's Agent chat (Agent::ask in engine/crates/taji/src/agent.rs) with the mention taji://channel/discord, and starts typing to you.
  4. Each card of the turn goes out by send_framed as buttons; the agent's last message comes back as Said::Answer.
  5. send_to renders it in Markup::Discord, cuts it at 2,000 characters, and calls send once per piece: POST /users/@me/channels with the owner's id as recipient_id if no DM is open yet, then POST /channels/{id}/messages {"content": …}. The row's last_sent_utc moves, and the kernel frames changed channels.

Why it is built this way​

  • Your own bot, by one token. Discord was the channel that proved the seam: one token, a numeric sender the platform authenticates, every OS, nothing unmeasured.
  • The Gateway for inbound. Taji runs on your machine with no public URL, so a webhook-style Interactions Endpoint cannot reach it; a socket the arm opens can. Because Discord delivers interactions on one path or the other, button presses come over the Gateway too.
  • One intent, no privileged one. DIRECT_MESSAGES is all a DM bot needs, and DM content arrives without MESSAGE_CONTENT, so the link asks you to toggle nothing and the bot is never sent a server's messages.
  • Pairing by code, not by token. A bot token says who the bot is, never who you are. The kernel binds the first account that sends the code, and the owner rule is the one guard between a chat account and an agent card that can run a shell (engine/crates/taji/src/wire/channels.rs, its //!). Hence link answers owner: None.
  • Filters before the kernel. direct_message and pressed drop guild traffic and bot authors, so the bot's own sends never come back as your words; engine/crates/taji-plugin/src/channel.rs requires that of every arm.
  • What the arm keeps between calls. Gate, because the kernel reruns run after every Unreached and each rerun would otherwise start a session afresh: the session to resume, when the next Identify may go and its backoff. The owner's DM channel, because Discord warns that opening DMs quickly rate-limits a bot (Constraints): send and typing call Create DM once, then reuse its id. Its Hold (taji_plugin::channel::Hold, every channel's 429 hold): when the next REST call may go after a 429 (Constraints). link forgets the session and the DM channel, so a new token never resumes the old one's session or posts to its DM.
  • One gate on Identify. Discord resets the token at 1,000 Identify calls a day, so identify_url is the one path to a new session: it waits out the backoff, reads session_start_limit from GET /gateway/bot and, at remaining 0, waits reset_after with no socket; a reply naming no reset_after holds nothing, as a 429 naming no seconds holds nothing, and the kernel's 5-second rerun asks GET /gateway/bot again, which sends no Identify. Taji runs one shard, so max_concurrency adds nothing: the 5-second floor of the backoff already keeps to one Identify per 5 seconds. discord.js reads the same object and refuses to connect when remaining is short (WebSocketManager.ts lines 344 to 351), and resumes whenever it holds a session (WebSocketShard.ts lines 317 to 321); Taji waits instead of refusing, because the row should mend itself once Discord's count resets.
  • A frame's title is the message text. The title is what a notification previews on your lock screen, so it goes in content, and the body goes in an embed (plugins/discord/src/lib.rs send_framed).
  • A press strips the buttons. ack_interaction answers type 7 with empty components, taking the buttons off the message as the channel design asks of every arm that draws them; the kernel spends the card's token on its first answer either way. It is spawned at once, inside Discord's 3-second window, after which the interaction token no longer answers (Receiving and responding). A failure is logged, not retried, and the buttons stay: the press already reached the kernel, which spent the card, so a second press answers "No such request." (NO_SUCH in engine/crates/taji/src/wire/channels.rs). The README says so.
  • The kernel renders markup, the arm sends it. Markup::Discord escapes Discord's markers *_~| and the backtick, keeps headings up to ###, fences tables and leaves URLs intact (engine/crates/taji/src/wire/markup.rs, markdown_becomes_discords). One renderer serves every channel; the arm never parses Markdown.
  • Failed carries the kernel's next move. Unreached reruns, Refused waits for you, and a word (invalid_key, no_dm) shows the manifest's sentence on the row and in the link sheet.
  • One base URL for tests. Discord::at(api) overrides REST, and the Gateway URL comes from GET {api}/gateway, so one mock server reroutes both halves.
  • The token never leaves the kernel. It is sealed in the vault, handed to the arm by value, and absent from every read (ADR 0005). A channel is a platform interface any messaging app fills; Slack, WhatsApp, iMessage and the webhook are its other arms (ADR 0004).

Constraints and limits​

The plugin README has no measured ### sections and there is no coverage page: the figures below are Discord's stated limits, fetched 2026-12-02, and Taji's own constants.

Message size. content takes 2,000 characters, which is the arm's text_limit, so the kernel cuts every message to fit. An embed's description takes 4,096 and all embeds of a message 6,000 (Message); the kernel caps a card's title at 100 characters and its body at about 1,200.

Buttons. A row holds up to 5 buttons, a custom_id 1 to 100 characters, a label 80 (Components). A card carries at most three replies, Yes, Always and No, whose custom_id is yes, always or no and five letters.

REST rate limits. Discord sets per-route buckets in X-RateLimit-* headers, a global limit of 50 requests a second per bot, and a 429 body with retry_after; it says to read the headers, never hard-code limits. An IP that draws 10,000 responses of 401, 403 or 429 in 10 minutes is blocked for a time (Rate limits). Discord says to rely on Retry-After or retry_after to know when to retry, and gives Retry-After whole seconds, retry_after a float (rate-limits.mdx lines 49 to 57). The arm reads the Retry-After header into its Hold, as discord.js does (SequentialHandler.ts lines 324 to 337): a 429 is Unreached naming the wait, and until it has passed every later REST call of the arm is Unreached at once, naming the seconds left, with nothing sent. Unlike discord.js, which waits and resends, the arm neither sleeps nor resends: a Retry-After can run to minutes (the docs' global example is 1337 s), which no send or typing tick should block for, and a failed send sets the row's error. It reads no X-RateLimit-* header, so it waits only after a 429. Each send costs one request once the DM is open, and each typing tick one, every 8 seconds while the agent works.

Opening DMs. Discord warns that opening many DMs too quickly can rate-limit or block a bot, and that DMs should follow a user's action (User). The arm opens one DM, with its owner, once per link (user.mdx line 333).

Gateway budgets. A connection may send 120 events every 60 seconds; the arm sends one Identify or Resume and one heartbeat per interval. Identify is limited to 1,000 calls a day (session_start_limit.total), resumes not counted; upon hitting it Discord ends every session, resets the token and emails the owner. max_concurrency Identify calls are allowed per 5 seconds (Gateway, fetched 2026-12-02). The arm resumes whenever it holds a session, across the kernel's reruns of run too. Before each Identify it waits out its backoff, 5 seconds after the last one, doubling to 10 minutes until a session reaches READY, then reads GET /gateway/bot; at remaining 0 it ends Unreached saying how many minutes until reset_after, a field Discord always sends (its name has no ?, the reference's mark of an optional field: gateway.mdx line 782, reference.mdx line 216), which the row shows, and the rerun waits that long before asking again. A reply without it ends Unreached saying Discord named no reset, and holds nothing.

How the socket ends.

Discord saysThe arm
close 4004, 4010 to 4014Refused: the row keeps the error until you link again
close 1000, 1001, 4007, 4009; op 9 d: false; any end before a new session's first dispatchUnreached: the kernel reruns run after 5 seconds, which identifies afresh once the gate allows
a socket that fails to open, or ends before a resumed session's first dispatchUnreached, keeping the session: the rerun resumes it
GET /gateway/bot with remaining 0Unreached naming the wait; no socket until reset_after has passed. With no reset_after, Unreached saying so, and the rerun asks again
after the first dispatch: op 7, op 9 d: true, any other close, a dropped socket or a missed heartbeat ACKresume at resume_gateway_url with the last sequence

Refusals. invalid_key: GET /users/@me answered a 4xx other than 429. no_dm: a REST call answered JSON code 50007. Their sentences are the manifest's [link.refusals].

Order approval. No order is approved from Discord: a phone turn's order follows the account's approvals and waits in the Taji window (Use).

Examples​

The plugin has no tests/fixtures/, tests/live.rs or captured exchange with Discord. Each example below is a request a crate test asserts and the answer its mock gives, shaped as Discord's docs show, except the last, which is the wire fixture; ids and tokens are masked as pN. engine/crates/taji/scripts/channels_walk.py against a real bot is what would capture Discord's own answers.

Prove the token (plugins/discord/src/lib.rs, link_proves_the_token_and_names_no_owner). POST /verb/channels/link {"channel":"discord","token":…} calls:

GET /users/@me
Authorization: Bot p1

The answer, after which the arm returns Linked { secret, owner: None }:

{ "id": "p2", "username": "taji-bot" }

A 401 {"message": "401: Unauthorized"} becomes Failed::Word("invalid_key") (link_with_a_refused_token_is_refused_and_a_dead_host_is_unreached). No capture yet of the kernel's answer for discord; engine/crates/taji/scripts/channels_walk.py <port> link makes one.

Send a text (plugins/discord/src/lib.rs, send_opens_the_dm_then_posts_the_text):

POST /users/@me/channels
Authorization: Bot p1

{ "recipient_id": "p3" }
{ "id": "p4" }
POST /channels/p4/messages
Authorization: Bot p1

{ "content": "hello" }
{ "id": "p5" }

send returns p5, which POST /verb/channels/send answers in {"sent": [...]}.

A card (plugins/discord/src/lib.rs, a_frame_is_an_embed_with_a_button_per_reply). The kernel's frame, title Allow `Bash`?, body ls, three replies, posts:

{
"content": "Allow `Bash`?",
"embeds": [{ "description": "ls" }],
"components": [{
"type": 1,
"components": [
{ "type": 2, "style": 3, "label": "Yes", "custom_id": "yes p6" },
{ "type": 2, "style": 2, "label": "Always", "custom_id": "always p6" },
{ "type": 2, "style": 4, "label": "No", "custom_id": "no p6" }
]
}]
}

An alert with no body and no replies posts {"content": "Time alert: 09:35 ET"} alone.

A picture (send_with_a_picture_is_a_multipart_with_the_png): one multipart/form-data body with a part payload_json, {"content": "AAPL", "attachments": [{"id": 0, "filename": "taji.png"}]}, and a part files[0] of type image/png.

No shared server (send_to_an_owner_who_shares_no_server_is_no_dm): Create DM answers 400 {"code": 50007, "message": "Cannot send messages to this user"}, and send fails with Failed::Word("no_dm").

The Gateway (plugins/discord/src/gateway.rs, identifies_hears_only_a_users_dm_and_resumes_after_a_drop). The server says Hello, and the arm identifies:

{ "op": 10, "d": { "heartbeat_interval": 40 } }
{ "op": 2, "d": { "token": "p1", "intents": 4096, "properties": { "os": "…", "browser": "taji", "device": "taji" } } }

The test asserts op, token and intents; properties is as connection builds it, os the build's std::env::consts::OS. READY names the session; a DM follows:

{ "op": 0, "s": 1, "t": "READY", "d": { "session_id": "p7", "resume_gateway_url": "…" } }
{ "op": 0, "s": 2, "t": "MESSAGE_CREATE", "d": { "id": "p8", "channel_id": "p9", "content": "buy 1", "author": { "id": "p3" } } }

That reaches the kernel as Inbound { id: "p8", sender: "p3", text: "buy 1", at_utc }. A message with guild_id, one whose author has "bot": true and one with empty content are dropped. After the socket drops, the arm reconnects and resumes with the last sequence it saw:

{ "op": 6, "d": { "token": "p1", "session_id": "p7", "seq": 5 } }

A button press (an_owners_press_is_heard_and_the_callback_is_posted):

{ "op": 0, "s": 2, "t": "INTERACTION_CREATE", "d": { "id": "p8", "type": 3, "token": "p10", "user": { "id": "p3" }, "data": { "component_type": 2, "custom_id": "yes p6" } } }

The arm posts POST /interactions/p8/p10/callback with {"type": 7, "data": {"components": []}}, and the kernel hears yes p6 from p3, which answers the card. The same press with a guild_id is ignored.

The link form on the wire (engine/crates/taji/tests/fixtures/wire/link-forms.json, trimmed):

{ "form": "discord", "group": "Channels", "kind": "fields", "pairs": true, "plugin": "discord",
"post": { "body": { "channel": "discord" }, "route": "channels/link" },
"fields": [{ "kind": "secret", "label": "Bot token", "name": "token", … }],
"refusals": { "invalid_key": "…", "no_dm": "…" }, … }

Testing​

Offline, no key. cargo test -p taji-discord runs the eighteen tests in plugins/discord/src/lib.rs and plugins/discord/src/gateway.rs: wiremock stands in for REST, and a local tokio-tungstenite server plays the Gateway (Hello, Identify, Ready, dispatches, a drop, a Resume, close 4004, op 9, an interaction and its callback). a_rerun_after_a_failed_identify_waits_before_identifying_again, no_session_starts_left_waits_out_reset_after_without_identifying and no_session_starts_left_and_no_reset_named_says_so_without_identifying hold the Identify gate; a_429_refuses_every_call_unsent_until_its_retry_after and the_dm_opens_once_per_owner_until_a_new_link hold REST pacing.

The kernel's side runs against fake arms:

  • cargo test -p taji --lib -- channels: the owner rule (only_the_owner_reaches_the_agent), pairing, cards, typing, alerts, cutting.
  • cargo test -p taji --lib -- markup: markdown_becomes_discords.
  • cargo test -p taji --lib -- agent: a question asked with origin discord.

cargo test -p taji-open --test routes checks that discord is among the compiled plugins.

Live. The crate has no tests/live.rs. engine/crates/taji/scripts/channels_walk.py <port> link|alert|ask|card|order|command|fill|burst walks a real bot against a headless kernel you started (AGENTS.md, Run) and your own phone, and prints PASS/FAIL checkpoints; its exit code is the FAIL count. It needs TAJI_STATE_DIR set to that kernel's, DISCORD_BOT_TOKEN (never printed), GATE_VAULT_PASSWORD to seal or open the vault, and for ask onward an agent conversation opened once in Taji's window. order uses a paper row and is refused while any live row is linked. fill and burst need Alpaca paper and run in regular US equity hours only. The script's header lists each step's needs. Run it only against a kernel you started, never your own Taji.

References​

All fetched 2026-12-02.