chat / adapter-discord
AGENTS.md2.4k starsChanged 59 days agoMITView on GitHub
Guidance for coding agents working inside the Discord adapter package. The top-level repository AGENTS.md covers monorepo-wide build, lint, and release rules — read it first. This file documents the adapter-specific surface, conventions, and pitfalls. @chat-adapter/discord connects a Chat SDK bot to a Discord guild via HTTP interactions and the Discord Gateway. It covers: - HTTP webhook endpoint at /api/webhooks/discord for slash commands, message components (buttons / selects), and modal submissions. - Gateway transport (websocket) that listens for MESSAGE_CREATE, MESSAGE_UPDATE, MESSAGE_DELETE,…
- Reads credentials
Trending
Quiet since March.thin dataabout the whole repository
Who's talking about vercel/chat
- @camilleroux.com“Un SDK TypeScript unifié pour créer des chatbots qui fonctionnent sur Slack, Teams, Google Chat, Discord, …”Bluesky · Mar 3, 2026 · 3 likes
- @technews4869.bsky.social“github.com/vercel/chat GitHub - vercel/chat: A unified TypeScript SDK for building chat bots across Slack, …”Bluesky · Mar 7, 2026 · 1 likes
- @yug1224.com“チャットアプリ開発に使える統一SDKを提供するツールらしい 様々なプラットフォーム対応で便利そうだな yug1224 starred vercel/chat https://github.com/vercel/chat”Bluesky · Mar 7, 2026 · 1 likes
- @news.humancoders.com“Vercel lance Chat SDK : un SDK TypeScript unifié pour créer des bots multi-plateformes”Bluesky · Mar 5, 2026 · 1 likes
- @github-trending-js.bsky.social“🔥 Hot Repo! 🔥 (100+ new stars) 📦 vercel / chat ⭐ 871 (+121) 🗒 TypeScript A unified TypeScript SDK for …”Bluesky · Feb 27, 2026 · 1 likes
The biggest 5 of 5 mentions linking to the repository that our crawl found. Each line is their own headline.
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository44 other files it gives its agents.
- AGENTS.mdAGENTS.md
- apps/docs/AGENTS.mdAGENTS.md
- chat-sdkAGENTS.md
- packages/adapter-gchat/AGENTS.mdAGENTS.md
- packages/adapter-github/AGENTS.mdAGENTS.md
- packages/adapter-instagram/AGENTS.mdAGENTS.md
- packages/adapter-linear/AGENTS.mdAGENTS.md
- packages/adapter-messenger/AGENTS.mdAGENTS.md
- packages/adapter-notion/AGENTS.mdAGENTS.md
- packages/adapter-slack/AGENTS.mdAGENTS.md
- packages/adapter-teams/AGENTS.mdAGENTS.md
- packages/adapter-telegram/AGENTS.mdAGENTS.md
- packages/adapter-web/AGENTS.mdAGENTS.md
- packages/adapter-whatsapp/AGENTS.mdAGENTS.md
- packages/chat/src/adapters/AGENTS.mdAGENTS.md
- packages/create-chat-sdk/AGENTS.mdAGENTS.md
- packages/create-chat-sdk/_template/AGENTS.mdAGENTS.md
- packages/state-ioredis/AGENTS.mdAGENTS.md
- packages/state-memory/AGENTS.mdAGENTS.md
- packages/state-pg/AGENTS.mdAGENTS.md
- packages/state-redis/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- packages/adapter-discord/CLAUDE.mdCLAUDE.md
- packages/adapter-gchat/CLAUDE.mdCLAUDE.md
- packages/adapter-github/CLAUDE.mdCLAUDE.md
- packages/adapter-linear/CLAUDE.mdCLAUDE.md
- packages/adapter-messenger/CLAUDE.mdCLAUDE.md
- packages/adapter-slack/CLAUDE.mdCLAUDE.md
- packages/adapter-teams/CLAUDE.mdCLAUDE.md
- packages/adapter-telegram/CLAUDE.mdCLAUDE.md
- packages/adapter-web/CLAUDE.mdCLAUDE.md
- packages/adapter-whatsapp/CLAUDE.mdCLAUDE.md
- packages/create-chat-sdk/CLAUDE.mdCLAUDE.md
- packages/create-chat-sdk/_template/CLAUDE.mdCLAUDE.md
- packages/state-ioredis/CLAUDE.mdCLAUDE.md
- packages/state-memory/CLAUDE.mdCLAUDE.md
- packages/state-pg/CLAUDE.mdCLAUDE.md
- packages/state-redis/CLAUDE.mdCLAUDE.md
- add-adapterSkill
- technical-writerSkill
- chat-sdkSkill
- chat-sdkSkill
- chat-sdkSkill
- chat-sdkSkill
The file
We split this AGENTS.md into the rules it gives an agent
4 rules. About 1 is common, 1 is distinctive, and 2 are very specific to this project.
≈1
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 217
Reactions are unicode-or-custom: Use :emoji_name:id for custom emoji.
- Very specific: line 234
When you add a new interaction type, capture a fresh fixture in sample-messages.md and extend the parser tests.
- Distinctive: line 239
Use named exports throughout.
- Common: line 246
Avoid storing the bot token in instance state — pass it explicitly to fetch helpers so testing can stub the credentials path.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md — @chat-adapter/discord
Guidance for coding agents working inside the Discord adapter package. The top-level repository AGENTS.md covers monorepo-wide build, lint, and release rules — read it first. This file documents the adapter-specific surface, conventions, and pitfalls.
Overview
@chat-adapter/discord connects a Chat SDK bot to a Discord guild via
HTTP interactions and the Discord Gateway. It covers:
- HTTP webhook endpoint at
/api/webhooks/discordfor slash commands, message components (buttons / selects), and modal submissions. - Gateway transport (websocket) that listens for
MESSAGE_CREATE,MESSAGE_UPDATE,MESSAGE_DELETE,MESSAGE_REACTION_ADD, etc., so the bot can react to ordinary chat messages — slash commands alone don't expose them. - Embeds rendering for cards (Discord has no native card primitive, but embeds are the closest analogue).
- Slash commands, components, and modals via the Interactions API.
- Threaded replies, DM channels, and bulk message fetches.
Both transports run side-by-side: HTTP for interactions (low latency, public endpoint required), Gateway for everything else (no public endpoint required, but a long-running connection is needed — see Gateway forwarding for serverless).
Directory layout
packages/adapter-discord/
├── src/
│ ├── index.ts # DiscordAdapter + createDiscordAdapter
│ ├── index.test.ts
│ ├── cards.ts # PostableMessage / Card → Embed payload
│ ├── cards.test.ts
│ ├── gateway.ts # WebSocket gateway client + forwarder
│ ├── gateway.test.ts
│ ├── markdown.ts # DiscordFormatConverter (mdast ↔ Discord MD)
│ ├── markdown.test.ts
│ └── types.ts # Discord API typings (raw)
├── sample-messages.md # captured webhook + gateway events
├── package.json
├── tsconfig.json
├── tsup.config.ts
├── vitest.config.ts
└── README.mdgateway.ts includes the serverless forwarding path — a transient
WebSocket listener that ACKs gateway events and forwards them as HTTP
requests to your existing webhook endpoint, so a single handler covers
both transports.
Build, test, typecheck
pnpm build
pnpm dev
pnpm test
pnpm test:watch
pnpm typecheck
pnpm clean
# from repo root
pnpm --filter @chat-adapter/discord build
pnpm --filter @chat-adapter/discord testReplay tests for Discord live in
packages/integration-tests/src/replay-discord.test.ts and consume
captured fixtures.
Public surface
Main exports from src/index.ts:
createDiscordAdapter(config?)— primary factory. Auto-detectsDISCORD_BOT_TOKEN,DISCORD_PUBLIC_KEY,DISCORD_APPLICATION_ID, and (optionally)DISCORD_GATEWAY_FORWARDING_SECRET.DiscordAdapterclass — implementsAdapter<DiscordThreadId, unknown>. Public methods:handleWebhook,postMessage,editMessage,deleteMessage,addReaction,removeReaction,startTyping,openModal,fetchThread,setThreadTitle,listThreads,fetchMessages,fetchSingleMessage,fetchChannelInfo,postChannelMessage,openDM,startGatewayListener.- Configuration:
DiscordAdapterConfig,DiscordThreadId. - Helpers:
cardToEmbed,cardToFallbackText,DiscordFormatConverter,decodeThreadId,encodeThreadId,isDM.
Thread ID format
discord:{channelId}:{threadId}channelId is the parent text channel; threadId is the
MESSAGE_CREATE.id of the thread root (or the channel id itself for
non-threaded replies). Both are Discord snowflakes (numeric strings),
so no encoding is needed. isDM(threadId) returns true when the
underlying channel type is DM or GROUP_DM.
Webhook flow
DiscordAdapter.handleWebhook(request, options) is the single entry
point for HTTP interactions:
- Signature verification — Discord signs every interaction with
ed25519 over
timestamp + body. Verification uses theDISCORD_PUBLIC_KEYand rejects requests with stale timestamps (default tolerance: 60 s). - Interaction type
PING(1) → respond withPONG.APPLICATION_COMMAND(2) →chat.handleSlashCommand.MESSAGE_COMPONENT(3) →chat.handleAction(buttons + selects).MODAL_SUBMIT(5) → modalonSubmitcallbacks.APPLICATION_COMMAND_AUTOCOMPLETE(4) →chat.handleOptionsLoad.
- Deferred responses — Discord requires a response within 3 s.
Long handlers should return
DEFERRED_CHANNEL_MESSAGE_WITH_SOURCEimmediately and useeditOriginalInteractionResponselater. waitUntil— heavy work runs throughwaitUntilso the initial response lands on time.
Gateway transport
DiscordAdapter.startGatewayListener(options, durationMs, …) opens a
WebSocket gateway connection, identifies, listens for events, and
returns when the duration expires. On serverless platforms (Vercel),
schedule it via cron:
export const maxDuration = 800;
export async function GET(request: Request) {
if (!isAuthorized(request)) {
return new Response("Unauthorized", { status: 401 });
}
return adapter.startGatewayListener(
{ waitUntil: (task) => after(() => task) },
600_000,
undefined,
`https://${process.env.VERCEL_URL}/api/webhooks/discord`
);
}The listener forwards each gateway event as an HTTP request to your
existing webhook URL, signed with gatewayForwardingSecret. This
keeps a single set of handlers serving both transports.
gateway.test.ts includes the isMe detection logic for forwarded
messages — when the bot's own MESSAGE_CREATE is forwarded, the
adapter must skip handler dispatch to avoid feedback loops.
Format conversion
DiscordFormatConverter (in markdown.ts) maps:
- mdast → Discord markdown —
**bold**,*italic*,~~strike~~, fenced code, blockquotes (> …), inline code, links via[label](url). Mentions use<@userId>, channel refs<#channelId>, role refs<@&roleId>. - Discord markdown → mdast — round-trips the same constructs. Custom
emoji
<:name:id>and animated<a:name:id>are preserved as inlineimagenodes pointing at the CDN URL. - Tables — Discord has no native table markdown; the converter flattens to fixed-width text inside a code fence.
Cards (embeds)
cardToEmbed translates a Chat SDK Card JSX tree into a Discord
Embed:
<Header>→embed.title.<Section>content →embed.description(markdown allowed).<Field>→embed.fields[]withinlineset totruewhen the card opts in.<Image>→embed.image.url.<Divider>is rendered as a blank line in the description.
Buttons and selects are emitted as components (action rows) attached to the message rather than inside the embed. Up to 5 buttons per action row, up to 5 action rows per message.
<LinkButton> becomes a LINK style button (url set, no
custom_id). <Button> becomes a primary/secondary/danger button with
custom_id = callbackId.
Modals
openModal returns a deferred response that opens a Discord modal.
Modal limits: up to 5 components, only TEXT_INPUT (short and
paragraph styles) and STRING_SELECT are accepted. Submit events
arrive as MODAL_SUBMIT interactions and dispatch through
chat.handleAction with the modal's callback id.
Discord quirks worth remembering
- 3-second response SLA on every interaction. Defer first, then follow up.
- Slash commands must be registered with the Discord API before
they fire. Use the bulk-overwrite endpoint
(
PUT /applications/{id}/commands) on deploy, or guild-scoped for faster local iteration. - Privileged intents.
MESSAGE_CONTENTis privileged and must be enabled in the developer portal before the gateway will deliver message text in non-mention contexts. - DM channels need a recipient first.
openDMcallsPOST /users/@me/channelswithrecipient_id; the channel id is cached in state so subsequentopenDM(userId)calls reuse it. - Webhook vs bot messages. Webhook-posted messages are not attributed to the bot; for bot identity to apply, post via the bot token endpoint.
- Reactions are unicode-or-custom. Use
:emoji_name:idfor custom emoji; the adapter normalises common aliases (thumbs_up→👍) via the resolver incards.ts. - Forwarded gateway events include the bot's own messages — keep
isMedetection ingateway.tssymmetric with the webhook side.
Testing approach
- Unit tests colocated with each module. Card / embed parity tests are particularly important because Discord rejects malformed embeds without a useful error.
- Replay tests in
packages/integration-tests/src/replay-discord.test.tsexercise both webhook and gateway flows, including the forwarded- event path. - Gateway shim —
gateway.test.tsuses avi.fn()WebSocket so tests don't need a network connection.
When you add a new interaction type, capture a fresh fixture in
sample-messages.md and extend the parser tests.
Coding conventions
- Use named exports throughout. No default exports.
- Discord payload types come from
discord-api-types/v10.types.tsonly declares adapter configuration and the Gateway forwarding envelope; do not hand-write Discord API shapes. - Errors map to
@chat-adapter/shared(AuthenticationError,AdapterRateLimitError,NetworkError,ValidationError). - Top-level regex literals only.
- Avoid storing the bot token in instance state — pass it explicitly to fetch helpers so testing can stub the credentials path.
Releases
Behavioural changes need a changeset (pnpm changeset, choose
@chat-adapter/discord plus chat if a public type changed). Sample
fixtures and AGENTS.md edits don't.
Resources
- Create a Discord support bot with Nuxt and Redis — Walks through building a Discord support bot with Nuxt, covering project setup, Discord app configuration, Gateway forwarding, AI-powered responses, and deployment.
See all guides and templates at chat-sdk.dev/resources.
Where to look next
- User-facing docs:
apps/docs/content/adapters/official/discord.mdx - README:
packages/adapter-discord/README.md - Shared error/utility helpers:
packages/adapter-shared/src/index.ts - Core Adapter contract:
packages/chat/src/adapter.ts - Sample webhook + gateway payloads:
packages/adapter-discord/sample-messages.md
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

