HTTP interactions
An app can receive its interactions (slash commands, components, autocomplete, modals) as
HTTP POST requests to its Interactions Endpoint URL instead of as gateway events.
Such a bot keeps no connection open: it wakes up for each request, so it runs in any web
server and on serverless platforms such as Cloudflare Workers. What it gives up is every
other event: no messages, members or presences reach it, only interactions.
djs-rs answers these requests with the same Client, routes and reply methods as a
gateway bot. It has no HTTP server of its own: the server the bot already uses hands
each request’s two signature headers and its body to an InteractionsEndpoint, and
sends back what it returns.
This chapter’s program is
http_interactions.rs,
served with axum. It needs the http-interactions feature; a bot
that never logs in to the gateway can leave the gateway out:
djs-rs = { version = "0.1.0-alpha.2", default-features = false, features = ["http-interactions", "hyper"] }
(hyper is the REST client’s HTTP transport; the default features include it, together
with the gateway.)
The routes
Nothing in the routes is specific to HTTP. This is what a gateway bot would register:
/// The bot's routes: exactly what a gateway bot would register.
fn routes(client: &Client) {
client.command("ping", |ctx, cmd| async move {
cmd.reply(&ctx, "Pong! (over HTTP)").await?;
Ok(())
});
// A slow command defers: the HTTP response goes back at once, the edit follows.
client.command("slow", |ctx, cmd| async move {
cmd.defer_reply(&ctx, MessageFlags::empty()).await?;
tokio::time::sleep(Duration::from_secs(5)).await;
cmd.edit_reply(&ctx, "Done, five seconds later.").await?;
Ok(())
});
}
The endpoint
Client::interactions_endpoint makes the endpoint from the app’s public key (the
Developer Portal shows it on the app’s General Information page). Its
handle does everything Discord requires of an endpoint:
/// The `POST` handler of the Interactions Endpoint URL.
async fn interactions(
State(endpoint): State<InteractionsEndpoint>,
headers: HeaderMap,
body: Bytes,
) -> impl IntoResponse {
let header = |name| {
headers
.get(name)
.and_then(|value| value.to_str().ok())
.unwrap_or_default()
};
let signature = header("x-signature-ed25519");
let timestamp = header("x-signature-timestamp");
let (response, background) = endpoint.handle(signature, timestamp, &body).await;
// What the handlers do after their first response (the edit of `/slow`).
tokio::spawn(background);
let status = StatusCode::from_u16(response.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
(
status,
[(header::CONTENT_TYPE, "application/json")],
response.body,
)
}
- It checks the request’s Ed25519 signature, and that its timestamp is at most five minutes old, so a recorded request cannot be replayed. Discord tests this when the URL is saved: it sends forged requests too, which must be refused.
- It answers a
PINGwith aPONG. - It dispatches the interaction like a gateway
INTERACTION_CREATE: theInteractionCreatehandlers, then the routes. - It returns as soon as a handler gives the initial response (
reply,defer_reply,update,show_modal, …), which becomes the HTTP response’s body: no REST request is made for it.
| Status | When |
|---|---|
200 | the initial response (its JSON is the body), or the PONG |
202 | the initial response had files: it was sent through REST instead |
400 | the body is not an interaction |
401 | the signature or the timestamp is wrong |
500 | the handlers ended without an initial response |
handle also returns a future: the rest of the handlers’ work, such as /slow’s edit
after its deferral. The server runs it after answering, here with tokio::spawn.
Serving it
let client = Client::builder(std::env::var("DISCORD_TOKEN")?).build();
routes(&client);
// No `READY` here: the commands are registered through REST (creating one that exists
// updates it).
let application = client.rest().get_current_application().await?;
for command in [
SlashCommandBuilder::new("ping", "Checks that the bot answers").build()?,
SlashCommandBuilder::new("slow", "Answers after five seconds").build()?,
] {
client
.rest()
.create_global_application_command(application.id, &command)
.await?;
}
let endpoint = client.interactions_endpoint(&std::env::var("DISCORD_PUBLIC_KEY")?)?;
let app = Router::new()
.route("/", post(interactions))
.with_state(endpoint);
let port = std::env::var("PORT").unwrap_or_else(|_| "8080".to_owned());
let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}")).await?;
println!("listening on http://127.0.0.1:{port}");
axum::serve(listener, app).await?;
Without a gateway there is no READY to register the commands in, so the program
registers them through REST when it starts. Discord only posts to an HTTPS URL that it can
reach: for a test, a tunnel such as cloudflared tunnel --url http://localhost:8080 gives
the local server one. Saving that URL as the Interactions Endpoint URL in the Developer
Portal sends the first PING; from then on the app’s interactions come over HTTP, not over
the gateway, until the URL is removed.
On Cloudflare Workers
The repository’s
examples/cloudflare-workers
is the same bot as a Worker, built for wasm32-unknown-unknown. There is no hyper there:
the REST client sends its requests through a Transport over the platform’s fetch.
/// djs-rs' REST requests and waits, through Workers' `fetch` and timers (D-404). Their
/// futures are not `Send` (the Workers runtime has one thread); `SendFuture` makes them so.
struct FetchTransport;
impl Transport for FetchTransport {
fn send(
&self,
request: http::Request<Body>,
) -> BoxFuture<'_, Result<http::Response<Bytes>, Box<dyn StdError + Send + Sync>>> {
Box::pin(SendFuture::new(async move {
// `worker::Error` holds JS values, which are not `Send`: keep its message only.
fetch(request)
.await
.map_err(|error| error.to_string().into())
}))
}
fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
Box::pin(SendFuture::new(Delay::from(duration)))
}
}
/// Sends `request` with `fetch` and reads the whole response.
async fn fetch(request: http::Request<Body>) -> worker::Result<http::Response<Bytes>> {
let (parts, body) = request.into_parts();
let headers = Headers::new();
for (name, value) in &parts.headers {
headers.set(name.as_str(), value.to_str().map_err(|e| e.to_string())?)?;
}
let mut init = RequestInit::new();
init.with_method(Method::from(parts.method.as_str().to_owned()))
.with_headers(headers);
if !body.is_empty() {
init.with_body(Some(Uint8Array::from(&body.into_bytes()[..]).into()));
}
let request = Request::new_with_init(&parts.uri.to_string(), &init)?;
let mut response = Fetch::Request(request).send().await?;
let mut builder = http::Response::builder().status(response.status_code());
for (name, value) in response.headers().entries() {
builder = builder.header(name, value);
}
let body = Bytes::from(response.bytes().await?);
builder.body(body).map_err(|e| e.to_string().into())
}
Handlers must be Send, and JavaScript futures are not, so a handler that awaits one (a
fetch, a Delay) wraps it in SendFuture. tokio’s timers do not run in a Worker, so
collectors are not available, and a handler waits with the platform’s timers:
/// The bot's routes: the same functions a gateway bot registers.
fn routes(client: &Client) {
client.command("ping", |ctx, cmd| async move {
cmd.reply(&ctx, "Pong! (from Cloudflare Workers)").await?;
Ok(())
});
client.command("slow", |ctx, cmd| async move {
cmd.defer_reply(&ctx, MessageFlags::empty()).await?;
// The Worker keeps running for this, through `ctx.wait_until` below. Handlers must
// be `Send`: a JS future awaited in one is wrapped in `SendFuture`.
SendFuture::new(Delay::from(Duration::from_secs(5))).await;
cmd.edit_reply(&ctx, "Done, five seconds later.").await?;
Ok(())
});
}
The Worker’s fetch handler builds the client once, passes each request to handle, and
keeps the Worker running for the background work with ctx.wait_until:
/// The endpoint, built by the isolate's first request and reused by the next ones.
static ENDPOINT: OnceLock<InteractionsEndpoint> = OnceLock::new();
fn endpoint(env: &Env) -> worker::Result<&'static InteractionsEndpoint> {
if let Some(endpoint) = ENDPOINT.get() {
return Ok(endpoint);
}
// Rust panics would otherwise show only as `unreachable` in the Workers log.
std::panic::set_hook(Box::new(|info| worker::console_error!("{info}")));
let token = env.secret("DISCORD_TOKEN")?.to_string();
let rest = Rest::builder()
.token(token.clone())
.transport(FetchTransport)
.build();
let client = Client::builder(token).rest(rest).build();
routes(&client);
let public_key = env.secret("DISCORD_PUBLIC_KEY")?.to_string();
let endpoint = client
.interactions_endpoint(&public_key)
.map_err(|e| e.to_string())?;
Ok(ENDPOINT.get_or_init(|| endpoint))
}
#[event(fetch)]
async fn main(mut request: Request, env: Env, ctx: Context) -> worker::Result<Response> {
let endpoint = endpoint(&env)?;
let headers = request.headers();
let signature = headers.get("x-signature-ed25519")?.unwrap_or_default();
let timestamp = headers.get("x-signature-timestamp")?.unwrap_or_default();
let body = request.bytes().await?;
let (response, background) = endpoint.handle(&signature, ×tamp, &body).await;
// The handlers' work after their first response (the edit of `/slow`).
ctx.wait_until(background);
let headers = Headers::new();
headers.set("content-type", "application/json")?;
Ok(Response::from_bytes(response.body)?
.with_status(response.status)
.with_headers(headers))
}
npx wrangler dev runs it locally (with the token and public key in .dev.vars), and
npx wrangler deploy publishes it.
What changes without the gateway
- Only interactions reach the handlers, and the cache holds only what they carry.
- Every handler of a request runs one after another, whatever the client’s
HandlerMode. ctx.shard()is the guild’s shard only when the same client is also logged in to the gateway; otherwise it is a detached one, and gateway requests through it fail.- A collector only sees the interactions of the same process. A platform that spreads requests over many instances (a Worker does) may hand the next click to another one.
- The three-second limit for the initial response holds as on the gateway: a slow command defers first.
The end
That is the guide. The API reference documents every type and method, with its Discord and discord.js counterparts, and the repository’s examples are complete bots. Coming from discord.js? The next page maps what you know to djs-rs.