# discord0 documentation # About discord0 Source: https://discord0.babyak.dev/start/about/ discord0 is the Discord application framework that scales to zero. A discord0 app answers Discord's [HTTP interactions](https://discord.com/developers/docs/interactions/overview) instead of holding a Gateway connection open. The app is a `fetch(request)` handler, so it runs on serverless hosts such as Cloudflare Workers, Vercel, Netlify, and AWS Lambda, or on a Node.js or Bun server. On a serverless host nothing runs between requests, so an idle app costs nothing. One `Discord` instance routes everything the app handles: - Slash commands, user and message context menus, and autocomplete - Message components and modals, routed by custom ID - Scheduled tasks, which each adapter turns into the host's cron triggers - Webhooks from outside APIs, and Discord's webhook events, such as app installs and entitlements The `discord0` CLI creates a project, runs it locally with hot reload and an HTTPS tunnel, syncs your commands with Discord, and deploys to your host. ```ts title="src/index.ts" const app = new Discord(); app.command("ping", "Replies with Pong!", () => "Pong!"); app.component("approve:{id}", (c) => c.update(`Approved ${c.params.id}`)); export default app; ``` Without a Gateway connection, an app can't read messages, track presence, or react to events such as a new message. If your app needs those, use a Gateway library instead. ## Why it's built this way ### Agent-first docs Coding agents write a lot of Discord apps, so discord0 is documented for them as much as for people. Everything an agent needs ships with the package and works offline: - A primer at `node_modules/discord0/skills/discord0/SKILL.md`, and an `AGENTS.md` in every new project that points to it. - Editor hover docs, with examples, on every export. - Errors that start with a stable code and say what went wrong, why, and how to fix it, with every code explained in `ERRORS.md`. - [`discord0/testing`](/guides/testing/), which runs the app the way Discord would, so an agent can check a change without Discord or a network. - [`/llms.txt`](/llms.txt) and [`/llms-full.txt`](/llms-full.txt) for loading these docs into a model's context. [AI agents](/guides/ai-agents/) covers each of these. ### A high-level API A handler says what the app does, not how to talk to Discord. Return a string to reply. Signature verification, interaction responses, and command registration happen for you. A handler that's still running near Discord's three-second deadline is [deferred](/guides/deferred-work/) automatically, and the adapter keeps the host alive until the reply is sent. ### A flexible design The framework doesn't decide where or how your app runs: - The same handlers run on six hosts. [Switching adapters](/guides/switching-adapters/) changes one import in `discord0.config.ts`. - A feature can live in its own file as a sub-app, mounted with [`app.route()`](/guides/features/). - `beforeHandle`, `afterHandle`, and `onError` hooks wrap every handler. - Credentials, webhook verification, and the rate limit store can be replaced with your own. ### Type safety throughout Types come from your own definitions, so the compiler catches mistakes before Discord does: - `c.options` is typed from the command's options, including which ones are required. - `c.params` is typed from the custom ID template, such as `{id}` in `approve:{id}`. - Event handlers get the payload for the event type they register. - Discord's API types are re-exported, and its full OpenAPI types are available from `discord0/openapi`. ## Status discord0 is in alpha. APIs can change between releases without notice. Ready to build? Start with the [quick start](/start/quick-start/). # Quick start Source: https://discord0.babyak.dev/start/quick-start/ This page takes you from `npx discord0 init` to a `/ping` command that replies in your own Discord server. It uses the default Cloudflare Workers adapter and npm, but every step works the same way with the other adapters and with pnpm, Yarn, or Bun. ## Before you start You need: - [Node.js](https://nodejs.org) 22 or newer, or [Bun](https://bun.sh) 1.4.4 or newer. The `discord0` CLI runs on Bun. The `discord0` package installs a Bun binary as a dependency and uses it when Node.js starts the CLI, so you don't have to install Bun yourself. - A Discord account and a server where you can add apps. A private test server works best. Create one from the **+** button in the Discord server list. - Optional: an HTTPS tunnel for local testing. `discord0 dev --tunnel` starts a Cloudflare Quick Tunnel for you. You can also run [`cloudflared`](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/) or [ngrok](https://ngrok.com/docs/getting-started/) yourself. ## Create a project Pick the host you plan to deploy to. You can [switch later](/guides/switching-adapters/). 1. Create the project and install its dependencies. For another host, add `--adapter ` to `init`, as the picker shows. ```sh npx discord0 init my-bot cd my-bot npm install ``` `init` copies a starter into `my-bot` but doesn't install anything. Its `package.json` depends on `discord0` and the adapter package at the CLI's own version, such as `^0.1.0-alpha.0`. The starter has one command in `src/index.ts`: ```ts title="src/index.ts" import { Discord } from "discord0"; const app = new Discord(); app.command("ping", "Replies with Pong!", () => "Pong!"); export default app; ``` 2. Copy `.env.example` to `.env`: ```sh cp .env.example .env ``` Then create a Discord application, add it to your test server, and fill in its credentials and your server ID. [Credentials](/start/credentials/) walks through each value. 3. Start the local server with a Quick Tunnel: ```sh npx discord0 dev --tunnel ``` It prints the local endpoint and a public `https://…/interactions` URL, then registers `/ping` with your test server: ```txt Discord interactions listening at http://127.0.0.1:3000/interactions Tunnel ready. Paste this Interactions Endpoint URL into the Developer Portal: https://example.trycloudflare.com/interactions Synced 1 commands (guild 123456789012345678). ``` 4. In the [Developer Portal](https://discord.com/developers/applications), open your application's **General Information** page and set **Interactions Endpoint URL** to the printed HTTPS URL. Save the change. Discord sends a signed test request, and the save succeeds only if `discord0 dev` answers it. 5. In your test server, type `/ping`. The app replies **Pong!** The starter's `dev`, `deploy`, `sync`, and `test` scripts run the matching `discord0` commands, so `npm run dev`, `pnpm dev`, `yarn dev`, and `bun dev` work too. With npm, pass flags after `--`, as in `npm run dev -- --tunnel`. ## Next steps - [Local development](/start/local-development/) covers hot reload, command sync, and tunnels in more detail. - [Deploy](/start/deploy/) puts the app on your host, so it keeps running when your computer is off. # Credentials Source: https://discord0.babyak.dev/start/credentials/ Every discord0 app needs a Discord application. Locally, the starter keeps its credentials in `.env`. `discord0 dev`, `discord0 sync`, `discord0 task`, and the command sync after `discord0 deploy` load `.env` and then `.env.local`. Your `.env` never leaves your machine. `discord0 deploy` doesn't upload it or pass it to the provider's CLI. ```sh title=".env" # Loaded locally by discord0 dev and by command sync after discord0 deploy. DISCORD_BOT_TOKEN= # Required to verify signed Discord requests. DISCORD_PUBLIC_KEY= APPLICATION_ID= # Your test server's ID; discord0 dev syncs commands to it as you edit. DISCORD_GUILD_ID= ``` ## Create the application 1. Open the [Discord Developer Portal](https://discord.com/developers/applications) and select **New Application**. Give it a name and create it. 2. On **General Information**, copy **Application ID** into `APPLICATION_ID` and **Public Key** into `DISCORD_PUBLIC_KEY`. 3. On **Bot**, select **Reset Token** and copy the token into `DISCORD_BOT_TOKEN`. Discord shows it only once. Treat it like a password. `APPLICATION_ID` is optional. When it's empty, command sync looks up the application from the bot token. ## Add the application to your test server 1. On **Installation**, make sure **Guild Install** is checked and that its scopes include `applications.commands`. 2. Open the **Install Link** in your browser and add the app to your test server. Commands work over HTTP interactions, so the app doesn't need the `bot` scope for `/ping`. Add it when your handlers call Discord APIs that need a bot user in the server. ## Find your test server ID 1. In Discord, open **User Settings → Advanced** and turn on **Developer Mode**. 2. Right-click your test server's icon and select **Copy Server ID**. 3. Paste it into `DISCORD_GUILD_ID`. With a server ID set, `discord0 dev` registers your commands with that server only. Server commands update instantly, while global commands can take a while to reach every server. ## Credentials in production In production, the app reads `DISCORD_PUBLIC_KEY` and `DISCORD_BOT_TOKEN` from the host's environment, which you set with the provider. [Deploy](/start/deploy/) shows how for each host. The app doesn't need `DISCORD_GUILD_ID` or `APPLICATION_ID` in production. To read the credentials from somewhere else, such as variables with other names, pass them to `new Discord()`: ```ts const app = new Discord({ publicKey: process.env.STAGING_PUBLIC_KEY, token: process.env.STAGING_BOT_TOKEN, }); ``` To pass Worker bindings instead, see [Cloudflare Workers](/adapters/cloudflare/). # Local development Source: https://discord0.babyak.dev/start/local-development/ `discord0 dev` runs your app on your machine, whichever adapter the project uses. ```sh npx discord0 dev ``` It: - Serves the app at `http://127.0.0.1:3000/interactions`. Set `PORT` to use another port. - Loads `.env` and `.env.local` from the project directory. - Reloads when you save a file. - Registers your commands with your test server when it starts, and again whenever the command definitions change. The entry point is `src/index.ts`, or `entry` in [`discord0.config.ts`](/guides/configuration/). Pass a path to use another one: `npx discord0 dev src/other.ts`. ## Command sync `dev` syncs commands to `guild` in `discord0.config.ts`, which the starter sets from `DISCORD_GUILD_ID`. Sync replaces every command registered with that server, so the server always matches your code. - `--guild ` syncs to another server for this run. - `--no-sync` skips syncing. - `--tunnel` starts a Cloudflare Quick Tunnel, described in the next section. - `sync: { dev: false }` in the config turns it off for good. If no server ID is set, `dev` prints a reminder and serves without syncing. ## HTTPS tunnel Discord sends interactions only to public HTTPS URLs, so a local server needs a tunnel. Pass `--tunnel` to start a Cloudflare Quick Tunnel alongside the server. Quick Tunnels don't need a Cloudflare account. ```sh npx discord0 dev --tunnel ``` It prints an `https://…/interactions` URL. Set that as **Interactions Endpoint URL** on your application's **General Information** page in the [Developer Portal](https://discord.com/developers/applications). The tunnel keeps its URL across hot reloads. Without the flag, `dev` prints a one-line tip about `--tunnel`. `dev` runs `cloudflared` through `bun x cloudflared`. If the tunnel fails or doesn't connect within 30 seconds, `dev` keeps serving locally and prints install instructions. You can also start a tunnel yourself in another terminal: ```sh # Cloudflare Quick Tunnel cloudflared tunnel --url http://127.0.0.1:3000 # ngrok ngrok http 3000 ``` Quick tunnels get a new URL each time they start, so update the endpoint after restarting the tunnel. An application has one endpoint at a time. If you also have a deployed copy, create a separate development application with its own `.env`. ## Deferred work while developing `dev` always runs on Bun as a long-lived process, so no host limit cuts off deferred replies. A handler that works locally can still hit your host's limit in production. Check [Deferred work](/guides/deferred-work/) for your adapter. # Deploy Source: https://discord0.babyak.dev/start/deploy/ ```sh npx discord0 deploy ``` `deploy` bundles your app with the project's adapter into `.discord0/`, uploads that directory with the provider's CLI, and then syncs your commands. The provider's CLI receives only the bundle and the files the adapter generates, not your source tree or `.env`. When the upload succeeds, `deploy` prints the endpoint to use: ```txt Interactions endpoint: https://my-bot.example.workers.dev/interactions ``` If `deploy` can't find a URL in the provider's output, it prints where to look instead. Then: 1. Set `DISCORD_PUBLIC_KEY` and `DISCORD_BOT_TOKEN` with your provider, as shown below. 2. Set the printed URL as **Interactions Endpoint URL** on your application's **General Information** page in the [Developer Portal](https://discord.com/developers/applications). 3. Try `/ping`. ## Set credentials with your provider Wrangler asks you to log in on the first deploy. Set the secrets on the Worker, which is named after your project's `package.json` name: ```sh npx wrangler secret put DISCORD_PUBLIC_KEY --name my-bot npx wrangler secret put DISCORD_BOT_TOKEN --name my-bot ``` Secrets apply right away. Workers always deploy live, so `--prod` has no effect. The Vercel CLI asks you to log in and link a project on the first deploy. Add the variables in **Project Settings → Environment Variables**, or from `.discord0/vercel`: ```sh cd .discord0/vercel npx vercel env add DISCORD_PUBLIC_KEY production npx vercel env add DISCORD_BOT_TOKEN production ``` Variables apply to new deployments, so deploy again afterwards. Deploys are previews unless you pass `--prod`: ```sh npx discord0 deploy --prod ``` The Netlify CLI asks you to log in and link a site on the first deploy. Add the variables in **Site configuration → Environment variables**, or from `.discord0/netlify`: ```sh cd .discord0/netlify npx netlify-cli env:set DISCORD_PUBLIC_KEY npx netlify-cli env:set DISCORD_BOT_TOKEN ``` Variables apply to new deploys, so deploy again afterwards. Deploys are drafts unless you pass `--prod`: ```sh npx discord0 deploy --prod ``` The AWS adapter deploys with Serverless Framework v3, which uses your AWS CLI credentials. Serverless reads the Discord credentials from SSM Parameter Store at deploy time, so create the parameters **before** the first deploy, in the region you deploy to. Serverless deploys to `us-east-1` unless you pass `-- --region `: ```sh aws ssm put-parameter --name /my-bot/DISCORD_PUBLIC_KEY --type String --value aws ssm put-parameter --name /my-bot/DISCORD_BOT_TOKEN --type SecureString --value ``` `my-bot` is your project's `package.json` name. Deploys go to the `dev` stage unless you pass `--prod`, which deploys the `prod` stage. The Node.js adapter builds a server instead of uploading anything: ```sh cd .discord0/node DISCORD_PUBLIC_KEY=... DISCORD_BOT_TOKEN=... node index.mjs ``` Copy `.discord0/node` to your server, set the variables in its environment, and serve it over HTTPS, such as behind a reverse proxy. It listens on `PORT`, or 3000. The Bun adapter builds a server instead of uploading anything: ```sh cd .discord0/bun DISCORD_PUBLIC_KEY=... DISCORD_BOT_TOKEN=... bun index.js ``` Copy `.discord0/bun` to your server, set the variables in its environment, and serve it over HTTPS, such as behind a reverse proxy. It listens on `PORT`, or 3000. ## Command sync after deploy After a successful upload, or after the build for Node.js and Bun, `deploy` registers your commands globally. It uses `DISCORD_BOT_TOKEN` from your local `.env`. Global commands can take a while to appear everywhere. Commands you synced to your test server during development stay there, so the test server shows each command twice until you remove the server copies. To sync elsewhere: - `--scope guild` syncs to your test server instead. - `--guild ` syncs to one server. - `--no-sync` skips the sync. - `sync: { deploy: "guild" }` or `sync: { deploy: false }` in [`discord0.config.ts`](/guides/configuration/) changes the default. Run `npx discord0 sync` at any time to sync without deploying. ## Other options - `--dry-run` builds `.discord0/` without uploading or syncing, and prints the provider command it would run. - Anything after `--` goes to the provider's CLI unchanged, such as `npx discord0 deploy -- --env staging`. The starter's `.gitignore` ignores `.discord0/`, which holds generated build output only. Keep it ignored if you replace that file. # discord0.config.ts Source: https://discord0.babyak.dev/guides/configuration/ `discord0.config.ts` in the project root holds the settings the CLI uses. Flags you pass on the command line override it. `init` writes one for the adapter you chose: ```ts title="discord0.config.ts" export default defineConfig({ entry: "src/index.ts", adapter: adapter(), // Your test server. `discord0 dev` syncs commands to it on start and on change. guild: process.env.DISCORD_GUILD_ID, sync: { // dev: false, // never sync from `discord0 dev` deploy: "global", // after `discord0 deploy`: "global", "guild", or false }, }); ``` The CLI loads `.env` and `.env.local` before it reads the config, so the config can read their values through `process.env`. `.env.local` wins over `.env`, and variables already set in your environment win over both. The CLI also accepts `discord0.config.mts`, `discord0.config.js`, and `discord0.config.mjs`. ## Options | Option | Default | Description | | ------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `entry` | `"src/index.ts"` | The module that default-exports the app. A path passed to `dev`, `sync`, `task`, or `deploy` overrides it. | | `adapter` | none | What `deploy` builds for, such as `adapter()` from `@discord0/adapter-vercel`. An adapter name passed to `deploy` overrides it. | | `guild` | none | Your test server's ID, 17 to 20 digits. An empty or unset value counts as no server. | | `sync.dev` | `"guild"` if `guild` is set, otherwise `false` | `"guild"` syncs to `guild` when `dev` starts and when commands change. `false` never syncs from `dev`. | | `sync.deploy` | `"global"` | Where `deploy` syncs after a successful deploy: `"global"`, `"guild"`, or `false`. | Setting `sync.dev` or `sync.deploy` to `"guild"` without `guild` is an error. So is any other key, at the top level or in `sync`, so a typo fails instead of being ignored. # Switching adapters Source: https://discord0.babyak.dev/guides/switching-adapters/ An adapter connects your app to a host. Your handlers stay the same on every host. Only `discord0.config.ts` changes. | Adapter | Host | `init --adapter` | | ------------------------------ | ------------------------------------------------------- | ---------------------- | | `@discord0/adapter-cloudflare` | [Cloudflare Workers](/adapters/cloudflare/) | `cloudflare` (default) | | `@discord0/adapter-vercel` | [Vercel Functions](/adapters/vercel/) | `vercel` | | `@discord0/adapter-netlify` | [Netlify Functions](/adapters/netlify/) | `netlify` | | `@discord0/adapter-aws` | [AWS Lambda](/adapters/aws/) with a Function URL | `aws` | | `@discord0/adapter-node` | [A Node.js server](/adapters/node/) you run yourself | `node` | | `@discord0/adapter-bun` | [A `Bun.serve` server](/adapters/bun/) you run yourself | `bun` | ## Switch an existing project 1. Install the new adapter as a dev dependency: ```sh npm install -D @discord0/adapter-vercel ``` 2. Import it in `discord0.config.ts` instead of the old one: ```ts title="discord0.config.ts" import adapter from "@discord0/adapter-vercel"; import { defineConfig } from "discord0"; export default defineConfig({ adapter: adapter(), guild: process.env.DISCORD_GUILD_ID, }); ``` 3. Remove the old adapter if you no longer need it: ```sh npm uninstall @discord0/adapter-cloudflare ``` 4. Set your credentials with the new provider, deploy, and update the **Interactions Endpoint URL** in the Developer Portal. If the app handles [webhook events](/guides/events/), update the Webhook Events URL too. [Deploy](/start/deploy/) covers each host. If your handlers run for more than a few seconds, check the new host's [deferred-work limit](/guides/deferred-work/) before you switch. ## Deploy to another host once To try a host without changing the config, pass its name to `deploy`: ```sh npm install -D @discord0/adapter-netlify npx discord0 deploy netlify ``` `deploy ` loads `@discord0/adapter-` from your project's `node_modules`, so install the adapter first. # Deferred work Source: https://discord0.babyak.dev/guides/deferred-work/ Discord waits only 3 seconds for the first response to an interaction. A handler that takes longer, such as one that calls another API, has to acknowledge the interaction first and send its reply later. discord0 does that for you, and each adapter keeps the host running until the reply is sent. ## Automatic deferral When a handler hasn't responded after 2 seconds, the app sends a deferred response, and Discord shows "_App_ is thinking…". When the handler returns, its message replaces the loading state. ```ts app.command("forecast", "Fetches the weather", async () => { const response = await fetch("https://api.example.com/forecast"); const { summary } = await response.json(); return summary; // Edits the deferred reply if this took over 2 seconds. }); ``` Two options control this: ```ts const app = new Discord({ // When to defer, in milliseconds. Must be below 3000. Default: 2000, // or a lower host default from the adapter when you leave it unset. autoDeferAfterMs: 1500, // Whether an automatic deferral is ephemeral (visible only to the user // who ran the command). Default: true. autoDeferEphemeral: false, }); ``` A deferred reply keeps the visibility it was deferred with. With the default `autoDeferEphemeral: true`, a slow handler's reply is ephemeral even if it returns a public message. Set it to `false` for public replies. With `false`, a slow handler that returns an ephemeral message fails with `EPHEMERAL_MISMATCH`. To keep that handler's reply private, call `c.defer(true)` in it before the slow work. ### Per-host defaults `autoDeferAfterMs` is measured from when your handler starts, not from when Discord sent the request. On serverless hosts, cold starts can use much of Discord's 3-second window before that. When you leave `autoDeferAfterMs` unset, each hosted adapter applies its own default so the acknowledgement still fits: | Adapter | Default `autoDeferAfterMs` | Why | | -------------------------------------------------- | -------------------------- | ----------------------------------------------------------------- | | [Cloudflare Workers](/adapters/cloudflare/) | 2000 | Cold starts are typically tens of milliseconds | | [Vercel Functions](/adapters/vercel/) | 1000 | Cold starts often take 0.7 to 1.6 seconds before the handler runs | | [Netlify Functions](/adapters/netlify/) | 500 | Cold starts can use most of the 3-second window | | [AWS Lambda](/adapters/aws/) | 1000 | Cold starts often take 0.7 to 1.5 seconds before the handler runs | | [Node.js](/adapters/node/) / [Bun](/adapters/bun/) | 2000 | A long-lived process has no cold start | Setting `autoDeferAfterMs` in `new Discord({ ... })` always wins over the adapter default. To defer yourself, call `c.defer()` before the slow work, or `c.defer(true)` for an ephemeral reply. Then return the message or call `c.reply()`. After the first response, you can also call `c.editReply()` and `c.followUp()`. ## How `waitUntil` keeps work alive The app answers Discord's HTTP request as soon as the interaction is acknowledged, and the rest of the handler runs afterwards. On a serverless host, a function can be frozen or stopped once it returns its response. So the app passes the unfinished work to the host's `waitUntil`, which keeps the function alive until that work settles. Each adapter connects this for you: | Adapter | How deferred work is kept alive | | ---------- | ---------------------------------------------------------------------------------------- | | Cloudflare | `ctx.waitUntil()` from the Worker's execution context | | Vercel | `waitUntil()` from `@vercel/functions` | | Netlify | `context.waitUntil()` from the function's context | | AWS | The handler streams the response, then waits for every pending promise before it returns | | Node.js | The process keeps running, and graceful shutdown waits for pending work | | Bun | The process keeps running, and graceful shutdown waits for pending work | The app reports errors in deferred work to `onError`, and edits the reply to the error message when it can. ## Fallback messages and lifecycle hooks The app sends a fallback reply when a handler throws (`error`), when no handler matches the interaction (`unavailable`), and when a handler returns without replying (`noResponse`). Replace them to localize them or to add a support link: ```ts const app = new Discord({ messages: { error: "Something went wrong. https://example.com/support", unavailable: "This control is no longer available.", noResponse: "No reply was produced.", }, }); ``` Lifecycle hooks add logging, tracing, or metrics without wrapping every handler. `beforeHandle` runs before each verified interaction is routed. `afterHandle` runs after routing finishes, with the duration in milliseconds. `onError` receives handler errors and replaces the default error log: ```ts app .beforeHandle((interaction) => { console.log("handling", interaction.id); }) .afterHandle((interaction, durationMs) => { console.log("done", interaction.id, durationMs); }) .onError((error, interaction, durationMs) => { console.error("failed", interaction.id, durationMs, error); }); ``` A hook that throws doesn't stop the interaction. You can set hooks only on the main app. Mounting a sub-app that sets one throws. If you call `app.fetch` from your own server code, pass your host's `waitUntil` as the second argument. Otherwise a serverless host can stop deferred work once the response is sent: ```ts app.fetch(request, { waitUntil: (promise) => keepAlive(promise) }); ``` ## Limits Two limits apply to every handler: - **Discord's 15 minutes.** Interaction tokens are valid for 15 minutes, so replies, edits, and follow-ups must be sent within 15 minutes of the interaction. ([Discord docs](https://docs.discord.com/developers/interactions/receiving-and-responding#followup-messages)) - **Your host's limit**, which is often shorter: | Adapter | How long deferred work can run | | ------------------------------------------- | ---------------------------------------------------------------------------------------------- | | [Cloudflare Workers](/adapters/cloudflare/) | 30 seconds after the response is sent, plus CPU time limits | | [Vercel Functions](/adapters/vercel/) | Until the function's maximum duration: 300 seconds by default, up to 800 on Pro and Enterprise | | [Netlify Functions](/adapters/netlify/) | 60 seconds in total, including the response | | [AWS Lambda](/adapters/aws/) | Until the function timeout: 60 seconds in the generated config | | [Node.js](/adapters/node/) | No host limit. On shutdown, your process manager's stop timeout applies | | [Bun](/adapters/bun/) | No host limit. On shutdown, your process manager's stop timeout applies | The host cancels work that runs past its limit, and the user is left with the loading state. For longer jobs, acknowledge the interaction and hand the job to a queue or background worker on your host. Have that worker edit the reply through Discord's webhook endpoints within 15 minutes. Each adapter's page links to the provider's current documentation, since provider limits change. # Features in their own files Source: https://discord0.babyak.dev/guides/features/ A feature, such as tickets, can live in its own file as a sub-app, which is a plain `Discord` instance. Mount it with `app.route()`. Discord has no URL paths, so the mount prefix is a command name, and the sub-app's commands become its subcommands. ```ts // src/features/tickets.ts export const tickets = new Discord() .command( { name: "open", description: "Open a ticket", options: [ { type: ApplicationCommandOptionType.String, name: "reason", description: "Why", required: true, }, ], }, (c) => `Opened: ${c.options.reason}`, ) .command("close", "Close a ticket", () => "Closed") .autocomplete("open", (c) => []) .component("ticket-close:{id}", (c) => c.update("Closed")); ``` ```ts // src/index.ts const app = new Discord() .command("ping", "Replies with Pong!", () => "Pong!") .route("ticket", "Manage tickets", tickets); // /ticket open, /ticket close export default app; ``` A handler doesn't know where it's mounted. `c.options` holds the subcommand's own options, flat and typed as they would be on a top-level command. Names in the sub-app are relative to it, so `autocomplete("open")` answers `/ticket open` once mounted. ## Ways to mount | Call | Result | | ---------------------------------------- | ------------------------------------------------------------------------------- | | `route("ticket", "Manage tickets", sub)` | The sub-app's commands become subcommands of `/ticket`. | | `route({ name, description, ... }, sub)` | The same, with top-level command fields such as `default_member_permissions`. | | `route(sub)` | The sub-app's commands, including context menus, join the app at the top level. | A sub-app can mount another sub-app, which becomes a subcommand group, such as `/ticket admin ban`. Discord allows only a command, a group, and a subcommand, so mounting one more level throws. Components, modals, scheduled tasks, webhook routes, and event handlers register on the main app unchanged, so mounting doesn't rename their custom IDs, names, or paths. Keep custom IDs unique across features, for example with a feature prefix such as `ticket-close:{id}`. ## Sealing Mounting copies the sub-app and seals it. Registering anything on a sealed sub-app throws, rather than leaving the new handler silently unrouted. Register everything on a sub-app before you mount it, and mount inner sub-apps before outer ones. The main app's settings apply to every handler, so a sub-app built with constructor options or lifecycle hooks (`beforeHandle`, `afterHandle`, `onError`) throws when mounted. ## Validation Mounting checks the result against Discord's limits and throws with the mount in the message, such as `route("ticket"): Duplicate command: ticket`. It rejects: - Names that aren't 1 to 32 lowercase letters, numbers, `-`, or `_`, and descriptions that aren't 1 to 100 characters. - A command path that already exists, and a duplicate autocomplete handler, component, modal, task name, or webhook path. - More than 25 subcommands or groups at one level. - More than 100 slash commands, or 15 user or 15 message commands. - A command over 8000 characters across its names, descriptions, and choice values. - In a sub-app mounted under a name, context menu commands, and commands that set top-level fields such as `default_member_permissions` or define their own subcommand options. Set top-level fields on the mount instead. A mount that fails changes nothing, and leaves the sub-app unsealed. # Scheduled tasks Source: https://discord0.babyak.dev/guides/scheduled-tasks/ A task is a handler that runs on a schedule instead of in answer to an interaction, such as a daily reminder or a nightly cleanup. Register it on the app with a name and a cron expression: ```ts app.task("standup", "0 13 * * 1-5", async (c) => { await c.send(process.env.STANDUP_CHANNEL_ID!, "Standup in 15 minutes!"); }); ``` On Cloudflare, Vercel, Netlify, and AWS, `discord0 deploy` writes every task into the host's scheduler, and the host calls the handler when the schedule fires. The Node.js and Bun servers run the schedule themselves. The app itself starts no timers. ## Schedules The expression has five fields: minute, hour, day of the month, month, and day of the week (0 is Sunday, 6 is Saturday). Each field takes numbers, `*`, lists (`1,15`), ranges (`1-5`), and steps (`*/15`, `0-30/10`). Names such as `MON`, nicknames such as `@daily`, and `L`, `W`, `#`, and `?` aren't accepted, because not every host supports them. As in standard cron, when both day fields are set, the task runs on days that match either. Schedules run in UTC unless you set a time zone: ```ts app.task( { name: "standup", expression: "0 9 * * 1-5", timezone: "America/Toronto" }, handler, ); ``` Cloudflare, Vercel, and Netlify schedule in UTC only, so deploying a task with another time zone there fails. A fixed UTC offset would drift by an hour across daylight saving time, so write the expression in UTC instead, or use an adapter that honors time zones: AWS, Node.js, or Bun. Task names are 1 to 64 lowercase letters, digits, hyphens, and underscores, and start with a letter or digit. Each name is unique across the app and its [mounted sub-apps](/guides/features/). ## The task context The handler receives `c`: | Member | Description | | ----------------- | ----------------------------------------------------------------------- | | `c.task` | The task's `name`, `expression`, and `timezone`. | | `c.scheduledTime` | When the host scheduled this run, or the current time when it has none. | | `c.send(id, msg)` | Posts a message to a channel as the bot and returns it. | A handler that throws fails the run. A hosted scheduler records the failure as it does for any other scheduled job, and the Node.js and Bun servers log it. ## Running a task yourself Run a task once, now, with the variables in your local `.env` and `.env.local`. The run posts to Discord for real: ```sh npx discord0 task standup ``` `app.runTask(name)` does the same from code, which helps in tests and with a scheduler of your own. It resolves when the handler finishes and rejects if it throws. `app.tasks` lists every task's schedule. ## How each host runs tasks | Adapter | Scheduler | Time zones | Limits | | ---------- | ----------------------------------------------------------------------- | ---------- | -------------------------------------------------------------------------------------------- | | Cloudflare | Cron Triggers in `wrangler.json`, handled by the Worker's `scheduled()` | UTC only | Workers Free: 5 triggers per account and 10 ms of CPU per run. Paid: 1,000 triggers. | | Vercel | Cron Jobs in `vercel.json`, calling `/api/tasks` | UTC only | Production deployments only. Hobby: at most once a day, at any minute of the scheduled hour. | | Netlify | One scheduled function per task | UTC only | Published deploys only. Each run stops after 30 seconds. | | AWS | EventBridge Scheduler, invoking a `tasks` function | Yes | The function stops after 300 seconds. Scheduler bills per invocation. | | Node.js | In the server process | Yes | Runs only while the server is up. | | Bun | `Bun.cron` in the server process | Yes | Runs only while the server is up. | On Cloudflare, tasks with the same schedule share one Cron Trigger, which runs them all. Trigger changes can take up to 15 minutes to apply. A deploy prints each task with notes like these for its host. On Vercel, set `CRON_SECRET` in the project. Vercel sends it with each cron request, and the task route refuses requests without it. While `CRON_SECRET` is unset, the route answers `503` and no task runs. ### Self-hosted servers and replicas The Node.js and Bun servers run tasks in process, so every running copy of the server runs every task. If you run more than one, set `DISCORD0_TASKS=off` in all but one, or pass `tasks: false` to `serve()`. If a run is still going when its next time comes, the server skips that time instead of starting a second run. Removing a task and deploying again removes its schedule from the host. # Webhooks from other services Source: https://discord0.babyak.dev/guides/webhooks/ A webhook route accepts HTTP requests from an outside API, such as GitHub, Stripe, or a service of your own, and can post to Discord in answer. Register it on the app with an exact path, a verifier, and a handler: ```ts app.webhook( "/webhooks/github", { verify: verifyHmac({ secret: () => process.env.GITHUB_WEBHOOK_SECRET, header: "x-hub-signature-256", prefix: "sha256=", }), }, (c) => { const push = c.json<{ ref: string; repository: { full_name: string } }>(); c.waitUntil( c.send( process.env.DEPLOYS_CHANNEL_ID!, `Pushed to ${push.ref} in ${push.repository.full_name}`, ), ); return new Response(null, { status: 202 }); }, ); ``` `discord0 deploy` routes the path to the app on every host. Hosted adapters print each `Webhook endpoint` URL after the `Interactions endpoint` line, and the Node.js and Bun servers log each webhook URL when they start. Give that URL to the outside service. `/interactions` stays Discord's signed interactions endpoint. A webhook route never reaches it, and Discord's Ed25519 check never runs on a webhook route. ## Verifying requests `verify` runs before the handler, with the request and its raw body. It's required. Pass `false` only for a route that checks requests itself or needs no check. | The verifier returns | The response | | -------------------- | ---------------------- | | `true` | The handler runs. | | `false` | `401 Unauthorized` | | A `Response` | That response. | | It throws | `401`, and it's logged | `verifyHmac()` checks HMAC signatures, in constant time. Set `header` to the header that carries the signature, and `prefix` to any text before it. `encoding` is `hex` (the default) or `base64`, and `algorithm` is `SHA-256` (the default), `SHA-1`, or `SHA-512`. Pass `secret` as a function to read it on each request. While the secret is unset or empty, requests answer `503`. Set `payload` when the service signs more than the raw body. It receives the request and returns the signed string or bytes. Slack, for example, signs `v0::`. A service whose signature header holds several values, such as Stripe's `t=,v1=`, needs a verifier of its own. Its argument has `body` (the raw bytes), `text()`, `json()`, `headers`, `method`, and `url`, as the handler's `c` does. ## The webhook context The handler receives `c`, with the members above and these: | Member | Description | | ----------------------------- | ------------------------------------------------------------------------------------------------------------- | | `c.waitUntil(promise)` | Keeps work running after the response is sent, for as long as the host allows. A rejection is logged. | | `c.send(id, msg)` | Posts a message to a channel as the bot and returns it. | | `c.executeWebhook(hook, msg)` | Posts through a Discord webhook, by its URL or `{ id, token }`, and returns the message. No bot token needed. | Return a `Response`, or nothing for `204 No Content`. A handler that throws answers `500`, and the error is logged. Outside services often wait only a few seconds for an answer, so answer first and post with `c.waitUntil`, as above. `waitUntil` keeps the post alive the same way it keeps [deferred interaction replies](/guides/deferred-work/) alive. ## Paths and methods Paths are exact and static, such as `/webhooks/github`. Each segment uses letters, digits, `.`, `_`, `~`, and `-`, with no parameters, query, or trailing slash. Each path is unique across the app and its [mounted sub-apps](/guides/features/). It can't be the interactions path (`/interactions` by default) or the events path (`/events` by default). Requests to any other path answer `404`. Routes accept `POST` unless you set `methods`, such as `["GET", "POST"]` for a service that checks the URL with a `GET` first. Other methods answer `405`. Bodies are limited to the app's `maxBodyBytes` (1 MiB by default), and a larger body answers `413`. Set `maxBodyBytes` on the route to change the limit. ```ts app.webhook( { path: "/hooks/build", verify: false, methods: ["GET", "POST"] }, handler, ); ``` ## How each host routes webhooks | Adapter | Routing | | ---------- | --------------------------------------------------------------------------- | | Cloudflare | The Worker receives every path. | | Vercel | A rewrite per path in `vercel.json`. Paths under `/api` fail. | | Netlify | Each path joins the function's `config.path`. Paths under `/.netlify` fail. | | AWS | The function URL receives every path. | | Node.js | The server receives every path, and logs each webhook URL. | | Bun | The server receives every path, and logs each webhook URL. | `discord0 deploy --dry-run` lists each route it generated. # Webhook events from Discord Source: https://discord0.babyak.dev/guides/events/ Discord can send some events to your app as signed HTTP requests, with no Gateway connection. These are [webhook events](https://docs.discord.com/developers/events/webhook-events), such as `APPLICATION_AUTHORIZED` when someone installs the app, and `ENTITLEMENT_CREATE` when someone buys a SKU. On a serverless host, they're the only way to receive events. Handle one with `app.event()`: ```ts app.event("APPLICATION_AUTHORIZED", (c) => { const where = c.data.guild ? `in ${c.data.guild.name}` : "to their account"; return c.send( process.env.INSTALLS_CHANNEL_ID!, `${c.data.user.username} installed the app ${where}`, ); }); app.event("ENTITLEMENT_CREATE", (c) => { console.log(`User ${c.data.user_id} bought SKU ${c.data.sku_id}`); }); ``` `c.data` is typed by the event type. Types without typed data, such as `LOBBY_MESSAGE_CREATE`, are accepted too, with `unknown` data. ## Set the Webhook Events URL Discord sends webhook events to their own URL, apart from the Interactions Endpoint URL. The app serves them at `/events` once it has an `app.event()` handler. 1. Deploy. `discord0 deploy` routes `/events` on every host. On a hosted adapter, it prints the URL next to the Interactions endpoint: ```txt Interactions endpoint: https://my-bot.example.workers.dev/interactions Webhook Events URL: https://my-bot.example.workers.dev/events ``` On Node.js and Bun, `serve()` logs the URL when the server starts. 2. In the [Developer Portal](https://discord.com/developers/applications), open your app's **Webhooks** page, paste that URL into **Endpoint URL**, and save. Discord sends a PING, which the app answers. 3. Turn on **Events**, and enable each event type you handle. Deploy prints the list. For local development, `discord0 dev` logs the events URL too. Give Discord the same URL through your HTTPS tunnel, as for interactions. To serve events at another path, set `eventsPath`: ```ts const app = new Discord({ eventsPath: "/discord/events" }); ``` ## How events are handled - Each request is checked against the app's public key, like an interaction, with the same Ed25519 signature and timestamp window. Requests that fail answer `401`. - Discord's PING answers `204`. - An event answers `204` at once, before its handlers run. They then finish through the host's `waitUntil`, as [deferred work](/guides/deferred-work/) does, so the same limits apply on each host. - An event type may have several handlers, such as one per [sub-app](/guides/features/). They run together, and an event with no handler is still answered `204`. - The app logs a handler's error. Discord retries only events that go unanswered, so it doesn't resend an event whose handler failed. ## The event context | Member | Description | | -------------------- | --------------------------------------------------------------- | | `c.type` | The event type, such as `APPLICATION_AUTHORIZED`. | | `c.data` | The event's data, typed by its type. | | `c.timestamp` | When the event occurred, as a `Date`. | | `c.applicationId` | The ID of the app the event is for. | | `c.event` | The `event` object as Discord sent it. | | `c.send()` | Posts a message to a channel as the bot, and returns it. | | `c.executeWebhook()` | Posts through a Discord webhook, by its URL or `{ id, token }`. | ## Testing `app.dispatchEvent()` runs the handlers for an event body, skipping the signature check, and resolves when they finish. Handler errors reject: ```ts await app.dispatchEvent({ version: 1, application_id: "123", type: 1, event: { type: "APPLICATION_AUTHORIZED", timestamp: new Date().toISOString(), data: { user: { id: "456", username: "tester", discriminator: "0", global_name: null, avatar: null, }, scopes: ["applications.commands"], }, }, }); ``` # Testing Source: https://discord0.babyak.dev/guides/testing/ `discord0/testing` runs your app the way Discord would, with no Discord and no network. It builds interaction payloads, sends them to the app, and records what the app sent back: the inline response, deferrals, edits, and follow-ups. REST calls go to a fake that answers like Discord. The helpers return plain data, so any test runner works. The starter's test uses Bun's: ```ts // src/index.test.ts const client = createTestClient(app); test("/ping replies with Pong!", async () => { const result = await client.command("ping"); expect(result.reply).toEqual({ content: "Pong!" }); }); ``` Run it with `npm test`, or `discord0 test`, which runs `bun test` on the Bun that the `discord0` CLI runs on, so the project needs no Bun install of its own. Arguments pass through, as in `discord0 test --watch`. `discord0/testing` is a separate entry point, so production bundles leave it out as long as only tests import it. ## Sending interactions | Method | Sends | | --------------------------------------------------- | ------------------------------------------------------------------- | | `client.command(path, values?, init?)` | A slash command. Name a subcommand by its path, as `"ticket open"`. | | `client.component(customId, init?)` | A button click, or a select menu choice with `init.values`. | | `client.modal(customId, fields?, init?)` | A modal submission. `fields` maps text input IDs to their values. | | `client.autocomplete(path, values, focused, init?)` | Autocomplete while the user types into the `focused` option. | | `client.runTask(name, options?)` | Runs a [scheduled task](/guides/scheduled-tasks/). | Option values are what the user typed or picked. Pass strings, numbers, and booleans, or IDs for users, channels, roles, and attachments. The client reads each option's type from the app's command definitions. A misspelled command, subcommand, or option rejects with `INVALID_TEST_INPUT`, so the test fails: ```ts await client.command("roll", { sides: 20 }); await client.component("approve:42"); await client.component("color", { values: ["red"] }); await client.modal("feedback", { comment: "Great bot" }); await client.autocomplete("search", { query: "ap" }, "query"); ``` `init` sets who sends the interaction and where. It takes `user` fields, `guildId` for a server interaction (the user becomes a member), `member`, `channelId`, `locale`, `guildLocale`, `applicationId`, `entitlements`, and `appPermissions`. For `client.component()`, it also takes `values`, `componentType`, and the `message` the component is on. For `client.modal()`, it also takes `message`. Pass defaults for every interaction with `createTestClient(app, { interaction: { guildId } })`. Each method resolves once the handler finishes, including work after the response, such as edits after a deferral. ### Transports By default the client signs each payload with a test key and sends it through `app.fetch`, as Discord would, so signature checks and payload validation run too. The client points the app at the test key, so no `DISCORD_PUBLIC_KEY` is needed. `createTestClient(app, { transport: "dispatch" })` hands payloads straight to `app.dispatch` instead. `client.send(payload)` sends a payload with the client's transport, and `client.fetch(payload)` and `client.dispatch(payload)` pick a transport for one payload. ### Building payloads yourself The builders behind the methods are exported too, for payloads you want to change first: ```ts const client = createTestClient(app); const interaction = buildCommand(app, "ping"); const user = interaction.user!; interaction.data.resolved = { users: { [user.id]: user } }; const result = await client.send(interaction); ``` `buildCommand`, `buildComponent`, `buildModalSubmit`, and `buildAutocomplete` return `discord-api-types` interactions with fresh IDs and tokens. `testMessage()` builds a message for `buildComponent(id, { message })`, and `testIds` holds the default application, user, channel, and server IDs. ## Results An interaction resolves to an `InteractionResult`: | Field | Description | | ------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `interaction` | The interaction payload that was sent. | | `reply` | The message the user sees: the inline reply or update with every edit applied. `undefined` if there is none or it was deleted. | | `response` | The inline interaction response, as the app returned it. | | `deferred` | Whether the response was a deferral, by the handler or after `autoDeferAfterMs`. | | `ephemeral` | Whether the reply is visible only to the user. | | `edits` | Bodies of `c.editReply()` calls, including a reply sent after a deferral. | | `followUps` | Bodies of `c.followUp()` calls. | | `choices` | Autocomplete choices, for an autocomplete response. | | `modal` | The modal shown, if the response opened one. | | `calls` | REST calls made with this interaction's token: method, path, query, body, and files. | | `errors` | Errors the app reported, such as a handler throwing. | | `status` | The HTTP status from `app.fetch`. Through `dispatch`, `200`, or `500` if the app produced no response. | A handler that throws still produces a result. `reply` is the ephemeral error message the user would see (`messages.error` if you set one), and `errors` holds what was thrown. The app's `onError` runs as usual, with the interaction and how long handling took. `client.runTask()` resolves to the `messages` the task posted with `c.send()`, each with its `channelId` and `data`, and the run's REST `calls`. It rejects if the task throws, as `app.runTask()` does: ```ts const result = await client.runTask("standup", { scheduledTime: new Date("2026-11-23T12:45:00Z"), }); expect(result.messages).toEqual([ { channelId: "123", data: { content: "Standup in 15 minutes!" } }, ]); ``` `client.calls` lists every REST call through the client, in order, including calls that belong to no single interaction or task run. ## Faking Discord's answers The fake answers the calls the framework makes. It sends, edits, reads, and deletes replies and follow-ups, posts channel messages, and executes Discord webhooks. It returns messages built from what was sent. Any other call fails with an error that names it. Pass `rest` to answer calls yourself, such as to make one fail. Return a `Response` to send it as is, any other value to send it as JSON, or `undefined` to use the default fake: ```ts const client = createTestClient(app, { rest: (call) => call.path.startsWith("/channels/") ? Response.json( { code: 50001, message: "Missing Access" }, { status: 403 }, ) : undefined, }); ``` ## Other endpoints `client.sign(body, { path })` returns a request signed with the test key, for endpoints the helpers don't cover, such as [webhook events](/guides/events/). Pass a `waitUntil` to `app.fetch` to wait for the event handlers: ```ts const pending: Promise[] = []; const request = await client.sign(eventBody, { path: "/events" }); const response = await app.fetch(request, { waitUntil: (promise) => void pending.push(promise), }); await Promise.all(pending); ``` ## One client per app The client attaches to the app the first time it sends something, replacing its REST client and public key, and every send attaches it again. Create one client per app, such as at the top of a test file, rather than several used at once. # AI agents Source: https://discord0.babyak.dev/guides/ai-agents/ discord0 ships files and tools for coding agents such as Claude Code, Cursor, and Codex. An agent can read the API from the package, test its changes offline, and fix errors from the error text alone, without opening a browser. ## What ships in the package | File | For | | ------------------------------------------------ | ------------------------------------------------------------------------- | | `node_modules/discord0/skills/discord0/SKILL.md` | A short primer: the mental model, an API cheat sheet, and common mistakes | | `node_modules/discord0/ERRORS.md` | Every error code, with why it happens and how to fix it | | `AGENTS.md` in new projects | Points agents at the primer and at `discord0 test` | `discord0 init` writes `AGENTS.md` into every new project, so an agent working in the project finds the primer without being told about it. ## Errors that explain themselves Every error starts with a stable code. Then it says what went wrong, with the specific names and values, why, and how to fix it: ```text [INVALID_TASK] Invalid task name "Daily": use 1-64 lowercase letters, digits, hyphens, and underscores Why: Task names become host resource names (Cloudflare Cron Triggers, EventBridge schedules, Netlify functions), so they're limited to 1-64 lowercase letters, digits, `-`, and `_`. Fix: Rename it, for example to "daily". Docs: https://github.com/natebabyak/discord0/blob/main/packages/discord0/ERRORS.md#invalid_task ``` When the fix depends on your code, the `Fix:` line names it. An invalid name comes with a valid one to use, and an unknown task, command, or option lists the valid ones. Errors from Discord's API list the fields Discord rejected, name the request with tokens redacted, and suggest a fix for common codes such as 10062 (answered too late) and 50001 (missing access). Thrown errors are `Discord0Error` instances, with `code`, `detail`, `why`, `fix`, and `docs` properties, and `JSON.stringify` gives a structured log entry. Match on `code`, not on the message text. See the [error reference](/reference/errors/) for every code. Failures discord0 recovers from, such as a handler that throws, are logged the same way, as `[HANDLER_FAILED] The handler for /ping threw` followed by the original error. ## Checking changes offline [`discord0/testing`](/guides/testing/) runs the app the way Discord would, without Discord or a network. After an agent changes a command, one command runs the tests and checks the reply: ```sh npx discord0 test ``` A test result's `errors` lists what handlers threw. A misspelled command, subcommand, or option fails with `INVALID_TEST_INPUT`, and the error lists the valid names. ## llms.txt The docs site publishes [`/llms.txt`](/llms.txt), an index of every page with its description, and [`/llms-full.txt`](/llms-full.txt), every page in one Markdown file for a model's context. # Cloudflare Workers Source: https://discord0.babyak.dev/adapters/cloudflare/ `@discord0/adapter-cloudflare` is the default adapter. `discord0 deploy` bundles your app as a module Worker and uploads it with [Wrangler](https://developers.cloudflare.com/workers/wrangler/). ```sh npx discord0 init my-bot # or: --adapter cloudflare ``` ## What deploy generates `.discord0/cloudflare` contains `worker.mjs`, a `package.json`, and a `wrangler.json` that: - names the Worker after your `package.json` name, - enables `nodejs_compat`, which exposes secrets through `process.env`, and - serves the Worker on its `*.workers.dev` URL. Workers always deploy live, so `--prod` has no effect. Wrangler asks you to log in on the first deploy. ## Credentials ```sh npx wrangler secret put DISCORD_PUBLIC_KEY --name my-bot npx wrangler secret put DISCORD_BOT_TOKEN --name my-bot ``` Your endpoint is `https://my-bot..workers.dev/interactions`, which `deploy` prints. If you deploy the Worker yourself with your own Wrangler config, you can read bindings explicitly instead of through `process.env`. Pass `cloudflare()` a factory, and make the file that exports it the Worker's `main`. `discord0 deploy` doesn't support this form. It wraps your entry point's default export in `cloudflare()` again, so the factory never gets the bindings. The factory runs on each request, so cache the app if you want one Worker isolate to reuse its in-memory rate-limit state. To share rate limits across isolates, pass a shared `rateLimitStore`, as in [`examples/rate-limit-store`](https://github.com/natebabyak/discord0/tree/main/examples/rate-limit-store). This factory caches the app in a module variable: ```ts interface Env { DISCORD_PUBLIC_KEY: string; DISCORD_BOT_TOKEN: string; } let app: Discord | undefined; export default cloudflare((env) => { app ??= new Discord({ publicKey: env.DISCORD_PUBLIC_KEY, token: env.DISCORD_BOT_TOKEN, }); return app; }); ``` ## Deferred work The adapter passes deferred work to the Worker's [`ctx.waitUntil()`](https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil). Worker cold starts are typically tens of milliseconds, so the adapter keeps the global **2000ms** `autoDeferAfterMs` default when you leave it unset. Set `autoDeferAfterMs` on `new Discord()` to override. See [Deferred work](/guides/deferred-work/#per-host-defaults). - **30 seconds after the response.** `waitUntil` extends a request for up to 30 seconds after the response is sent. Promises still pending after that are cancelled. The 30 seconds are shared by all `waitUntil` work in the request. The app responds when it defers, 2 seconds in by default, so a slow handler has about 32 seconds in total. - **CPU time.** Workers on the Free plan get 10 ms of CPU time per request. Paid plans default to 30 seconds and can raise it to 5 minutes with `limits.cpu_ms`. Waiting on `fetch()` and other I/O doesn't count toward CPU time, so most handlers that wait on APIs use very little. ([Limits](https://developers.cloudflare.com/workers/platform/limits/#cpu-time)) - HTTP-triggered Workers have no wall-clock duration limit of their own. ([Limits](https://developers.cloudflare.com/workers/platform/limits/#duration)) For work that takes longer than 30 seconds, send it to [Cloudflare Queues](https://developers.cloudflare.com/queues/) or [Workflows](https://developers.cloudflare.com/workflows/) and edit the reply from there within Discord's 15-minute window. ## Scheduled tasks Each [scheduled task](/guides/scheduled-tasks/)'s expression becomes a Cron Trigger in `wrangler.json`, and the Worker's `scheduled()` handler runs every task on the trigger that fired. Cron Triggers run in UTC, so tasks must use UTC. Tasks that share an expression share one trigger. Workers Free allows 5 Cron Triggers per account and 10 ms of CPU per run, which a task that does much work can exceed. Workers Paid allows 1,000. Trigger changes can take up to 15 minutes to apply. # Vercel Functions Source: https://discord0.babyak.dev/adapters/vercel/ `@discord0/adapter-vercel` deploys your app as a Vercel Function with the [Vercel CLI](https://vercel.com/docs/cli). ```sh npx discord0 init my-bot --adapter vercel ``` ## What deploy generates `.discord0/vercel` contains: - `api/interactions.mjs`, - a `package.json` that depends on `@vercel/functions` and pins Node.js 22, - a `vercel.json` that rewrites `/interactions` and each [webhook](/guides/webhooks/) path to the function, and - a `.vercelignore` that keeps source maps out of the upload. The Vercel CLI asks you to log in and link a project on the first deploy. Deploys are previews unless you pass `--prod`: ```sh npx discord0 deploy --prod ``` Use the production domain for your Interactions Endpoint URL. Preview URLs change with each deploy and may be behind [Deployment Protection](https://vercel.com/docs/deployment-protection), which would block Discord's requests. ## Credentials Add `DISCORD_PUBLIC_KEY` and `DISCORD_BOT_TOKEN` in **Project Settings → Environment Variables**, or from `.discord0/vercel`: ```sh cd .discord0/vercel npx vercel env add DISCORD_PUBLIC_KEY production npx vercel env add DISCORD_BOT_TOKEN production ``` Variables apply to new deployments, so deploy again after adding them. ## Deferred work The adapter passes deferred work to [`waitUntil()` from `@vercel/functions`](https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package#waituntil). When you leave `autoDeferAfterMs` unset, the adapter defaults it to **1000ms**. Cold starts often take 0.7 to 1.6 seconds before the handler runs, and the lower default still fits the acknowledgement inside Discord's 3-second window. Set `autoDeferAfterMs` on `new Discord()` to override. See [Deferred work](/guides/deferred-work/#per-host-defaults). - **The function's maximum duration.** Promises passed to `waitUntil` share the function's timeout. Vercel cancels them if the function times out. - With [fluid compute](https://vercel.com/docs/fluid-compute), on by default, the default maximum duration is 300 seconds on every plan. Hobby can't raise it. Pro and Enterprise can raise it to 800 seconds. ([Duration limits](https://vercel.com/docs/functions/configuring-functions/duration#duration-limits)) - `deploy` rewrites `vercel.json` each time, so set a longer duration as the project default in **Project Settings → Functions** rather than in the generated file. ## Scheduled tasks Each [scheduled task](/guides/scheduled-tasks/) becomes a Cron Job in `vercel.json` that calls `/api/tasks?task=`, served by `api/tasks.mjs`. Set `CRON_SECRET` in the project. Vercel sends it in the `Authorization` header of each cron request, and the route refuses requests without it. Cron Jobs run in UTC, on production deployments only. Hobby allows only schedules that run at most once a day, and runs them anywhere within the scheduled hour. # Netlify Functions Source: https://discord0.babyak.dev/adapters/netlify/ `@discord0/adapter-netlify` deploys your app as a Netlify Function with the [Netlify CLI](https://docs.netlify.com/api-and-cli-guides/cli-guides/get-started-with-netlify-cli/). ```sh npx discord0 init my-bot --adapter netlify ``` ## What deploy generates `.discord0/netlify` contains: - `functions/interactions.mjs`, which serves `/interactions` and each [webhook](/guides/webhooks/) path, - a `netlify.toml`, - a placeholder `public/index.html`, and - a `package.json` that sets `engines.node` to `22.x`. The Netlify CLI asks you to log in and link a project on the first deploy. Deploys are drafts unless you pass `--prod`: ```sh npx discord0 deploy --prod ``` Use the production URL for your Interactions Endpoint URL. ## Credentials Add `DISCORD_PUBLIC_KEY` and `DISCORD_BOT_TOKEN` in **Project configuration → Environment variables**, or from `.discord0/netlify`: ```sh cd .discord0/netlify npx netlify-cli env:set DISCORD_PUBLIC_KEY npx netlify-cli env:set DISCORD_BOT_TOKEN ``` Variables apply to new deploys, so deploy again after setting them. ## Deferred work The adapter passes deferred work to the function's [`context.waitUntil()`](https://docs.netlify.com/build/functions/api/#waituntil). When you leave `autoDeferAfterMs` unset, the adapter defaults it to **500ms**. A cold start can use most of Discord's 3-second window before the handler runs, and the lower default still leaves room for the acknowledgement. Set `autoDeferAfterMs` on `new Discord()` to override. See [Deferred work](/guides/deferred-work/#per-host-defaults). - **60 seconds in total.** A function can run until its execution time limit, and that limit includes all `waitUntil` work. Synchronous functions have a 60-second limit, which you can't change. ([Default values](https://docs.netlify.com/build/functions/configuration/#default-values)) - Netlify bills and logs the full duration, until the deferred work finishes. Netlify's background functions run for up to 15 minutes, but they answer with an immediate `202` and no body, which Discord doesn't accept as an interaction response. For longer jobs, trigger a background function from your handler and edit the reply from there. ## Scheduled tasks Each [scheduled task](/guides/scheduled-tasks/) becomes a scheduled function, `functions/task-.mjs`. Scheduled functions run in UTC, on published deploys only, and stop after 30 seconds. # AWS Lambda Source: https://discord0.babyak.dev/adapters/aws/ `@discord0/adapter-aws` deploys your app as an AWS Lambda function with a [Function URL](https://docs.aws.amazon.com/lambda/latest/dg/urls-configuration.html), using [Serverless Framework v3](https://github.com/serverless/serverless/tree/v3). Version 3 deploys with only your AWS credentials. Version 4 requires a Serverless account or license key. ```sh npx discord0 init my-bot --adapter aws ``` ## What deploy generates `.discord0/aws` contains `index.mjs`, a `package.json`, and a `serverless.json` that creates: - a Node.js 22 function on `arm64` with 256 MB of memory and a 60-second timeout, and - a Function URL with `RESPONSE_STREAM` invoke mode. Serverless uses your [AWS CLI credentials](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html). Deploys go to the `dev` stage unless you pass `--prod`, which deploys the `prod` stage. Your endpoint is the Function URL followed by `/interactions`, which `deploy` prints. `npx serverless@3 info` in `.discord0/aws` shows it again. ## Credentials The function reads `DISCORD_PUBLIC_KEY` and `DISCORD_BOT_TOKEN` from SSM Parameter Store under `//`, where `` is your `package.json` name in lowercase, with each run of other characters replaced by a hyphen. For example, `@acme/my-bot` becomes `acme-my-bot`. `serverless.json` shows the exact paths. Serverless resolves them at deploy time, so create them **before** the first deploy: ```sh aws ssm put-parameter --name /my-bot/DISCORD_PUBLIC_KEY --type String --value aws ssm put-parameter --name /my-bot/DISCORD_BOT_TOKEN --type SecureString --value ``` ## Deferred work Lambda has no `waitUntil`. Instead, the adapter uses [response streaming](https://docs.aws.amazon.com/lambda/latest/dg/configuration-response-streaming.html): it streams the response to Discord, ends the stream, and then waits for every pending promise before the handler returns. When you leave `autoDeferAfterMs` unset, the adapter defaults it to **1000ms**. Cold starts often take 0.7 to 1.5 seconds before the handler runs, and the lower default still fits the acknowledgement inside Discord's 3-second window. Set `autoDeferAfterMs` on `new Discord()` to override. See [Deferred work](/guides/deferred-work/#per-host-defaults). - **The function timeout.** The invocation lasts until all deferred work settles, so the work must finish within the function timeout: 60 seconds in the generated config. Lambda allows timeouts up to 1,800 seconds. ([Timeout](https://docs.aws.amazon.com/lambda/latest/dg/configuration-timeout.html)) - `deploy` rewrites `serverless.json` each time, so a timeout you change in the console or with the AWS CLI resets to 60 seconds on the next deploy. - You're billed for the full duration, including deferred work. - Function URLs don't support response streaming inside a VPC, so the function can't be attached to one. ## Scheduled tasks With [scheduled tasks](/guides/scheduled-tasks/), `serverless.json` adds a `tasks` function with a 300-second timeout and an EventBridge Scheduler schedule for each task, in the task's time zone. Deploy converts each expression to EventBridge's six-field form. EventBridge can't combine a day of the month with a day of the week, so deploy rejects an expression that sets both. Split it into two tasks. Scheduler bills per invocation. # Node.js server Source: https://discord0.babyak.dev/adapters/node/ `@discord0/adapter-node` builds a Node.js HTTP server that you run yourself, on any machine or container that can serve HTTPS. ```sh npx discord0 init my-bot --adapter node ``` ## Build and run `discord0 deploy` builds `.discord0/node/index.mjs` and syncs commands, but doesn't upload anything. Start the server from that directory: ```sh cd .discord0/node DISCORD_PUBLIC_KEY=... DISCORD_BOT_TOKEN=... node index.mjs ``` It listens on `PORT`, or 3000, on every interface. Discord connects only over HTTPS, so put it behind a reverse proxy or load balancer that terminates TLS, and set `https:///interactions` as the Interactions Endpoint URL. ## Use it in your own server To mount the app in an existing server, use `node(app)` as a request listener: ```ts createServer(node(app)).listen(3000); ``` In an Express-style server, mount it before any body parser, since the app verifies Discord's signature against the raw body. `serve(app, { port, hostname, signals, tasks })` starts a server with graceful shutdown. The built `index.mjs` runs it. ## Deferred work The server is a long-lived process, so deferred work keeps running after the response with no host limit. Discord's 15-minute token lifetime is the only bound. On `SIGINT` or `SIGTERM`, the server stops accepting requests, waits for in-flight requests and deferred work to finish, then exits. A second signal exits at once. Pass `signals: false` to `serve()` to handle signals yourself, and call `close()` or the handler's `idle()` to wait for pending work. Deferred work lives in memory, so give your process manager a stop timeout longer than your slowest handler. Otherwise it kills the process before the work finishes: - `docker stop` waits 10 seconds by default. Raise it with `--time` or [`stop_grace_period`](https://docs.docker.com/reference/compose-file/services/#stop_grace_period). ([docker stop](https://docs.docker.com/reference/cli/docker/container/stop/)) - Kubernetes waits `terminationGracePeriodSeconds`, 30 seconds by default. ([Pod termination](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-termination)) - systemd waits `TimeoutStopSec`, 90 seconds by default. ([systemd.service](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#TimeoutStopSec=)) ## Scheduled tasks `serve()` runs [scheduled tasks](/guides/scheduled-tasks/) in the server process, in each task's time zone, while the server is up. Every copy of the server runs every task, so if you run more than one, set `DISCORD0_TASKS=off` in all but one, or pass `tasks: false` to `serve()`. On shutdown, the server waits for running tasks to finish. # Bun server Source: https://discord0.babyak.dev/adapters/bun/ `@discord0/adapter-bun` builds a [`Bun.serve`](https://bun.sh/docs/api/http) server that you run yourself, on any machine or container that can serve HTTPS. ```sh npx discord0 init my-bot --adapter bun ``` ## Build and run `discord0 deploy` builds `.discord0/bun/index.js` and syncs commands, but doesn't upload anything. Start the server from that directory: ```sh cd .discord0/bun DISCORD_PUBLIC_KEY=... DISCORD_BOT_TOKEN=... bun index.js ``` It listens on `PORT`, or 3000, on every interface. Discord connects only over HTTPS, so put it behind a reverse proxy or load balancer that terminates TLS, and set `https:///interactions` as the Interactions Endpoint URL. ## Use it in your own server `bun(app)` returns a `fetch` handler for `Bun.serve`, plus `idle()`, which resolves once deferred work has finished: ```ts const handler = bun(app); Bun.serve({ port: 3000, fetch: handler.fetch }); ``` `serve(app, { port, hostname, signals, tasks })` starts a server with graceful shutdown. The built `index.js` runs it. ## Deferred work The server is a long-lived process, so deferred work keeps running after the response with no host limit. Discord's 15-minute token lifetime is the only bound. On `SIGINT` or `SIGTERM`, the server stops accepting requests, waits for in-flight requests and deferred work to finish, then exits. A second signal exits at once. Pass `signals: false` to `serve()` to handle signals yourself, and call `close()` or the handler's `idle()` to wait for pending work. Deferred work lives in memory, so give your process manager a stop timeout longer than your slowest handler. Otherwise it kills the process before the work finishes: - `docker stop` waits 10 seconds by default. Raise it with `--time` or [`stop_grace_period`](https://docs.docker.com/reference/compose-file/services/#stop_grace_period). ([docker stop](https://docs.docker.com/reference/cli/docker/container/stop/)) - Kubernetes waits `terminationGracePeriodSeconds`, 30 seconds by default. ([Pod termination](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-termination)) - systemd waits `TimeoutStopSec`, 90 seconds by default. ([systemd.service](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#TimeoutStopSec=)) ## Scheduled tasks `serve()` runs [scheduled tasks](/guides/scheduled-tasks/) with `Bun.cron` in the server process, in each task's time zone, while the server is up. Every copy of the server runs every task, so if you run more than one, set `DISCORD0_TASKS=off` in all but one, or pass `tasks: false` to `serve()`. On shutdown, the server waits for running tasks to finish. # CLI Source: https://discord0.babyak.dev/reference/cli/ The `discord0` CLI ships with the `discord0` package. Run it with `npx discord0`, `pnpm exec discord0`, `yarn discord0`, or `bun x discord0`, or through the starter's package scripts. The CLI runs on Bun. When Bun 1.4.4 or newer starts it, the CLI runs in that process. Otherwise it runs on the Bun binary that `discord0` installs as an optional dependency (`@oven/bun-`), so you don't need Bun yourself. With Yarn, the starter's `.yarnrc.yml` installs into `node_modules`, because Bun doesn't read Plug'n'Play. Settings in [`discord0.config.ts`](/guides/configuration/) apply when flags don't override them. `-h` or `--help` prints usage. `discord0 sync --help` and `discord0 deploy --help` print the options for those commands. `discord0 test --help` prints the help for `bun test`. ## Interactive prompts When stdin and stdout are both TTYs and `CI` is unset, `discord0` prompts for missing arguments. `init` and `sync` prompt even for options that have a default, with the default preselected. For example, `init` prompts for the directory, then for the adapter with Cloudflare preselected. Run `discord0` with no command to pick one from a list. - Every prompt has a matching flag or argument. Passing a flag skips only that prompt. The CLI still prompts for the other missing values. - Prompts work on all platforms, including Windows. - With `-y`, `--yes`, `--no-interactive`, or `CI` set, or when stdin or stdout isn't a TTY, the CLI never prompts. It uses defaults and exits with an error when a required value is missing. | Option | Description | | ------------------ | ------------------------------------------------------------------------------- | | `-y`, `--yes` | Accept defaults and skip prompts (all commands except `test`). | | `--no-interactive` | Never prompt; use defaults or error on missing required values (except `test`). | ## `init` ```sh discord0 init [directory] [--directory ] [--adapter ] [-y|--yes] [--no-interactive] ``` Copies the starter into `directory`, or the current directory, which must be new or empty. It doesn't install anything. | Option | Description | | -------------------- | -------------------------------------------------------------------- | | `--directory ` | Target directory (alternative to the positional `directory`). | | `--adapter ` | `cloudflare` (default), `vercel`, `netlify`, `aws`, `node`, or `bun` | | `-y`, `--yes` | Accept defaults (`.` and `cloudflare`) without prompting. | | `--no-interactive` | Never prompt; use defaults. | ## `dev` ```sh discord0 dev [entrypoint] [--guild ] [--no-sync] [--tunnel] ``` Serves the app at `http://127.0.0.1:3000/interactions` (set `PORT` to change the port) with hot reload, loading `.env` and `.env.local`. See [Local development](/start/local-development/). | Option | Description | | -------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `--guild ` | Sync commands to this server on start and whenever they change. Default: `guild` from the config, unless `sync.dev` is `false`. | | `--no-sync` | Don't sync commands. | | `--tunnel` | Start a Cloudflare Quick Tunnel and print the HTTPS `/interactions` URL for the Developer Portal. | ## `sync` ```sh discord0 sync [entrypoint] [--scope ] [--guild ] [-y|--yes] [--no-interactive] ``` Registers the app's commands with Discord, replacing the current set in that scope. Loads `.env` and `.env.local` for `DISCORD_BOT_TOKEN` and the optional `APPLICATION_ID`. | Option | Description | | ------------------------- | ---------------------------------------------------------------------- | | `--scope ` | Every server (default), or the test server from `guild` in the config. | | `--guild ` | Sync to this server. Implies `--scope guild`. | | `-y`, `--yes` | Accept defaults (`global`) without prompting. | | `--no-interactive` | Never prompt; use defaults or error if a guild ID is required. | ## `deploy` ```sh discord0 deploy [adapter] [entrypoint] [options] [-- ] ``` Bundles the entry point's default export with the adapter into `.discord0/`, writes each [scheduled task](/guides/scheduled-tasks/) and [webhook route](/guides/webhooks/), and the [events endpoint](/guides/events/) when the app handles webhook events, into the host's config, uploads it with the provider's CLI, then syncs commands. It prints each webhook URL and the Webhook Events URL next to the Interactions endpoint. An adapter name loads `@discord0/adapter-` instead of the config's adapter. The `node` and `bun` adapters build a server to run yourself instead of uploading. See [Deploy](/start/deploy/). | Option | Description | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `--adapter ` | Host adapter (alternative to the positional `adapter`). | | `--prod` | Production on Vercel and Netlify, the `prod` stage on AWS. Default: preview, draft, or the `dev` stage. No effect on Cloudflare. | | `--dry-run` | Build without uploading or syncing. | | `--scope ` | Sync scope. Default: `sync.deploy` in the config, or `global`. | | `--guild ` | Sync commands to one server instead of globally. | | `--no-sync` | Skip command sync. | | `-y`, `--yes` | Skip discord0's own prompts (pass provider `--yes` after `--`). | | `--no-interactive` | Never prompt; error if required values (such as adapter) are missing. | Flags after `--` pass through to the provider's CLI unchanged. ## `task` ```sh discord0 task [name] [entrypoint] [--name ] [-y|--yes] [--no-interactive] ``` Runs one [scheduled task](/guides/scheduled-tasks/) once, now, loading `.env` and `.env.local`. When `name` is omitted on a TTY with `CI` unset, prompts to choose from the app's registered tasks. It exits with an error if the task throws. | Option | Description | | ------------------ | ------------------------------------------------- | | `--name ` | Task name (alternative to the positional `name`). | | `-y`, `--yes` | Skip prompts (errors if no task name is passed). | | `--no-interactive` | Never prompt (errors if no task name is passed). | ## `test` ```sh discord0 test [bun test options] ``` Runs `bun test` in the project on the Bun the CLI uses, so npm, pnpm, and Yarn projects need no Bun of their own. Options pass through to `bun test`. See [Testing](/guides/testing/). ## Environment variables | Variable | Used by | Description | | -------------------- | ----------------------------------- | -------------------------------------------------------------------------------------- | | `DISCORD_PUBLIC_KEY` | The app | Verifies that requests come from Discord. Falls back to `PUBLIC_KEY`. | | `DISCORD_BOT_TOKEN` | The app, `sync`, `dev`, `deploy` | Sends replies and syncs commands. Falls back to `BOT_TOKEN`. | | `APPLICATION_ID` | `sync`, `dev`, `deploy` | Optional. Falls back to `DISCORD_APPLICATION_ID`, then to a lookup with the bot token. | | `DISCORD_GUILD_ID` | `discord0.config.ts` in the starter | Your test server's ID. | | `PORT` | `dev`, the Node.js and Bun servers | The port to listen on. Default: 3000. | | `CRON_SECRET` | The Vercel task route | Required for scheduled tasks on Vercel. | | `DISCORD0_TASKS` | The Node.js and Bun servers | `off`, `false`, or `0` stops this server from running scheduled tasks. | | `CI` | The CLI | Any value other than empty, `0`, or `false` disables interactive prompts. | # Errors Source: https://discord0.babyak.dev/reference/errors/ Every error discord0 throws or logs starts with a stable code in brackets, followed by what went wrong, why, and how to fix it: ```text [DUPLICATE_COMMAND] Duplicate command: ban Why: Discord identifies a command by its name and type, so the second definition would replace the first when commands sync. Fix: Rename one of them, or move one into a sub-app mounted with `app.route()` so it becomes a subcommand. Docs: https://github.com/natebabyak/discord0/blob/main/packages/discord0/ERRORS.md#duplicate_command ``` Thrown errors are `Discord0Error` instances (or subclasses such as `ValidationError` and `InteractionAlreadyRepliedError`) with `code`, `detail`, `why`, `fix`, and `docs` properties. Match on `code`, which never changes between releases, rather than on the message: ```ts try { app.command("ban", "Ban a member", ban); } catch (error) { if (error instanceof Discord0Error && error.code === "DUPLICATE_COMMAND") { // ... } } ``` Errors from Discord's API are `DiscordAPIError` instances instead, with Discord's `status`, numeric `code`, and `errors`, plus a `hint` for common codes. See [DISCORD_API_ERROR](#discord_api_error). This page is generated from `packages/discord0/src/errors.ts`. A copy ships in the package at `node_modules/discord0/ERRORS.md`. ## Index - **App setup:** [INVALID_APP_OPTION](#invalid_app_option), [APP_SEALED](#app_sealed) - **Commands:** [INVALID_COMMAND_NAME](#invalid_command_name), [INVALID_DESCRIPTION](#invalid_description), [DUPLICATE_COMMAND](#duplicate_command), [TOO_MANY_COMMANDS](#too_many_commands), [TOO_MANY_SUBCOMMANDS](#too_many_subcommands), [EMPTY_COMMAND_GROUP](#empty_command_group), [COMMAND_TOO_DEEP](#command_too_deep), [SUBCOMMAND_FIELD](#subcommand_field), [COMMAND_TOO_LARGE](#command_too_large), [DUPLICATE_AUTOCOMPLETE](#duplicate_autocomplete), [INVALID_COMMAND_OPTIONS](#invalid_command_options) - **Sub-apps:** [INVALID_MOUNT](#invalid_mount), [SUB_APP_CONFIGURED](#sub_app_configured), [MOUNT_CONTEXT_MENU](#mount_context_menu) - **Components and modals:** [INVALID_CUSTOM_ID_TEMPLATE](#invalid_custom_id_template), [INVALID_CUSTOM_ID](#invalid_custom_id), [DUPLICATE_HANDLER](#duplicate_handler), [INVALID_COMPONENT](#invalid_component) - **Responding to interactions:** [ALREADY_ACKNOWLEDGED](#already_acknowledged), [NOT_ACKNOWLEDGED](#not_acknowledged), [EPHEMERAL_MISMATCH](#ephemeral_mismatch), [MODAL_WITHOUT_MESSAGE](#modal_without_message), [INVALID_AUTOCOMPLETE_CHOICES](#invalid_autocomplete_choices) - **Scheduled tasks:** [INVALID_TASK](#invalid_task), [INVALID_CRON](#invalid_cron), [INVALID_TIMEZONE](#invalid_timezone), [DUPLICATE_TASK](#duplicate_task), [UNKNOWN_TASK](#unknown_task), [NO_SCHEDULED_TASK](#no_scheduled_task), [TASKS_UNSUPPORTED](#tasks_unsupported) - **Webhooks and events:** [INVALID_WEBHOOK](#invalid_webhook), [WEBHOOK_NEEDS_VERIFY](#webhook_needs_verify), [PATH_CONFLICT](#path_conflict), [MISSING_HANDLER](#missing_handler), [INVALID_EVENT_TYPE](#invalid_event_type), [INVALID_EVENT_BODY](#invalid_event_body), [INVALID_WEBHOOK_URL](#invalid_webhook_url) - **Credentials and REST:** [MISSING_PUBLIC_KEY](#missing_public_key), [INVALID_PUBLIC_KEY](#invalid_public_key), [MISSING_BOT_TOKEN](#missing_bot_token), [APPLICATION_NOT_FOUND](#application_not_found), [INVALID_REST_REQUEST](#invalid_rest_request), [INVALID_REST_OPTION](#invalid_rest_option), [DISCORD_API_ERROR](#discord_api_error) - **Deploy and CLI:** [INVALID_CONFIG](#invalid_config), [GUILD_REQUIRED](#guild_required), [ADAPTER_REQUIRED](#adapter_required), [ADAPTER_NOT_FOUND](#adapter_not_found), [INVALID_ADAPTER](#invalid_adapter), [INVALID_ENTRY](#invalid_entry), [APP_LOAD_FAILED](#app_load_failed), [BUILD_FAILED](#build_failed), [UNSUPPORTED_RUNTIME](#unsupported_runtime), [ADAPTER_FAILED](#adapter_failed), [INIT_FAILED](#init_failed) - **Testing:** [INVALID_TEST_INPUT](#invalid_test_input) - **Runtime logs:** [HANDLER_FAILED](#handler_failed), [BACKGROUND_WORK_FAILED](#background_work_failed), [WEBHOOK_VERIFY_FAILED](#webhook_verify_failed), [WEBHOOK_SECRET_UNSET](#webhook_secret_unset) ## App setup ### INVALID_APP_OPTION **What you see:** An option passed to `new Discord()` is out of range. **Why:** discord0 checks options when the app is built, so a bad value fails at startup rather than on the first interaction. **Fix:** Correct the option named in the message. `autoDeferAfterMs` must be from 0 to 2999, since Discord drops interactions that aren't answered within 3 seconds. ```ts new Discord({ autoDeferAfterMs: 2000 }); ``` ### APP_SEALED **What you see:** A handler was registered on a sub-app after it was mounted. **Why:** `app.route()` copies a sub-app's commands, components, tasks, and webhooks when it mounts it. Later registrations would be silently lost, so the sub-app is sealed instead. **Fix:** Register every handler on the sub-app before passing it to `app.route()`, and mount inner sub-apps before outer ones. ```ts const tickets = new Discord().command("open", "Open a ticket", () => "Opened"); app.route("ticket", "Manage tickets", tickets); // mount last ``` ## Commands ### INVALID_COMMAND_NAME **What you see:** A command, subcommand, or group name breaks Discord's naming rules. **Why:** Discord rejects slash command names that aren't 1-32 lowercase letters, digits, `-`, or `_`, and the whole sync fails. **Fix:** Rename it to lowercase without spaces, such as `"open-ticket"`. Show a different name per language with `name_localizations`. ### INVALID_DESCRIPTION **What you see:** A slash command or subcommand is missing its description, or it is too long. **Why:** Discord requires every slash command, subcommand, and group to have a description of 1-100 characters. **Fix:** Pass a description as the second argument, or as `description` in the config object. ```ts app.command("ping", "Replies with Pong!", () => "Pong!"); ``` ### DUPLICATE_COMMAND **What you see:** Two commands of the same type share a name. **Why:** Discord identifies a command by its name and type, so the second definition would replace the first when commands sync. **Fix:** Rename one of them, or move one into a sub-app mounted with `app.route()` so it becomes a subcommand. ### TOO_MANY_COMMANDS **What you see:** The app defines more commands of one type than Discord allows. **Why:** Discord allows 100 slash commands, 15 user commands, and 15 message commands per app. **Fix:** Group related slash commands into sub-apps with `app.route()`. Each mount counts as one command and can hold 25 subcommands or groups. ### TOO_MANY_SUBCOMMANDS **What you see:** A command or group has more than 25 subcommands and groups. **Why:** Discord allows at most 25 options, including subcommands and groups, on each level of a command. **Fix:** Split the sub-app into groups by mounting smaller sub-apps inside it with `route()`. ### EMPTY_COMMAND_GROUP **What you see:** A mounted sub-app has no slash commands. **Why:** Mounting with a name turns the sub-app's commands into subcommands, and Discord rejects a command with no subcommands. **Fix:** Register at least one `command()` on the sub-app before mounting it, or mount it without a name: `app.route(subApp)`. ### COMMAND_TOO_DEEP **What you see:** Commands nest deeper than command → group → subcommand. **Why:** Discord supports at most two levels below a command: a group and its subcommands. **Fix:** Flatten the tree. Mount sub-apps at most twice deep, and don't put Subcommand options in `options` yourself; mount a sub-app instead. ### SUBCOMMAND_FIELD **What you see:** A subcommand sets a field only top-level commands support. **Why:** Fields such as `default_member_permissions`, `contexts`, and `nsfw` apply to a whole top-level command, so Discord ignores or rejects them on subcommands. **Fix:** Set the field on the mount instead. ```ts app.route( { name: "mod", description: "Moderation", default_member_permissions: "8" }, moderation, ); ``` ### COMMAND_TOO_LARGE **What you see:** A command's names, descriptions, and choices exceed 8000 characters. **Why:** Discord caps each top-level command, counting all its subcommands, options, choices, and localizations, at 8000 characters. **Fix:** Shorten descriptions, move choices to autocomplete, or split the command into several top-level commands. ### DUPLICATE_AUTOCOMPLETE **What you see:** Two autocomplete handlers target the same command. **Why:** Each command path gets one autocomplete handler, which answers for every option of that command. **Fix:** Keep one handler and branch on `c.focused?.name` to answer for each option. ```ts app.autocomplete("ticket open", (c) => c.focused?.name === "team" ? teams : priorities, ); ``` ### INVALID_COMMAND_OPTIONS **What you see:** An interaction's options don't match the command's definition. **Why:** The command registered with Discord differs from the one in your code, usually because commands haven't been synced since the definition changed. discord0 rejects the interaction rather than hand your handler bad data. **Fix:** Sync commands again with `discord0 sync` (or restart `discord0 dev`). Until then, users see the generic `messages.error` reply. ## Sub-apps ### INVALID_MOUNT **What you see:** `app.route()` was called with something it can't mount. **Why:** `route()` takes a sub-app built with `new Discord()`, optionally after a name and description or a config object. A sub-app takes its options from its own commands. **Fix:** Pass the sub-app as the last argument, don't mount an app into itself, and leave `options` and `type` off the mount config. ```ts app.route("ticket", "Manage tickets", tickets); app.route(misc); // no name: its commands stay top-level ``` ### SUB_APP_CONFIGURED **What you see:** A sub-app has constructor options or lifecycle hooks. **Why:** Only the main app serves requests, so options such as `publicKey` and hooks such as `onError` on a sub-app would never run. **Fix:** Create sub-apps with `new Discord()` and no options, and set `beforeHandle`, `afterHandle`, and `onError` on the main app. ### MOUNT_CONTEXT_MENU **What you see:** A sub-app with context menu commands was mounted under a name. **Why:** Discord doesn't allow user and message commands as subcommands. **Fix:** Mount it without a name, `app.route(subApp)`, or move the context menu commands to the main app. ## Components and modals ### INVALID_CUSTOM_ID_TEMPLATE **What you see:** A custom ID template such as `approve:{id}` is malformed. **Why:** Templates are `:`-separated literal and `{param}` segments. Each segment must be non-empty, parameter names must be unique, and the template must fit in Discord's 100-character custom ID. **Fix:** Fix the template named in the message. A template with no `{param}` is just an ID: register the exact string instead, such as `"refresh"`. ```ts app.component("approve:{id}", (c) => c.update(`Approved ${c.params.id}`)); ``` ### INVALID_CUSTOM_ID **What you see:** `CustomId.id()` got parameters it can't encode. **Why:** Every parameter needs a non-empty value without `:`, the separator, and the result must fit in Discord's 100 characters. **Fix:** Pass every parameter, encode values that may contain `:` (for example with `encodeURIComponent`), and keep values short: store large state elsewhere and put its key in the ID. ### DUPLICATE_HANDLER **What you see:** Two component or modal handlers claim the same custom ID. **Why:** discord0 routes each incoming custom ID to exactly one handler; with two candidates the choice would be arbitrary. **Fix:** Give each handler its own custom ID or template. Templates overlap when one ID could match both, such as `vote:{id}` and `vote:{choice}`; add a distinct literal segment, such as `vote:up:{id}`. ### INVALID_COMPONENT **What you see:** A message component or modal breaks Discord's component rules. **Why:** Discord rejects the whole message when one component is invalid, and its error is hard to trace back. discord0 checks components before sending them so the message names the exact field. **Fix:** Correct the component field named in the message. Components v2 messages (with `MessageFlags.IsComponentsV2`) can't also set `content`, `embeds`, `poll`, or stickers. ## Responding to interactions ### ALREADY_ACKNOWLEDGED **What you see:** A handler replied to an interaction twice. **Why:** Discord accepts exactly one initial response per interaction. Later messages must edit the reply or send follow-ups. **Fix:** Use `c.editReply()` to change the reply, or `c.followUp()` to send another message. Returning a value from a handler also replies, so don't both `await c.reply()` and return a string. ```ts app.command("slow", "Slow command", async (c) => { await c.defer(); await c.editReply(await work()); }); ``` ### NOT_ACKNOWLEDGED **What you see:** A handler edited or followed up on an interaction it hasn't answered. **Why:** Edits and follow-ups act on the original response, which doesn't exist until the interaction is acknowledged with a message. **Fix:** Call `c.reply()` or `c.defer()` first. After `c.showModal()`, answer from the modal's handler instead. ### EPHEMERAL_MISMATCH **What you see:** A deferred public reply was finished as ephemeral. **Why:** Discord fixes a reply's visibility when it is deferred, so a later reply can't change it. **Fix:** Defer with the visibility you need, `c.defer(true)` for ephemeral, or send the private message as an ephemeral follow-up. ### MODAL_WITHOUT_MESSAGE **What you see:** `update()` or `deferUpdate()` was called on a modal not opened from a message. **Why:** Only a modal opened from a message component has a message to update. A modal opened from a slash command has none. **Fix:** Check `c.interaction.message` first, or `c.reply()` instead. ### INVALID_AUTOCOMPLETE_CHOICES **What you see:** Autocomplete choices break Discord's rules. **Why:** Discord shows at most 25 choices, and every choice in one response must have the option's type: all strings or all finite numbers. **Fix:** Return at most 25 choices with `.slice(0, 25)`, and give every choice a value of the option's type. ## Scheduled tasks ### INVALID_TASK **What you see:** A task's name or handler is invalid. **Why:** Task names become host resource names (Cloudflare Cron Triggers, EventBridge schedules, Netlify functions), so they're limited to 1-64 lowercase letters, digits, `-`, and `_`. **Fix:** Use a name such as `daily-digest`, and pass a handler function as the last argument. ```ts app.task("daily-digest", "0 9 * * *", (c) => c.send(channelId, "Digest")); ``` ### INVALID_CRON **What you see:** A task's cron expression uses syntax not every host supports. **Why:** discord0 deploys the same schedule to six hosts, so it accepts only what they all share: five fields of numbers, `*`, lists, ranges, and steps. Days of the week run from 0 (Sunday) to 6. **Fix:** Rewrite names such as `MON` as numbers (`1`), and `@daily` as `0 0 * * *`. `L`, `W`, `#`, and `?` have no portable equivalent. ### INVALID_TIMEZONE **What you see:** A task's `timezone` isn't an IANA time zone. **Why:** Hosts that honor time zones need a name from the IANA database; abbreviations such as `EST` are ambiguous. **Fix:** Use a name such as `"America/Toronto"`, or leave `timezone` off for UTC. ### DUPLICATE_TASK **What you see:** Two tasks share a name. **Why:** A task's name identifies its schedule on the host and in `discord0 task `. **Fix:** Rename one task. Tasks in sub-apps share the main app's namespace. ### UNKNOWN_TASK **What you see:** A task was run by a name the app doesn't define. **Why:** `runTask()`, `discord0 task`, and host schedules look tasks up by name. **Fix:** Check the spelling against the names listed in the message. After renaming a task, deploy again so the host's schedule uses the new name. ### NO_SCHEDULED_TASK **What you see:** The host fired a schedule the deployed app has no task for. **Why:** The host's schedules come from the last deploy. A task removed or rescheduled in code still fires until you deploy again. **Fix:** Run `discord0 deploy` so the host's schedules match `app.task()` again. ### TASKS_UNSUPPORTED **What you see:** The adapter can't run the app's scheduled tasks as written. **Why:** Each host has its own scheduler. Some can't run tasks at all, some schedule in UTC only, and EventBridge can't combine a day of the month with a day of the week. **Fix:** Follow the fix in the message, or deploy with an adapter whose scheduler supports the task: aws, node, and bun honor time zones. ## Webhooks and events ### INVALID_WEBHOOK **What you see:** An `app.webhook()` route has an invalid path or options. **Why:** Webhook paths are routed by the host as exact URLs, so they must be absolute, without a trailing slash, query, `.` or `..` segments. **Fix:** Use a path such as `"/webhooks/github"`, HTTP methods such as `["POST"]`, and a positive `maxBodyBytes`. ### WEBHOOK_NEEDS_VERIFY **What you see:** A webhook route has no `verify` option. **Why:** A webhook URL is public, so anyone can post to it. `verify` is required so that skipping verification is a visible choice. **Fix:** Pass `verify: verifyHmac({ ... })` or your own check. Pass `verify: false` only for a source that can't sign requests. ```ts app.webhook( "/webhooks/github", { verify: verifyHmac({ secret: () => process.env.GITHUB_WEBHOOK_SECRET, header: "x-hub-signature-256", prefix: "sha256=", }), }, (c) => new Response(null, { status: 202 }), ); ``` ### PATH_CONFLICT **What you see:** A webhook or events path collides with another route or a path the host reserves. **Why:** Each URL can reach one route. `/interactions` takes only Discord's signed interactions, `/events` takes `app.event()` webhook events, and some hosts reserve paths such as `/api` (Vercel) and `/.netlify` (Netlify). **Fix:** Choose another path, such as `/webhooks/`, or move the events endpoint with `new Discord({ eventsPath })`. ### MISSING_HANDLER **What you see:** `app.event()` or `app.webhook()` was called without a handler function. **Why:** Each route needs a function to run when it's called. **Fix:** Pass the handler as the last argument. ### INVALID_EVENT_TYPE **What you see:** `app.event()` got an event type that isn't Discord's name for one. **Why:** Discord names webhook events in SCREAMING_SNAKE_CASE, and discord0 enables exactly these names in the Developer Portal instructions. **Fix:** Use Discord's name, such as `"APPLICATION_AUTHORIZED"` or `"ENTITLEMENT_CREATE"`. ### INVALID_EVENT_BODY **What you see:** `app.dispatchEvent()` got a body that isn't a Discord webhook event. **Why:** `dispatchEvent()` expects the parsed JSON Discord posts to the events URL: `{ version, application_id, type, event }`. **Fix:** Pass the whole event body. In tests, build one with `discord0/testing`. ### INVALID_WEBHOOK_URL **What you see:** A Discord webhook to post to isn't a webhook URL. **Why:** Posting through a webhook needs its ID and token, which discord0 reads from the URL. **Fix:** Pass the URL Discord shows under Integrations → Webhooks, `https://discord.com/api/webhooks//`, or `{ id, token }`. ## Credentials and REST ### MISSING_PUBLIC_KEY **What you see:** The app received a request before it had a public key. **Why:** Discord signs every interaction with your application's Ed25519 key, and discord0 must check the signature before trusting the request. **Fix:** Set `DISCORD_PUBLIC_KEY` (Developer Portal → General Information → Public Key) in `.env` and in the host's environment, or pass `publicKey` to `new Discord()`. ### INVALID_PUBLIC_KEY **What you see:** The public key isn't a 64-character hex string. **Why:** An Ed25519 public key is 32 bytes, which the Developer Portal shows as 64 hex characters. **Fix:** Copy the Public Key from Developer Portal → General Information again; don't use the bot token or client secret. ### MISSING_BOT_TOKEN **What you see:** A command sync ran without a bot token. **Why:** Registering commands is a REST call that Discord authorizes with the bot token. **Fix:** Set `DISCORD_BOT_TOKEN` (Developer Portal → Bot → Reset Token) in `.env`, or skip syncing with `--no-sync`. ### APPLICATION_NOT_FOUND **What you see:** discord0 couldn't look up which application the bot token belongs to. **Why:** Command sync needs the application ID. Without `APPLICATION_ID`, discord0 asks Discord for it with the token, which failed. **Fix:** Set `APPLICATION_ID` (Developer Portal → General Information → Application ID), and check that `DISCORD_BOT_TOKEN` is current. ### INVALID_REST_REQUEST **What you see:** A REST request targeted a URL outside Discord's API. **Why:** The REST client attaches the bot token to requests, so it refuses any URL other than `https://discord.com/api/v10`. **Fix:** Call Discord's API through `c.rest` or the paths in `discord0/openapi`. Use `fetch` for other services. ### INVALID_REST_OPTION **What you see:** A REST, rate limit, or request limit option is out of range. **Why:** These limits must be positive, finite numbers for requests to be checked and scheduled. **Fix:** Correct the option named in the message, or leave it unset for the default. ### DISCORD_API_ERROR **What you see:** Discord's API rejected a request. **Why:** Discord returned an HTTP error. The error's `status`, `code`, and `errors` say which; the message adds a likely fix for common codes. **Fix:** Read the hint in the message. 401: reset the bot token. 403 or 50001: invite the bot with the `bot` and `applications.commands` scopes. 50035: fix the fields listed in the message. 10062: answer within 3 seconds or let discord0 defer. ## Deploy and CLI ### INVALID_CONFIG **What you see:** `discord0.config.ts` has an invalid setting. **Why:** The CLI validates the config before building, so a typo fails fast instead of deploying with the wrong settings. **Fix:** Correct the setting named in the message. Valid options are `entry`, `adapter`, `guild`, and `sync`. ```ts export default defineConfig({ adapter: adapter(), guild: process.env.DISCORD_GUILD_ID, }); ``` ### GUILD_REQUIRED **What you see:** A guild sync was requested without a server ID. **Why:** Syncing to one server, which updates instantly, needs that server's ID. **Fix:** Pass `--guild `, set `DISCORD_GUILD_ID` in `.env`, or set `guild` in `discord0.config.ts`. Copy the ID with Developer Mode on: right-click the server → Copy Server ID. ### ADAPTER_REQUIRED **What you see:** `discord0 deploy` doesn't know which host to deploy to. **Why:** Each host needs its own bundle and provider CLI. **Fix:** Pass the adapter, `discord0 deploy cloudflare`, or set `adapter` in `discord0.config.ts`. ### ADAPTER_NOT_FOUND **What you see:** The adapter package isn't installed. **Why:** `discord0 deploy ` loads `@discord0/adapter-` from the project's dependencies. **Fix:** Install the package with the command in the message. ### INVALID_ADAPTER **What you see:** The configured adapter isn't a discord0 adapter. **Why:** `adapter` in `discord0.config.ts` must be the object an adapter package's default export returns. **Fix:** Call the adapter: `adapter: cloudflare()`, not `adapter: cloudflare`. ### INVALID_ENTRY **What you see:** The entry point is missing, or doesn't `export default` a Discord app. **Why:** The CLI imports the entry point to read its commands, tasks, and webhooks, and the host calls its `fetch`. **Fix:** Point `entry` (default `src/index.ts`) at the file that ends with `export default app`, where `app = new Discord()`. ### APP_LOAD_FAILED **What you see:** The entry point threw while the CLI loaded it. **Why:** Before building, the CLI runs the entry point to read its tasks, webhooks, and events, so top-level code runs then too. **Fix:** Read the app's output in the message. Move work that needs the host's environment, such as database connections, into handlers. ### BUILD_FAILED **What you see:** Bundling the app for the host failed. **Why:** Each host runs one JavaScript file, so the app and its imports must bundle without assets. **Fix:** Fix the build errors in the message. Import data as JSON or TypeScript instead of other asset types, and keep the entry point outside `.discord0`. ### UNSUPPORTED_RUNTIME **What you see:** An adapter's handler ran outside the runtime it was built for. **Why:** Each adapter wraps the app for one host's runtime and relies on its APIs, such as Lambda's response streaming. **Fix:** Deploy the bundle with `discord0 deploy ` to the matching host, or import the adapter that matches where the code runs. ### ADAPTER_FAILED **What you see:** An adapter produced files discord0 refuses to write. **Why:** Adapters may write only inside `.discord0/`, so a buggy adapter can't overwrite the project. **Fix:** This is a bug in the adapter. Report it with the path from the message. ### INIT_FAILED **What you see:** `discord0 init` can't create a project in the directory. **Why:** `init` never overwrites files, so it needs a new or empty directory. **Fix:** Pass a new directory, `discord0 init my-bot`, or empty the existing one. ## Testing ### INVALID_TEST_INPUT **What you see:** A `discord0/testing` helper got a command, option, or app the app doesn't define. **Why:** The test client builds interactions from the app's own command definitions, the way Discord would, so it rejects names Discord would never send. **Fix:** Use the full path, such as `client.command("ticket open", { title: "Help" })`, and only option names the command defines. ## Runtime logs ### HANDLER_FAILED **What you see:** An interaction, event, task, or webhook handler threw. **Why:** discord0 catches the error so the request still gets an answer: users see the generic `messages.error` reply, webhooks get a 500, and events and tasks are logged. **Fix:** Read the error and stack trace below the message. Report errors elsewhere with `app.onError()`. ### BACKGROUND_WORK_FAILED **What you see:** Work passed to `waitUntil` rejected after the response was sent. **Why:** The response already went out, so the failure can only be logged. **Fix:** Read the error below the message, and catch errors inside the background work if it needs its own handling. ### WEBHOOK_VERIFY_FAILED **What you see:** A webhook's `verify` function threw, so the request was rejected with 401. **Why:** A verifier that throws can't vouch for the request, so discord0 treats it as unverified. **Fix:** Return `false` (or a `Response`) for bad requests instead of throwing, and check the secret and header names. ### WEBHOOK_SECRET_UNSET **What you see:** `verifyHmac()` has no secret, so the webhook answered 503. **Why:** Without the shared secret no request can be verified, so every request is refused until it's set. **Fix:** Set the secret's environment variable on the host, then redeploy if the host needs it.