Skip to content

HTTP bots

Bots that receive interactions over HTTP (an Interactions Endpoint URL) instead of the gateway use @shardlens/http. It runs on Cloudflare Workers, Deno, Bun and Node (for example with @discordjs/core), using Web-standard APIs only.

Terminal window
pnpm add @shardlens/http

You need a running collector and its ingest key (slk_ingest_…). The code on this page takes its types from discord-api-types; install it too if you don’t have it.

wrapInteractionHandler takes the function that answers an interaction and returns one you call the same way. Your answer goes back to Discord unchanged; a handler that throws still throws.

This is a whole bot in one module. It verifies Discord’s signature, answers, and records every interaction:

worker.ts
import { createShardlensHttp, type WaitUntilContext } from '@shardlens/http';
import type { APIInteraction, APIInteractionResponse } from 'discord-api-types/v10';
/** Worker bindings (vars and secrets), or `process.env` and `Deno.env.toObject()` on other runtimes. */
export interface Env {
/** Developer Portal → General Information → Public Key. */
DISCORD_PUBLIC_KEY?: string | undefined;
/** Your collector, for example `https://stats.example.com`. */
SHARDLENS_URL?: string | undefined;
/** `slk_ingest_…`. Keep it in a secret. */
SHARDLENS_INGEST_KEY?: string | undefined;
}
const hex = (s: string) => Uint8Array.from(s.match(/../g) ?? [], (b) => Number.parseInt(b, 16));
/** Discord signs every request with Ed25519, and checks that the endpoint refuses a bad signature with 401. */
async function verified(request: Request, body: string, publicKey: string): Promise<boolean> {
const signature = request.headers.get('x-signature-ed25519');
const timestamp = request.headers.get('x-signature-timestamp');
if (!signature || !timestamp) return false;
try {
const key = await crypto.subtle.importKey('raw', hex(publicKey), { name: 'Ed25519' }, false, ['verify']);
return await crypto.subtle.verify('Ed25519', key, hex(signature), new TextEncoder().encode(timestamp + body));
} catch {
return false;
}
}
// Shardlens finds `ctx` among the arguments, and sends this interaction's events through `ctx.waitUntil`.
async function answer(interaction: APIInteraction, _ctx?: WaitUntilContext): Promise<APIInteractionResponse> {
if (interaction.type === 1) return { type: 1 }; // PING: answered, not recorded
if (interaction.type === 2 && interaction.data.name === 'ping') {
return { type: 4, data: { content: 'Pong!', flags: 64 } };
}
return { type: 4, data: { content: 'Unknown command', flags: 64 } };
}
/** The bot, for any runtime: Workers below, Deno, Bun and Node through their own servers. */
export function createBot(env: Env) {
// Nothing runs until the first interaction: no timers, no network.
const lens = createShardlensHttp({ endpoint: env.SHARDLENS_URL, apiKey: env.SHARDLENS_INGEST_KEY });
const handle = lens.wrapInteractionHandler(answer);
return {
lens,
async fetch(request: Request, ctx?: WaitUntilContext): Promise<Response> {
if (request.method !== 'POST') return new Response('Not found', { status: 404 });
const body = await request.text();
if (!(await verified(request, body, env.DISCORD_PUBLIC_KEY ?? ''))) {
return new Response('Bad request signature', { status: 401 });
}
return Response.json(await handle(JSON.parse(body) as APIInteraction, ctx));
},
};
}
// Cloudflare Workers: secrets arrive with the first request, so the bot is created then.
let bot: ReturnType<typeof createBot> | undefined;
export default {
fetch(request: Request, env: Env, ctx: WaitUntilContext): Promise<Response> {
bot ??= createBot(env);
return bot.fetch(request, ctx);
},
};

The same module runs on every runtime. Only the last few lines, which start the server, differ:

The default export above is the Worker. Keep the URL in wrangler.toml and the two keys in secrets:

wrangler.toml
name = "my-bot"
main = "worker.ts"
compatibility_date = "2026-10-01"
[vars]
SHARDLENS_URL = "https://stats.example.com"
Terminal window
npx wrangler secret put DISCORD_PUBLIC_KEY
npx wrangler secret put SHARDLENS_INGEST_KEY
npx wrangler deploy

For npx wrangler dev, put the same two names in a .dev.vars file, which Git should ignore.

Pass ctx to the wrapped handler, as the module does. Shardlens sends each interaction’s events through ctx.waitUntil, after your response has gone back to Discord.

On Deno, Bun and Node, set DISCORD_PUBLIC_KEY, SHARDLENS_URL and SHARDLENS_INGEST_KEY in the environment. Then put the bot’s public URL in Interactions Endpoint URL in the Developer Portal. Discord checks it with a PING and with a badly signed request, which must get a 401: the module answers both.

For every interaction except PING, exactly the same fields as the discord.js adapter: command, subcommand, options used, context, channel type, install type, locale, member tier, premium, the response type, and how long your answer took against Discord’s 3-second deadline. The user ID is hashed before anything is sent. The interaction token and what users type never leave your bot; nor do option values, unless you list the option in captureOptionValues.

  • Buttons, selects and modals are recorded by their custom ID, with numbers and IDs replaced by *. Buttons and selects are attributed to the command that created their message, and a command that opens a modal is linked to the modal’s submissions.
  • Errors thrown by your handler are recorded by class (never the message) and re-thrown unchanged.
  • Slow answers: a response returned more than 3 seconds after the interaction was created is recorded as a timeout, because Discord will already have shown “The application did not respond”.
  • Deferred replies: the time recorded is the time to your first answer, the deferral. Follow-ups and edits you send through Discord’s REST API afterwards are not recorded.
  • Response objects: a handler may return a Response instead of the body. Shardlens reads the callback type from a copy of a JSON body; your Response is returned as it is.
  • Custom events: lens.track(name, props, { userId, guildId }, ctx) works as in the discord.js adapter. Pass ctx on Workers, or the event waits for the next interaction. For typed events, register them with declare module '@shardlens/http'.
  • With waitUntil (Cloudflare Workers, and anything else whose handler gets an object with a waitUntil method): if any argument you pass to the wrapped handler has waitUntil, Shardlens hashes and sends that request’s events through it, after your response. Nothing is left for a timer, because a Worker’s timers stop with the request that set them. If the collector could not be reached, the next interaction asks it for its settings again.
  • Without waitUntil (a long-running Node, Bun or Deno server): events are batched and sent in the background every 5 seconds, as in the discord.js adapter. Call await lens.shutdown() when the process stops.
  • Serverless without waitUntil: if your platform can stop the process as soon as the response is sent and gives you nothing like waitUntil, await lens.flush() before you return. That adds the collector’s round trip to your answer, so prefer waitUntil where there is one.

Creating the Shardlens instance is free: nothing runs (no timers, no network) until the first interaction that is recorded, so it is safe on runtimes that forbid I/O at startup. A PING, such as Discord checking your endpoint URL, starts nothing.

createShardlensHttp takes the options of the discord.js adapter that make sense without a gateway: endpoint, apiKey, mode, auditIncludeProfile, captureOptionValues, normaliseCustomId, environment, release, optedOut, sampleRate, exporters, dryRun, logger and fetch, described in Configuration. One is its own: instance, a label for this deployment in SDK health (the Worker’s name, for example). Opt-outs and erasure work the same way: lens.optOut(userId), lens.optIn(userId) and await lens.forgetUser(userId).

A complete Worker is in examples/cloudflare-worker.