Introduction
djs-rs is a library for writing Discord bots in Rust. Its API follows discord.js v14 closely (the same clients, events, managers and builders, under Rust names), so what you know from discord.js carries over, and what you learn here carries over to discord.js’s documentation when you need it. Under that API it is built for speed: the gateway’s events are decoded without needless copies, the cache can be tuned or turned off, and every hot path is benchmarked.
This guide walks you from an empty project to a bot that answers commands, keeps state, scales to many shards and talks in voice channels. Each chapter builds on the ones before it, so if you are new to Discord bots, read them in order.
What you need to know
The guide assumes you can read Rust and have written a little async code. If async fn,
.await or Result and ? are new to you, two short detours will make everything here
easier:
- The Rust Programming Language, chapters 1 to 9 and 17 (async).
- The tokio tutorial, up to “Spawning”: djs-rs runs on tokio.
You do not need to know discord.js. When a djs-rs item has a discord.js counterpart, the
guide names it in passing (“discord.js: Client#login”), which helps if you are moving a
bot over, and can be skipped otherwise.
How the guide is written
Every listing in this guide is part of a program that the project’s tests compile, so the
code you read here compiles with the djs-rs it describes. The complete programs live in
book/code/examples:
run any of them with cargo run -p djs-rs-guide --example <name> from a checkout of the
repository.
The state of djs-rs
djs-rs is pre-alpha: it works end to end (the guide’s bots run against Discord), but it
is not on crates.io yet and its API can still change between commits. The
roadmap says what is done and
what comes next. The API reference is published next to this
guide, for the current main; cargo doc --open in your project shows it for the exact
version you use.
Installation
Rust
djs-rs needs Rust 1.89 or newer. Install Rust with rustup if you do not have it, or update it:
rustup update
rustc --version
Two features need a C compiler, because they build C libraries: zstd-stream (the
default gateway compression) and voice (which also needs CMake). On Linux install gcc
or clang (and cmake for voice) from your distribution; on macOS, the Xcode command line
tools (xcode-select --install, and CMake from Homebrew); on Windows, the “Desktop
development with C++” workload of Visual Studio Build Tools, and CMake. If you would rather
not need a C compiler, see Cargo features below.
A Discord server to test in
Bots are tested best in a server of your own, where nothing can go wrong: in the Discord app, press the + at the bottom of the server list and create one. The next chapter adds your bot to it.
The project
Create a binary crate:
cargo new my-bot
cd my-bot
and add djs-rs and an async runtime to its Cargo.toml:
[dependencies]
djs-rs = "0.1.0-alpha.2"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
- djs-rs comes from crates.io. It is in alpha, and its API can still change between
alpha releases; since
cargo updatemay move to a newer alpha, write"=0.1.0-alpha.2"to upgrade only when you choose to. The newest, unreleased code is in its Git repository:djs-rs = { git = "https://github.com/kotoanidev/djs-rs" }. - tokio runs the bot.
macrosgives#[tokio::main],rt-multi-threadthe runtime that spreads the bot’s work over your CPU’s cores,signala way to notice Ctrl+C. - tracing-subscriber prints the library’s logs: djs-rs reports what it does
(connecting, reconnecting, a handler’s error) through
tracing, and without a subscriber those messages go nowhere.
Run cargo build once now. The first build compiles every dependency and takes a few
minutes; later builds only compile what changed.
Cargo features
djs-rs keeps optional parts behind features, so a bot only builds what it uses:
| Feature | On by default | What it adds |
|---|---|---|
gateway | yes | The gateway: client.login(), the shards and their events. |
hyper | yes | The REST client’s HTTP transport. |
zstd-stream | yes | Compresses the gateway’s traffic with zstd (needs a C compiler). |
zlib-stream | The same with zlib, in pure Rust: no C compiler. | |
native-roots | Trusts your operating system’s certificates too (for a corporate proxy). | |
sharding | Runs the bot’s shards in several processes (the Sharding chapter). | |
voice | Joins voice channels, plays and receives audio (the Voice chapter). | |
http-interactions | Answers interactions at an Interactions Endpoint URL (the HTTP interactions chapter). |
To build without a C compiler, turn the default off and pick zlib:
djs-rs = { version = "0.1.0-alpha.2", default-features = false, features = ["zlib-stream"] }
With the project set up, the next chapter creates the bot on Discord’s side and writes its first lines.
Your first bot
This chapter creates a bot on Discord’s side, adds it to your test server and writes a
program that answers !ping with Pong!. It is small, but it has every part a bot has: a
client, the events it asks Discord for, handlers that react to them, and a clean shutdown.
Creating the application
A bot belongs to an application, which you create in Discord’s Developer Portal:
- Press New Application, give it a name (the bot’s, which you can change later) and accept the terms.
- Open the Bot page. Under Token, press Reset Token and copy the token it shows. It is shown only once: if you lose it, reset it again.
- On the same page, under Privileged Gateway Intents, turn on Message Content
Intent. The bot reads the text of messages to see
!ping, and Discord only sends that text to bots that ask for it (more on intents below).
Keep the token secret
The token is the bot’s password: whoever has it can log in as your bot and do anything
it may do. Never write it into your code, never commit it, never paste it into a chat.
This guide reads it from an environment variable, DISCORD_TOKEN. If a token leaks,
reset it on the Bot page at once: the old one stops working.
Adding the bot to your server
- Open the Installation page. Under Installation Contexts, keep Guild Install.
- Under Install Link, choose Discord Provided Link.
- Under Default Install Settings, give Guild Install the scopes
botandapplications.commands(the second one is for slash commands, two chapters on), and the permissions View Channels, Send Messages and Read Message History (a reply refers to the message it answers, which needs the history). - Copy the install link, open it in a browser, choose your test server and confirm.
The bot now shows in the server’s member list, offline: nothing runs it yet.
The code
Replace src/main.rs with this program:
use djs_rs::prelude::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Print the library's logs (connections, warnings, a handler's errors).
tracing_subscriber::fmt::init();
let token = std::env::var("DISCORD_TOKEN")?;
let client = Client::builder(token)
.intents(Intents::GUILDS | Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT)
.build();
client.on(Events::ClientReady, |_ctx, ready| async move {
println!("Logged in as {}", ready.user.tag());
Ok(())
});
client.on(Events::MessageCreate, |ctx, msg| async move {
if msg.content == "!ping" {
msg.reply(&ctx, "Pong!").await?;
}
Ok(())
});
// Ctrl+C disconnects the bot cleanly; `login` then returns.
let handle = client.clone();
tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_ok() {
handle.shutdown();
}
});
client.login().await?;
Ok(())
}
Run it with the token in the environment. In a Unix shell:
DISCORD_TOKEN='<your token>' cargo run
and in PowerShell:
$env:DISCORD_TOKEN = '<your token>'; cargo run
After a moment it prints the library’s log lines and Logged in as with the bot’s name,
and the bot shows as online. Send !ping in a channel of your server: it answers Pong!.
Press Ctrl+C to stop it.
The rest of this chapter goes through the program part by part.
The client
let token = std::env::var("DISCORD_TOKEN")?;
let client = Client::builder(token)
.intents(Intents::GUILDS | Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT)
.build();
A Client is the bot: it holds the token, the connections to Discord and the handlers.
Client::builder starts its configuration and build finishes it; the builder has more
settings (the cache, shards, the presence), which later chapters use.
The intents say which events the bot wants. Discord sends a bot only the events of the intents it asks for, which saves both sides the traffic of everything else:
GUILDS: the servers the bot is in, their channels and roles.GUILD_MESSAGES: messages sent in servers.MESSAGE_CONTENT: the text of those messages. It is a privileged intent, the one you turned on in the portal; without it,msg.contentis empty for messages that do not mention the bot.
Asking for a privileged intent the portal does not allow makes the login fail with an error that says so. The opposite mistake is quieter: listening to an event without its intent means it never comes, so djs-rs logs a warning at startup for every event you listen to without one of its intents.
(discord.js: new Client({ intents }).)
Handlers
client.on(Events::ClientReady, |_ctx, ready| async move {
println!("Logged in as {}", ready.user.tag());
Ok(())
});
Client::on registers a handler for an event, named by a constant of Events. The
handler is an async closure that receives two things: a Context (ctx), through which
it talks to Discord and reads the cache, and the event’s data, here the Ready payload,
which says who the bot is. ClientReady comes once the bot is connected and ready to
work.
client.on(Events::MessageCreate, |ctx, msg| async move {
if msg.content == "!ping" {
msg.reply(&ctx, "Pong!").await?;
}
Ok(())
});
MessageCreate comes for every message the bot can see, including its own. This handler
answers only !ping, with reply, which sends a message that refers to the one it
answers. Sending is a request to Discord’s API, so it is async and can fail: ? hands
the error back.
A handler returns Result<(), HandlerError>, and ? turns any error into a
HandlerError. An error does not stop the bot: djs-rs logs it (with the event’s name)
and goes on with the next events. Each event’s handlers run in their own tokio tasks, so a
slow handler never holds up the others.
(discord.js: client.on(Events.MessageCreate, …) and message.reply.)
Logging in, and out
client.login().await?;
Ok(())
Client::login connects to Discord’s gateway, identifies the bot with its token and
intents, and then runs: it receives the events and calls the handlers, reconnects when a
connection drops, and returns only when the bot is shut down (Ok) or cannot go on, for
example with a wrong token (Err).
// Ctrl+C disconnects the bot cleanly; `login` then returns.
let handle = client.clone();
tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_ok() {
handle.shutdown();
}
});
Client::shutdown asks a running client to disconnect; login then returns Ok(())
and main ends. A Client is a cheap handle (cloning it shares the same bot), so a task
can keep a clone to stop it from elsewhere. Here that task waits for Ctrl+C.
(discord.js: client.login(token) and client.destroy().)
Logs
// Print the library's logs (connections, warnings, a handler's errors).
tracing_subscriber::fmt::init();
djs-rs writes what it does to tracing: the connection,
reconnections, warnings and a handler’s errors. tracing_subscriber::fmt::init() prints
those lines to the terminal, at the info level and above by default. The RUST_LOG
variable chooses more or less, per crate: RUST_LOG=djs_gateway=debug cargo run shows
the gateway’s traffic in detail.
What’s next
The bot reacts to one event. The next chapter looks at
events and intents in general: which events there are, what each needs, and what the
Context gives a handler.
Events and intents
Almost everything a bot does starts with an event: a message was sent, a member joined, a button was pressed. This chapter shows which events there are, how a handler receives them, which intents bring them, and the two ways to consume them: handlers and a stream.
The listings come from two programs:
events.rs
and
in_order.rs.
The events
Discord’s gateway sends a bot dispatches, one per thing that happened, and djs-rs turns
each into an event of Events: Events::MessageCreate, Events::GuildMemberAdd,
Events::MessageReactionAdd, and so on, one for each of discord.js’s events, under the
same names. The event module lists them all, each with the intents it needs and its
discord.js name.
An event’s constant also fixes the type of what its handler receives. A handler of
Events::GuildMemberAdd gets the member and the guild’s ID:
client.on(Events::GuildMemberAdd, |_ctx, joined| async move {
println!(
"{} joined guild {}",
joined.member.user.tag(),
joined.guild_id
);
Ok(())
});
and one of Events::MessageReactionAdd gets the IDs of the user, the channel and the
message, and the emoji:
client.on(Events::MessageReactionAdd, |_ctx, reaction| async move {
let emoji = reaction.emoji.name().unwrap_or("an emoji");
println!(
"user {} reacted with {emoji} to message {}",
reaction.user_id, reaction.message_id
);
Ok(())
});
If you write a field that the payload does not have, the program does not compile: the compiler knows each event’s payload, and so does your editor’s completion.
Before and after
Some events are about something that changed or went away: a message edited or deleted, a
member’s roles changed, a channel renamed. For those, the handler gets both sides: old
is the thing as the cache held it just before the event, and the payload
itself (it dereferences to the new data) is what Discord sent.
client.on(Events::MessageUpdate, |_ctx, update| async move {
// `old` is the message as the cache held it before the edit, if it held it.
let before = update
.old
.as_ref()
.map_or("(not in the cache)", |old| old.content.as_str());
// The payload itself is the message after the edit.
println!("edited: {before:?} -> {:?}", update.content);
Ok(())
});
old is None when the cache did not hold it: when the bot runs without a cache (the
default), when that kind of object is not cached, or when it was never seen (a message sent
before the bot started). This program turns on a cache of the last 200 messages of each
channel when it builds the client (the cache has a chapter of its own):
let intents = Intents::GUILDS
| Intents::GUILD_MEMBERS
| Intents::GUILD_MESSAGES
| Intents::MESSAGE_CONTENT
| Intents::GUILD_MESSAGE_REACTIONS;
let client = Client::builder(token)
.intents(intents)
// Keep the last 200 messages of each channel, so an edit can show the text before.
.cache(CacheConfig::builder().messages(Limit::Max(200)).build())
.build();
From discord.js: discord.js drops events about objects it has not cached unless you enable partials. djs-rs has no partials: every event arrives, and what was not cached is
None(or an ID, where Discord sends only an ID), which you can complete with a request when you need it. Theeventmodule has the table of what each partial becomes.
Intents
When a bot connects, it tells Discord which groups of events it wants: its intents. Every event belongs to one or more of them, and Discord does not send the events of intents the bot did not ask for. Ask only for what the bot uses: every intent is traffic that Discord sends and the bot decodes.
The most used ones:
| Intent | Brings |
|---|---|
GUILDS | servers, channels, threads, roles; almost every bot needs it |
GUILD_MEMBERS | members joining, leaving and changing (privileged) |
GUILD_MODERATION | bans and the audit log |
GUILD_EXPRESSIONS | emojis, stickers and soundboard sounds |
GUILD_VOICE_STATES | who is in which voice channel (needed for voice) |
GUILD_PRESENCES | members’ statuses and activities (privileged) |
GUILD_MESSAGES | messages in servers |
GUILD_MESSAGE_REACTIONS | reactions in servers |
DIRECT_MESSAGES | messages in direct messages |
MESSAGE_CONTENT | the text, embeds, attachments and components of messages (privileged) |
Intents has every one, with its events. Intents combine with |.
Privileged intents
Three intents give access to data Discord considers sensitive: GUILD_MEMBERS,
GUILD_PRESENCES and MESSAGE_CONTENT. A bot can ask for them only after they are
turned on for it on the Bot page of the Developer Portal (Server Members Intent,
Presence Intent, Message Content Intent); once a bot is in 100 servers or more, Discord
also has to approve them. A bot that asks for a privileged intent it is not allowed is
refused at login, with an error that names the problem.
MESSAGE_CONTENT is unlike the others: it brings no events of its own, but without it the
messages of other users arrive with their text, embeds, attachments and components empty
(except in direct messages and messages that mention the bot).
Checking the intents
Listening to an event that no intent of the client brings is a quiet mistake: the handler
is never called. djs-rs warns about it in its log when the bot logs in, and
Client::required_intents tells which intents the registered handlers need, so a bot
can check itself:
// Does every event a handler listens to come with one of the client's intents?
let missing = client.required_intents().difference(intents);
if !missing.is_empty() {
eprintln!("some handlers' events need intents the client does not ask for: {missing:?}");
}
The context
Every handler receives a Context before the event’s data. It is how a handler acts:
ctx.rest()is the REST client, which sends requests to Discord’s API (replying to a message uses it). The methods on the structures, likemsg.reply(&ctx, …), take the context for this reason.ctx.cache()is the cache, orNonewhen the client has none.ctx.shard_id()is the shard the event came on, andctx.shard()sends that shard’s connection commands (a presence, a request for members).- The managers, such as
ctx.guilds(),ctx.members(guild)andctx.messages(channel), fetch and change Discord’s objects, with the cache in between when there is one.
client.on(Events::MessageCreate, |ctx, msg| async move {
if msg.content == "!cached" {
// The context reaches the cache, the REST client and the event's shard.
let cached = ctx
.cache()
.map_or(0, |cache| cache.messages(msg.channel_id).len());
let answer = format!(
"I remember {cached} messages of this channel (shard {}).",
ctx.shard_id()
);
msg.reply(&ctx, answer).await?;
}
Ok(())
});
A context is cheap to clone, and a clone can be moved into a task the handler spawns.
How handlers run
By default each call of a handler runs in its own tokio task. Events are handled concurrently: a handler that waits for a slow request holds up nothing else, and two events can be handled at the same time, in any order. That is what most bots want, and what discord.js does.
When the order matters more than throughput (a log that must show a message’s creation
before its deletion, say), HandlerMode::Sequential makes each shard call its handlers
one at a time, in the order of its events:
let client = Client::builder(token)
.intents(Intents::GUILDS | Intents::GUILD_MESSAGES)
// Each shard calls its handlers one at a time, in the order of its events.
.handler_mode(HandlerMode::Sequential)
.build();
client.on(Events::MessageCreate, |_ctx, msg| async move {
println!("created {}", msg.id);
Ok(())
});
client.on(Events::MessageDelete, |_ctx, deleted| async move {
// Never printed before the "created" line of the same message.
println!("deleted {}", deleted.id);
Ok(())
});
The price is that a slow handler delays every later event of its shard; if it takes long enough, it delays the shard’s heartbeats too and Discord drops the connection. In this mode, handlers should finish quickly and spawn tasks for slow work.
A stream of events
Handlers are the convenient way. For full control, Client::events gives a stream of
every event the client receives, as a Dispatch with the shard it came on:
let mut events = client.events();
tokio::spawn(async move {
let mut messages = 0_u64;
while let Some(event) = events.next().await {
if let Dispatch::MessageCreate(_) = event.event {
messages += 1;
if messages.is_multiple_of(100) {
println!(
"{messages} messages so far (the last on shard {})",
event.shard
);
}
}
}
});
Each call of events() creates its own stream, which receives every event from then on,
next to the handlers. A stream keeps the events its reader has not taken yet without a
limit: read it steadily, or drop it.
What’s next
Messages that start with ! are the old way of taking commands. The next
chapter turns to slash commands, which Discord shows to users with their options, checks their input, and
needs no MESSAGE_CONTENT at all.
Slash commands
A slash command is a command Discord itself knows about: when a user types /, Discord
lists the bot’s commands with their descriptions, asks for their options with the right
kind of input (a user picker, a number, a list of choices), checks the input, and sends the
bot an interaction with it. The bot needs no MESSAGE_CONTENT intent and parses nothing.
This chapter’s program is
commands.rs.
It needs the bot to be installed with the applications.commands scope, which the first
chapter’s install link includes.
Two steps: register, then answer
A command exists in two places, and a bot takes care of both:
- Registering tells Discord the command’s name, description and options. It is a request to Discord’s API, made once and kept by Discord: the commands stay registered while the bot is offline.
- Answering happens each time a user runs the command: Discord sends the interaction and the bot replies to it.
Defining commands
SlashCommandBuilder describes a command, and an option builder each of its options:
/// The bot's commands. `build` checks Discord's rules (names, lengths, the order of the
/// options) before anything is sent.
fn commands() -> Result<Vec<CreateApplicationCommand>, ValidationError> {
Ok(vec![
SlashCommandBuilder::new("ping", "Checks that the bot answers").build()?,
SlashCommandBuilder::new("echo", "Repeats a text")
.option(
SlashCommandStringOption::new("text", "What to repeat")
.required(true)
.max_length(200),
)
.option(
SlashCommandIntegerOption::new("times", "How many times")
.choice("Once", 1)
.choice("Twice", 2)
.choice("Three times", 3),
)
.option(SlashCommandBooleanOption::new(
"private",
"Only you see the answer",
))
.build()?,
SlashCommandBuilder::new("info", "Shows information")
.subcommand(
SlashCommandSubcommandBuilder::new("user", "About a user")
.option(SlashCommandUserOption::new("user", "Who (you by default)")),
)
.subcommand(SlashCommandSubcommandBuilder::new(
"server",
"About this server",
))
.build()?,
SlashCommandBuilder::new("fruit", "Picks a fruit")
.option(
SlashCommandStringOption::new("name", "Which one")
.required(true)
.autocomplete(true),
)
.build()?,
SlashCommandBuilder::new("slow", "Answers after a few seconds").build()?,
])
}
- A name is lowercase, without spaces, at most 32 characters; a description at most 100. Each option has the same two.
- Option kinds: strings, integers, numbers, booleans, users, roles, channels,
mentionables (a user or a role) and attachments, each with a builder (
SlashCommandStringOption, …) and the limits that make sense for it (max_length,min_value, …). - Required options come before the optional ones.
- Choices turn an option into a fixed list:
/echo timesoffers “Once”, “Twice” and “Three times”, and the bot receives 1, 2 or 3. - Subcommands split a command into several (
/info user,/info server); a command with subcommands cannot be run without one.
build checks all of Discord’s rules (lengths, characters, the order of the options, at
most 25 options or choices) and returns a ValidationError that says which one a
command breaks, before anything is sent.
(discord.js: SlashCommandBuilder and the same option builders.)
Registering them
Commands are registered in one of two scopes:
- Guild commands belong to one server and update instantly: the scope for developing and testing.
- Global commands are available in every server that has the bot (and, if you allow it, in direct messages): the scope for a released bot. A bot can have 100 global slash commands.
Registering needs the bot’s application ID, which the client knows once it is ready, so the
program registers in a ClientReady handler:
/// Registers the commands in the test server once the bot is ready (or removes them).
fn register(client: &Client, guild: Option<GuildId>, remove: bool) -> Result<(), ValidationError> {
let commands = Arc::new(commands()?);
client.on(Events::ClientReady, move |ctx, ready| {
let commands = Arc::clone(&commands);
async move {
let guild_id = match guild {
Some(guild_id) => guild_id,
None => ready.guilds.first().ok_or("the bot is in no server")?.id,
};
// `set` replaces all the bot's commands in that server with these.
let commands: &[CreateApplicationCommand] = if remove { &[] } else { &commands };
let registered = ctx.guild_commands(guild_id).set(commands).await?;
println!("{} command(s) in server {guild_id}", registered.len());
if remove {
ctx.shutdown();
}
Ok(())
}
});
Ok(())
}
ctx.guild_commands(guild).set(…) replaces all the bot’s commands in that server with the
given list; an empty list removes them (the program does that with -- --remove).
ctx.commands().set(…) does the same for the global commands. Commands left unchanged keep
their identity, and only new ones count toward Discord’s limit of 200 command creations per
server and day, so setting the same list at every start is fine.
Answering: the router
Interactions arrive as Events::InteractionCreate, whatever the intents. A handler of that
event could look at each interaction’s command name, but the client has a router for it:
Client::command sends the interactions of one command to one handler.
client.command("ping", |ctx, cmd| async move {
cmd.reply(&ctx, "Pong!").await?;
Ok(())
});
The handler receives a CommandInteraction (cmd), with the command’s data and the ways
to answer it; cmd.reply sends the answer. Anything that converts into a message’s data
can be the reply: a &str, a String, or a MessageCallbackData with more in it.
Every interaction must be answered within 3 seconds, or Discord shows the user that the bot did not respond. A reply is the usual answer; a deferred one (below) buys time.
(discord.js: interaction.reply; a switch on interaction.commandName instead of the
router.)
Options
The interaction carries the options the user gave, read by name with a getter for their
kind: get_string, get_integer, get_number, get_boolean, get_user, get_channel,
get_role, get_attachment… Each returns an Option, None when the user left an
optional option out (a required option is always there).
client.command("echo", |ctx, cmd| async move {
// Required options are always there; the others may be missing.
let text = cmd.get_string("text").unwrap_or_default();
let times = usize::try_from(cmd.get_integer("times").unwrap_or(1))?;
// The text is the user's: never let it ping `@everyone`, roles or users.
let mut reply = MessageCallbackData::from(vec![text; times].join("\n")).no_mentions();
if cmd.get_boolean("private").unwrap_or(false) {
reply = reply.ephemeral();
}
cmd.reply(&ctx, reply).await?;
Ok(())
});
Two things in this reply:
ephemeralmakes the answer visible only to the user who ran the command, with a note that only they see it. Use it for errors, settings and anything private.no_mentionskeeps the text from pinging anyone./echorepeats what a user wrote, so without it anyone could make the bot ping@everyone. Whenever a reply contains text a user chose, turn mentions off.
(discord.js: interaction.options.getString and the other getters, ephemeral as a
message flag, allowedMentions.)
Subcommands
A route’s name is the command as Discord shows it, with single spaces, so each subcommand can have a route of its own:
client.command("info user", |ctx, cmd| async move {
let user = cmd
.get_user("user")
.or_else(|| cmd.interaction().author())
.ok_or("an interaction without a user")?;
let answer = format!("{} (ID {}), a bot: {}", user.tag(), user.id, user.bot);
cmd.reply(&ctx, answer).await?;
Ok(())
});
client.command("info server", |ctx, cmd| async move {
let Some(guild_id) = cmd.interaction().guild_id else {
let reply = MessageCallbackData::from("This only works in a server.").ephemeral();
cmd.reply(&ctx, reply).await?;
return Ok(());
};
let guild = ctx.guilds().fetch(guild_id).await?;
cmd.reply(&ctx, format!("{} (ID {})", guild.name, guild.id))
.await?;
Ok(())
});
cmd.interaction() is the whole interaction: who ran the command (author), where
(guild_id, channel_id), and more. /info user falls back to the user who ran it when
the option is left out; /info server fetches the server through the guild manager.
A route for "info" alone would receive the subcommands that have no route of their own.
Taking longer: deferred replies
When an answer takes more than 3 seconds to prepare (a slow API, a computation), answer first with a deferred reply: Discord shows “Bot is thinking…” and the interaction stays open for 15 minutes.
// Discord waits 3 seconds for the first answer; `defer_reply` gives 15 minutes.
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: this replaces the \"thinking…\" message.")
.await?;
cmd.follow_up(&ctx, "And this is one more message.").await?;
Ok(())
});
edit_reply replaces the “thinking” message with the real answer (it also edits a normal
reply), and follow_up sends more messages after it, for as long as the interaction is
open. Pass MessageFlags::EPHEMERAL to defer_reply to make the answer ephemeral.
(discord.js: deferReply, editReply, followUp.)
Autocomplete
Choices are fixed when the command is registered, and limited to 25. For a longer or changing list, an option can ask for autocomplete: while the user types, Discord sends the bot what was typed so far, and the bot answers with up to 25 suggestions.
// Discord asks while the user types; the answer must come within 3 seconds.
client.autocomplete("fruit", |ctx, search| async move {
let typed = search.focused_value().unwrap_or_default().to_lowercase();
let choices = FRUITS
.iter()
.filter(|fruit| fruit.contains(typed.as_str()))
.take(25)
.map(|&fruit| Choice::new(fruit, fruit.into()))
.collect();
search
.respond(&ctx, AutocompleteChoices::String(choices))
.await?;
Ok(())
});
client.command("fruit", |ctx, cmd| async move {
// A suggestion's value, or whatever the user typed instead.
let name = cmd.get_string("name").unwrap_or_default();
let reply = if FRUITS.contains(&name) {
MessageCallbackData::from(format!("You picked {name}."))
} else {
MessageCallbackData::from(format!("I know no fruit called {name:?}.")).ephemeral()
};
cmd.reply(&ctx, reply).await?;
Ok(())
});
Client::autocomplete routes those requests like command routes commands. The answer
must come within 3 seconds, and cannot be deferred. The suggestions only help: the user
can still send anything, so the command’s handler checks the value it receives.
(discord.js: interaction.respond in an isAutocomplete() branch.)
Putting it together
// Interactions come whatever the intents are; `GUILDS` gives the bot its servers.
let client = Client::builder(token).intents(Intents::GUILDS).build();
register(&client, guild, remove)?;
if !remove {
routes(&client);
}
Run the program, type / in your server and the five commands appear with their options.
What’s next
Replies so far are text. The next chapter makes them richer: embeds, buttons and select menus, and the modals that ask a user to fill in a form.
Components and embeds
Text is only part of what a message can carry. An embed is a framed card with a title,
a colour, fields and images; components are what users can click or pick in a message
(buttons and select menus) and the fields of a modal, the form a bot can open over the
chat. This chapter builds a /card command whose reply has all of them.
This chapter’s program is
buttons_and_embeds.rs.
It registers its command like the previous chapter’s program does.
The card
EmbedBuilder makes the embed; ActionRowBuilder holds a row of components: up to
five buttons, or one select menu.
/// The card `/card` shows: an embed, a row of buttons and a row with a select menu. The
/// like button carries its count in its custom ID (`like:3`), so the bot keeps no state.
fn card(likes: u32) -> Result<(Embed, Vec<Component>), ValidationError> {
let embed = EmbedBuilder::new()
.title("djs-rs")
.url("https://github.com/kotoanidev/djs-rs")
.description("Discord bots in Rust, the discord.js way.")
.color(0x00_5f_87)
.inline_field("Likes", likes.to_string())
.inline_field("Language", "Rust")
.footer("Click a button or pick a flavor")
.timestamp_now()
.build()?;
let buttons = ActionRowBuilder::new()
.component(ButtonBuilder::primary(format!("like:{likes}")).label("Like"))
.component(ButtonBuilder::secondary("form").label("Tell us more"))
.component(ButtonBuilder::link("https://kotoanidev.github.io/djs-rs/").label("Guide"))
.build()?;
let menu = ActionRowBuilder::new()
.component(
StringSelectMenuBuilder::new("flavor")
.placeholder("Your favourite flavor")
.option("Vanilla", "vanilla")
.option("Chocolate", "chocolate")
.option("Strawberry", "strawberry"),
)
.build()?;
Ok((embed, vec![buttons, menu]))
}
- Embeds have a title (which
urlturns into a link), a description, a colour, up to 25 fields (inline_fieldputs them side by side), a footer, an author, an image, a thumbnail and a timestamp, which each user sees in their own time zone. A message can have up to 10 embeds, with 6 000 characters in all. - Buttons come in styles:
primary(the accent colour),secondary(grey),success(green),danger(red), each with a custom ID the bot receives when it is clicked, andlink, which opens a URL and sends the bot nothing. - Select menus offer a list (
StringSelectMenuBuilder, up to 25 options) or Discord’s own pickers of users, roles, mentionables and channels (UserSelectMenuBuilder, …).min_valuesandmax_valuesallow picking several.
build checks Discord’s limits for what it builds (lengths, counts, a label or an emoji on
each button) and says which one is broken, before anything is sent; validate_components
checks a message’s rows together, custom IDs unique across them included.
(discord.js: EmbedBuilder, ActionRowBuilder, ButtonBuilder, StringSelectMenuBuilder.)
Sending it
Embeds and components go into the reply’s data:
client.command("card", |ctx, cmd| async move {
let (embed, components) = card(0)?;
let reply = MessageCallbackData::default()
.embeds([embed])
.components(components);
cmd.reply(&ctx, reply).await?;
Ok(())
});
The same embeds and components exist on a message sent to a channel (CreateMessage)
and on an edit (EditMessage).
Answering clicks
A click is an interaction, like a slash command, and must be answered within 3 seconds.
Client::component routes clicks by custom ID: the route "like" receives the custom ID
like, and every custom ID that starts with like:. What follows the : is the
handler’s args, so a button can carry what its handler needs:
// `like:3` reaches the route `like` with the arguments `3`.
client.component("like", |ctx, button| async move {
let likes: u32 = button.args().parse()?;
let (embed, components) = card(likes + 1)?;
// `update` edits the message the button is on, and answers the click.
let update = MessageCallbackData::default()
.embeds([embed])
.components(components);
button.update(&ctx, update).await?;
Ok(())
});
The like button carries its count (like:3), and the handler sends the card again with the
count one higher. update replaces the message the button is on and answers the click in
one step; reply would send a new message instead, and defer_update answers without a
change, for a handler that edits the message later.
Keeping the state in the custom ID means nothing is lost when the bot restarts: the buttons of a week-old message still work. A custom ID holds up to 100 characters; for more, keep a key in it and the data in a database.
(discord.js: client.on("interactionCreate") with interaction.isButton() and a check of
customId; interaction.update.)
Waiting for a click where it happens
When a click only matters right after a message is sent, a handler can wait for it with a
collector instead of a route: message.await_component(&ctx).time(…) returns the next
click on that message, and message.component_collector(&ctx) all of them until it ends.
The repository’s
components.rs
turns pages with one. A route survives a restart; a collector lives as long as its handler.
Select menus
A select menu sends its custom ID with the picked values:
client.component("flavor", |ctx, menu| async move {
let picked = menu
.values
.first()
.map_or("nothing", |value| value.as_str());
let reply = MessageCallbackData::from(format!("You picked {picked}.")).ephemeral();
menu.reply(&ctx, reply).await?;
Ok(())
});
The values are the options’ values ("vanilla"), not their labels. Discord’s user, role
and channel menus send IDs, with the users, roles or channels themselves in the
interaction’s resolved data.
Modals
A modal is a form with up to five fields. It can only be the first answer to an
interaction (a command or a click), and its submission arrives as an interaction of its
own, routed by the modal’s custom ID with Client::modal:
client.component("form", |ctx, button| async move {
let form = ModalBuilder::new("about", "About you")
.label("Your name", TextInputBuilder::short("name").max_length(80))
.label(
"What are you building?",
TextInputBuilder::paragraph("project")
.max_length(1000)
.required(false),
)
.build()?;
// A modal must be the first answer to the click.
button.show_modal(&ctx, form).await?;
Ok(())
});
client.modal("about", |ctx, modal| async move {
let name = modal.text_value("name").unwrap_or_default();
let project = modal.text_value("project").unwrap_or_default();
let answer = if project.is_empty() {
format!("Nice to meet you, {name}!")
} else {
format!("Nice to meet you, {name}! Good luck with {project}.")
};
// The text is the user's: no pings.
let reply = MessageCallbackData::from(answer).no_mentions().ephemeral();
modal.reply(&ctx, reply).await?;
Ok(())
});
Each field has a label and an input: TextInputBuilder::short for one line,
::paragraph for several, with lengths and a placeholder; fields are required unless set
otherwise. text_value reads a field by its custom ID. A user can close a modal without
sending it, and then nothing arrives; a slash command that opens a modal and waits for it
in place (cmd.await_modal_submit) needs a time limit for that reason.
(discord.js: ModalBuilder, TextInputBuilder, interaction.showModal,
ModalSubmitInteraction#fields.)
What’s next
The bot has been asking Discord for what it needs. The next chapter shows what the client keeps on its own: the cache.
The cache
Discord tells a bot about everything that changes in its servers, through gateway events. A cache keeps what those events said: the servers, their channels, roles and members, recent messages. A bot that reads the cache answers without asking Discord’s API, which is faster and spends none of its rate limits.
This chapter’s program is
cache_tour.rs.
It needs the Server Members and Message Content intents, enabled in the Developer
Portal (Bot → Privileged Gateway Intents).
Choosing what to keep
A client has no cache until it is given one, and a cache keeps only what its
CacheConfig lists:
// The default cache keeps guilds, channels and roles; add what the bot reads.
let cache = CacheConfig::builder()
.members(Limit::Unlimited)
.users(Limit::Unlimited)
// The latest 100 messages of each channel.
.messages(Limit::Max(100))
// Every 10 minutes, forget messages older than an hour.
.sweep_messages(Some(Sweep::new(
Duration::from_secs(10 * 60),
Duration::from_secs(60 * 60),
)))
.build();
// What the cache can fill depends on the intents: members need GUILD_MEMBERS.
let client = Client::builder(token)
.intents(
Intents::GUILDS
| Intents::GUILD_MEMBERS
| Intents::GUILD_MESSAGES
| Intents::MESSAGE_CONTENT,
)
.cache(cache)
.build();
CacheConfig::default()keeps guilds, channels and roles, which most bots read and which cost little.- Each resource (members, users, messages, presences, voice states, threads, emojis,
stickers, scheduled events, stage instances, soundboard sounds) has a
Limit:Disabled,Max(n)orUnlimited. A limit counts where it makes sense: messages per channel, members and roles per server, guilds and users over the whole cache. When a scope is full, its oldest entry makes room. CacheConfig::discord_js()keeps what discord.js keeps by default: everything, with the latest 200 messages of each channel. It is the most memory a bot can spend.- Intents decide what can arrive: members need
GUILD_MEMBERS, presencesGUILD_PRESENCES, messagesGUILD_MESSAGES. A resource cached without its intent stays empty.
The repository’s comparison with discord.js measures what each choice costs per server and member.
(discord.js: the makeCache option with Options.cacheWithLimits; discord.js always has a
cache.)
Reading it
ctx.cache() is the client’s cache (None without one). Each resource is read through a
view: cache.guilds(), cache.members(guild_id), cache.messages(channel_id), … with
get, contains, len, keys and values.
client.on(Events::MessageCreate, |ctx, msg| async move {
let (Some(guild_id), "!cache") = (msg.guild_id, msg.content.trim()) else {
return Ok(());
};
let cache = ctx.cache().ok_or("the client has a cache")?;
let guild = cache.guilds().get(guild_id).ok_or("a guild of the bot")?;
let answer = format!(
"{}: {} members on Discord, {} in the cache; {} users; {} messages of this channel",
guild.name,
guild.member_count,
cache.members(guild_id).len(),
cache.users().len(),
cache.messages(msg.channel_id).len(),
);
msg.reply(&ctx, answer).await?;
Ok(())
});
What a view returns is an Arc: a shared handle, cheap to clone, which holds no lock, so a
handler can keep it across .await while the cache goes on changing. It is the state at the
time it was read.
Every event goes into the cache before its handlers run, so a handler sees the state
after its event: in a GuildMemberAdd handler the new member is already cached.
(discord.js: client.guilds.cache, guild.members.cache, channel.messages.cache.)
The state before an event
An update or a deletion replaces or removes what the cache held, so the client hands it to
the event’s handlers first. The payloads of those events have an old field:
// `old` is what the cache held before the event; `None` if it did not hold it.
client.on(Events::MessageUpdate, |_ctx, update| async move {
if let Some(old) = &update.old {
println!("edited: {:?} -> {:?}", old.content, update.content);
}
Ok(())
});
client.on(Events::MessageDelete, |_ctx, deleted| async move {
match &deleted.old {
Some(old) => println!("deleted: {:?} by {}", old.content, old.author.tag()),
None => println!("deleted message {}, never cached", deleted.id),
}
Ok(())
});
old is None when the cache did not hold the object: without a cache, with that
resource disabled, or for a message older than the cache’s limit. The event still
arrives, with what Discord sent (for a deleted message, only its ID and channel).
(discord.js: oldMessage, oldMember and the other first arguments; discord.js drops
such events about uncached objects unless partials are enabled, djs-rs always sends
them.)
Fetching through the cache
The managers (ctx.members(guild), ctx.channels(), ctx.messages(channel), …) read the
cache first and ask Discord only for what is missing, caching the answer:
client.on(Events::GuildMemberAdd, |ctx, member| async move {
let members = ctx.members(member.guild_id);
// The member was cached from this very event: no request.
let cached = members.fetch(member.user.id);
println!("cached: {}", cached.is_cached());
// `force` asks Discord anyway, and caches the answer.
let fresh = members.fetch(member.user.id).force().await?;
println!("{} joined", fresh.display_name());
Ok(())
});
fetch returns a value that can be checked before it is awaited: is_cached says whether
it will be answered from the cache. force skips the cache, for when the cached state
might be stale (an event the bot missed while offline, say).
(discord.js: guild.members.fetch(id) and its force option.)
Sweeping
Limits bound how much the cache holds; sweeps forget what has grown old. A sweep set in
the configuration (sweep_messages, sweep_threads) runs periodically while the client is
logged in; by default, like discord.js, threads archived for more than 4 hours are swept
every hour. Each resource can also be swept by hand, with a filter:
client.on(Events::ClientReady, |ctx, _ready| async move {
let cache = ctx.cache().ok_or("the client has a cache")?;
// A sweep of its own: forget the bots among the users.
let removed = cache.sweep_users(|user| user.bot);
println!("{removed} bot user(s) swept");
Ok(())
});
(discord.js: the sweepers option and client.sweepers.)
What’s next
The managers have been calling Discord’s API through the cache. The next chapter calls the API directly: the REST client and its rate limits.
The REST API
Everything a bot does (sending a message, banning a member, registering a command) is a
request to Discord’s REST API. The managers and the structures’ methods of the earlier
chapters make those requests through the client’s Rest client; this chapter uses it
directly, for the endpoints the managers do not wrap and for programs without a gateway
connection at all.
This chapter’s program is
rest_calls.rs.
It never connects to the gateway: it needs a token and the ID of a channel the bot can
write in (enable Developer Mode in Discord’s settings, then right-click the channel → Copy
Channel ID).
A client
In a bot, ctx.rest() is the client’s REST client. On its own, it is built from a token:
// A client of its own; in a bot, `ctx.rest()` is the client's one.
let rest = Rest::builder()
.token(token)
// Each attempt gets 10 seconds, and a failed one is tried twice more.
.timeout(Duration::from_secs(10))
.retries(2)
.build();
The client is cheap to clone, and clones share the connection and the rate limits: keep
one and clone it into tasks. The djs-rest crate can be used alone, for a command-line
tool, a web dashboard or an HTTP-only interactions bot.
(discord.js: new REST().setToken(token) from @discordjs/rest; client.rest.)
One method per endpoint
Every endpoint of the API is a method, named after Discord’s documentation: Create
Message is create_message, Get Guild Member get_guild_member, and so on. Each takes
the IDs in the path, then the request’s body or query as a type of djs_rs::model::rest,
and returns the decoded response:
let sent = rest
.create_message(channel, &CreateMessage::from("Hello from djs-rest!"))
.await?;
let edit = EditMessage::default().content("Hello again, edited.");
let edited = rest.edit_message(channel, sent.id, &edit).await?;
println!(
"sent and edited message {}: {:?}",
edited.id, edited.content
);
Bodies are plain structs with builder-style setters (content, embeds, components,
…) and Default; a &str turns into a message body. Fields that an edit can leave alone,
set or clear are a Patch (Keep, Set(…), Clear), so an edit sends only what it
changes. Requests that show up in the server’s audit log take a reason.
Lists, page by page
Endpoints that list return one page. Messages come newest first, up to 100 per request,
and the query’s before asks for the page before a given message:
// Up to 100 messages per request; `before` asks for the page before the last one seen.
let mut query = GetChannelMessages::default();
query.limit = Some(100);
let mut seen = 0;
let mut oldest: Option<MessageId> = None;
for _ in 0..3 {
query.before = oldest;
let page = rest.get_channel_messages(channel, &query).await?;
seen += page.len();
// Newest first: the page's last message is its oldest.
match page.last() {
Some(message) if page.len() == 100 => oldest = Some(message.id),
_ => break,
}
}
println!("{seen} message(s) in the channel's latest pages");
Members are listed oldest first with after, bans and reactions the same way; the query
types document their limits.
Rate limits
Discord limits how many requests a bot may make: per route (a bucket, shared for example by all messages sent to one channel), globally (50 requests per second), and against too many failed requests (10 000 invalid ones in 10 minutes ban the IP for a while). The client keeps to all of them by itself:
- requests to one bucket wait in a queue until Discord’s headers allow the next one;
- a
429 Too Many Requestspauses the bucket, or every request for a global limit, and the request is sent again; - server errors, timeouts and connection failures are retried (
retries, 3 by default); - invalid requests (401, 403, 429) are counted (
rest.invalid_requests()), and withinvalid_request_limit(9_000)the client stops sending before the ban; there is no such limit by default.
A bot does nothing for any of this. Hitting a limit is logged through tracing at the
warn level, which is worth watching: it usually means a loop sends more than it should.
(discord.js: the same model, in @discordjs/rest.)
Errors
A failed request returns a djs_rest::Error: the request could not be sent, it timed
out, the response could not be decoded, or Discord answered with an error status. In the
last case status() is the HTTP status and api_error() the error Discord sent, with its
JSON error code:
rest.delete_message(channel, sent.id).await?;
// Deleting it again fails: Discord answers 404 with its error code 10008.
match rest.delete_message(channel, sent.id).await {
Ok(()) => println!("deleted twice?"),
Err(error)
if error
.api_error()
.is_some_and(|api| api.code == ErrorCode::UnknownMessage) =>
{
println!(
"already gone ({})",
error.status().map_or(0, |status| status.as_u16())
);
}
Err(error) => return Err(error.into()),
}
ErrorCode names Discord’s codes (UnknownMessage, MissingPermissions,
MissingAccess, …): match on them rather than on texts, which Discord may change. In a
handler, ? passes the error on, and the client logs it with the event’s name.
(discord.js: DiscordAPIError with code and status, and RESTJSONErrorCodes.)
What’s next
One connection to the gateway serves up to 2 500 servers. The next chapter splits a bigger bot into shards.
Sharding
A gateway connection is a shard, and Discord sends each shard the events of a share of the bot’s servers. A bot in fewer than 2 500 servers may use one shard; above that Discord requires more, about one per 1 000 servers. djs-rs shards by itself: the question is only where the shards run.
This chapter’s program is
sharded.rs.
It needs the sharding feature of djs-rs:
djs-rs = { version = "0.1.0-alpha.2", features = ["sharding"] }
In one process
A client asks Discord how many shards the bot should have and runs them all, in its one
process: Shards::Auto, the default. Nothing in a bot changes with the shard count. The
events of every shard reach the same handlers, ctx.shard_id() tells which shard an event
came from, and the client keeps Discord’s limit on how fast shards may connect. One
process holds a lot of shards: the repository’s benchmarks run a thousand in one.
Shards::Count(n) fixes the number, and Shards::Range { range, total } runs only some of
them, for a bot split over machines by hand.
(discord.js: the shards: "auto" client option, which is not the default there.)
In several processes
A bot that outgrows one process (its memory, a restart of everything at once) runs its
shards in several. A ClusterManager starts them: one program that, run, either is
the manager or is one of the processes it started, a cluster:
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::fmt::init();
let token = std::env::var("DISCORD_TOKEN")?;
// The manager starts this same program again for each cluster; `process` tells them
// apart from the first one.
if let Some(assignment) = sharding::process()? {
cluster(token, assignment).await?;
return Ok(());
}
// The first process: the manager.
let manager = ClusterManager::builder(token)
.shards(Shards::Count(2))
.shards_per_process(1)
.build();
let stopping = manager.clone();
tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_ok() {
stopping.shutdown();
}
});
// Returns once every process has exited.
manager.spawn().await?;
Ok(())
}
sharding::process() returns the process’s ClusterAssignment (its shards) when the
manager started it, and None in the first process, which becomes the manager. The
manager asks Discord for the shard count once, starts the processes one after another
(shards_per_process shards each), passes their connections through one queue so they
never connect too fast, and restarts a process that fails.
(discord.js: ShardingManager, which runs a separate script.)
A cluster
Each cluster is an ordinary client, given its assignment:
/// The bot itself, in each process the manager starts.
async fn cluster(token: String, assignment: ClusterAssignment) -> Result<(), djs_rs::Error> {
let client = Client::builder(token)
.intents(Intents::GUILDS | Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT)
.cluster(assignment)
.build();
let cluster = client.cluster().expect("a client built with `cluster`");
// This process's answer to `ShardIds`.
cluster.handle::<ShardIds, _, _>(|client, ()| async move {
let cluster = client.cluster().expect("a cluster");
Ok(cluster.shards().collect())
});
client.on(Events::MessageCreate, move |ctx, msg| {
let cluster = cluster.clone();
async move {
if msg.content.trim() != "!servers" {
return Ok(());
}
// Every cluster answers, this one included; one that is down fails alone.
let stats = cluster.stats().await?;
let guilds: u64 = stats
.iter()
.filter_map(|reply| reply.result.as_ref().ok()?.guilds)
.sum();
let shards = cluster.broadcast::<ShardIds>(()).await?;
let answering = shards.iter().filter(|reply| reply.result.is_ok()).count();
let answer = format!(
"{guilds} servers over {} shards in {answering} processes; this is shard {}.",
cluster.total_shards(),
ctx.shard_id(),
);
msg.reply(&ctx, answer).await?;
Ok(())
}
});
client.login().await
}
Its cache holds only its own shards’ servers, so a question about all of them goes to
every cluster. cluster.stats() asks each one for its servers, users, shards and memory.
For anything else, a bot declares a command:
/// A command each cluster answers: the IDs of its shards. The name must be the same in
/// every process, which it is: they all run this program.
struct ShardIds;
impl ClusterCommand for ShardIds {
const NAME: &'static str = "shard-ids";
type Input = ();
type Output = Vec<u32>;
}
A command has a name and the types of its input and output, which travel between the
processes as JSON. handle answers it in each cluster, and broadcast sends it to every
cluster (send to one) and returns each one’s answer, or why it gave none: a cluster that
is restarting fails alone instead of spoiling the others.
(discord.js: broadcastEval and fetchClientValues. Rust cannot run code sent to it at run
time, so the code a command runs is compiled into the bot.)
Limits worth knowing
- Discord limits how many sessions a bot may start per day (1 000 for most bots); every shard’s connection is one. The manager checks that enough are left before it starts.
- Each process has its own REST client, and Discord’s rate limits are per bot: processes that send a lot at once see 429 answers, which the client waits out.
- The processes talk to the manager over
127.0.0.1, with a secret token only the processes it started know.
What’s next
The next chapter joins voice channels.
Voice
A bot can join voice channels, play audio into them and hear what is said there. Voice
lives in the djs-voice crate, which the voice feature plugs into the client:
djs-rs = { version = "0.1.0-alpha.2", features = ["voice"] }
It builds libopus from source and links it in, so building needs CMake and a C compiler. Playing anything but Ogg/Opus and raw PCM needs FFmpeg installed.
This chapter’s program is
voice_call.rs:
a small music bot playing the files of a music/ directory.
The client
// GUILD_VOICE_STATES: the bot learns its own voice state (joining needs it) and, cached,
// where everyone else is.
let client = Client::builder(token)
.intents(
Intents::GUILDS
| Intents::GUILD_VOICE_STATES
| Intents::GUILD_MESSAGES
| Intents::MESSAGE_CONTENT,
)
.cache(
CacheConfig::builder()
.voice_states(Limit::Unlimited)
.build(),
)
.build();
let voice = client.voice().clone();
client.voice() is the client’s VoiceManager: one per bot, with one Call per
server. The manager sends the gateway’s voice requests through the right shard and
follows the voice events by itself; a bot only joins and plays. The client needs the
GUILD_VOICE_STATES intent, without which a join never completes; the cache of voice
states tells the program which channel a user is in.
(discord.js: @discordjs/voice with joinVoiceChannel and guild.voiceAdapterCreator.)
Joining
/// `!join`: the author's voice channel, from the cache's voice states.
async fn join(
ctx: &Context,
voice: &VoiceManager,
msg: &djs_rs::model::message::Message,
guild_id: GuildId,
) -> Result<(), HandlerError> {
let channel_id = ctx
.cache()
.and_then(|cache| cache.voice_states(guild_id).get(msg.author.id))
.and_then(|state| state.channel_id)
.ok_or("join a voice channel first")?;
// Not deafened, to hear who speaks.
let options = JoinOptions::new().self_deaf(false);
let call = voice.join_with(guild_id, channel_id, options).await?;
let mut events = call.events();
tokio::spawn(async move {
while let Some(event) = events.next().await {
match event {
CallEvent::SpeakingStarted(user) => println!("{user} speaks"),
CallEvent::Disconnected(reason) => {
println!("left the call: {reason}");
break;
}
_ => {}
}
}
});
msg.reply(ctx, "Joined.").await?;
Ok(())
}
join returns once the bot is connected and its call is encrypted. Every call is
encrypted end to end with Discord’s DAVE protocol, which Discord requires of every client
since March 2026; djs-voice does it with no setting. A bot joins deafened unless
JoinOptions says otherwise: Discord sends a deafened bot nobody’s audio.
call.events() reports what happens in the call: users joining and leaving, who starts and
stops speaking, and the disconnection, with its reason.
Playing
/// `!play <file>`: a file of `music/`, queued after the others. Only plain file names: the
/// name comes from a user, and FFmpeg would open any path or URL it is given.
fn play(call: &Call, name: &str) -> Result<String, HandlerError> {
let name = name.trim();
if name.is_empty() || name.starts_with('.') || name.contains(['/', '\\']) {
return Err("give the name of a file in music/".into());
}
let path = Path::new("music").join(name);
if !path.is_file() {
return Err(format!("music/{name} does not exist").into());
}
call.enqueue(Input::ffmpeg(&path));
Ok(format!(
"Queued {name} ({} in the queue).",
call.queue().len()
))
}
An Input is what a track plays:
Input::ogg_fileandInput::oggread Ogg/Opus, Discord’s own format, and send it as it is: no decoding, no encoding, a fraction of a CPU core for hundreds of calls.Input::pcmreads raw 48 kHz stereo samples, encoded on the way.Input::ffmpegreads anything FFmpeg reads (MP3, FLAC, WAV, a URL…).
call.play plays a track now, call.enqueue after the others. Both return a
TrackHandle: pause, play, stop, set_volume, seek, set_loop, its state
(info) and its events (events).
Whatever FFmpeg is given, it opens: a path, a URL, a device. The program therefore takes
only plain file names of its music/ directory from users. A bot that plays links should
check them the same way (an allowed host, https:// only).
(discord.js: createAudioPlayer, createAudioResource, player.play; djs-voice has a
queue of its own.)
The commands
client.on(Events::MessageCreate, move |ctx, msg| {
let voice = voice.clone();
async move {
let Some(guild_id) = msg.guild_id else {
return Ok(());
};
let text = msg.content.trim();
let (command, argument) = text.split_once(' ').unwrap_or((text, ""));
if command == "!join" {
return join(&ctx, &voice, &msg, guild_id).await;
}
// Every other command needs the bot in a call in this server.
let Some(call) = voice.get(guild_id) else {
return Ok(());
};
let answer = match command {
"!play" => play(&call, argument)?,
"!volume" => {
let volume: f32 = argument.trim().parse()?;
let track = call.queue().current().ok_or("nothing is playing")?;
// 1.0 is the file's own volume.
track.set_volume(volume.clamp(0.0, 2.0))?;
format!("Volume {volume}.")
}
"!skip" => {
call.queue().skip();
"Skipped.".to_owned()
}
"!leave" => {
call.leave().await?;
"Bye.".to_owned()
}
_ => return Ok(()),
};
msg.reply(&ctx, answer).await?;
Ok(())
}
});
voice.get(guild) is the server’s call, if the bot is in one. call.queue() is its queue:
current is the track playing, skip goes to the next one, clear empties it. leave
ends the call.
Hearing
call.subscribe(user) returns a stream of that user’s audio: their packets in order,
lost ones reported, as Opus or (ReceiveOptions::decode) as 48 kHz stereo samples, and
EndBehavior ends it after a silence. Only the users a call is subscribed to are
decrypted and decoded, so listening to one speaker in a crowded channel costs one
speaker. The djs-voice
README
records a user until they stop speaking.
(discord.js: connection.receiver.subscribe.)
What’s next
The last chapter answers interactions over HTTP, without the gateway.
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.
Coming from discord.js
djs-rs follows discord.js v14’s concepts and names, so most of what a discord.js developer
knows carries over: a Client with intents, events by name, managers with a cache and
fetch, builders for embeds, components and commands. This page maps one to the other and
lists what differs, and why.
The same bot
In discord.js:
const { Client, Events, GatewayIntentBits } = require("discord.js");
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent],
});
client.once(Events.ClientReady, (ready) => console.log(`Logged in as ${ready.user.tag}`));
client.on(Events.MessageCreate, async (message) => {
if (message.content === "!ping") await message.reply("Pong!");
});
client.login(process.env.DISCORD_TOKEN);
In djs-rs (the first chapter’s program):
use djs_rs::prelude::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Print the library's logs (connections, warnings, a handler's errors).
tracing_subscriber::fmt::init();
let token = std::env::var("DISCORD_TOKEN")?;
let client = Client::builder(token)
.intents(Intents::GUILDS | Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT)
.build();
client.on(Events::ClientReady, |_ctx, ready| async move {
println!("Logged in as {}", ready.user.tag());
Ok(())
});
client.on(Events::MessageCreate, |ctx, msg| async move {
if msg.content == "!ping" {
msg.reply(&ctx, "Pong!").await?;
}
Ok(())
});
// Ctrl+C disconnects the bot cleanly; `login` then returns.
let handle = client.clone();
tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_ok() {
handle.shutdown();
}
});
client.login().await?;
Ok(())
}
The shape is the same. What Rust adds: handlers are async closures returning a Result
(an Err is logged with the event’s name), they receive a Context (ctx) through which
they reach the REST client, the cache and the managers, and msg.reply needs it.
Names
| discord.js | djs-rs |
|---|---|
new Client({ intents }) | Client::builder(token).intents(…).build() |
GatewayIntentBits.GuildMessages | Intents::GUILD_MESSAGES |
client.on(Events.MessageCreate, fn) | client.on(Events::MessageCreate, fn) |
client.login(token) | client.login().await (the token is given to the builder) |
client.destroy() | client.shutdown() |
client.guilds.cache.get(id) | ctx.cache()?.guilds().get(id) |
client.guilds.fetch(id) | ctx.guilds().fetch(id).await |
guild.members.fetch(id) | ctx.members(guild_id).fetch(id).await, or guild.members(&ctx) |
channel.send("hi") | channel.send(&ctx, "hi").await |
message.reply, .edit, .delete, .react | the same, with &ctx |
interaction.reply, deferReply, editReply, followUp, showModal | reply, defer_reply, edit_reply, follow_up, show_modal |
EmbedBuilder, ButtonBuilder, ActionRowBuilder, SlashCommandBuilder | the same names, in djs_rs::builders |
PermissionFlagsBits.BanMembers | Permissions::BAN_MEMBERS |
@discordjs/rest’s REST | Rest (djs-rest) |
@discordjs/voice | client.voice() (djs-voice) |
ShardingManager, broadcastEval | ClusterManager, cluster commands |
time(), userMention(), bold() (formatters) | time, user_mention, bold, in djs_rs::formatters |
Collection | djs_rs::collection::Collection |
Methods are snake_case, types UpperCamelCase, constants SCREAMING_CASE: fetchAll
is fetch_all, ChannelType.GuildText is ChannelType::GuildText. The API reference
names the discord.js counterpart of every item (“discord.js counterpart: …”), so its
search finds a djs-rs item by its discord.js name.
What differs, and why
- The cache is opt-in. A client has none until
.cache(…)is called, and then keeps only what its configuration lists (guilds, channels and roles by default);CacheConfig::discord_js()keeps what discord.js does. A bot that does not read the cache pays nothing for it. See The cache. - No partials. discord.js drops events about uncached objects unless partials are
enabled. djs-rs always sends every event; what the cache did not hold is
None(theoldof an update) or an ID to fetch. - Shards are automatic.
Shards::Autois the default: a client runs as many shards as Discord recommends. - Errors are values. A failed request returns an error (
djs_rest::Error, with Discord’sErrorCode) instead of throwing;?in a handler passes it on, to be logged. - Interactions have routers.
client.command("ping", …),client.component("vote", …)andclient.modal("form", …)replace aswitchoncommandNameorcustomId; what follows a:in a custom ID is the handler’sargs. - Types are exact. A payload’s fields are typed as Discord documents them: an
optional field is an
Option, an edit’s field aPatch(keep, set, or clear), a channel an enum of its kinds (Channel::Text,Channel::Voice, …). The compiler checks what discord.js checks at run time. - Handlers run concurrently. Each event runs its handlers in a task of its own (the
default
HandlerMode::Concurrent), so a slow handler holds nothing up;HandlerMode::Sequentialkeeps the order of events. - No eval. Cluster commands are declared types compiled into the bot, not code sent as text.
Performance
The repository measures djs-rs and discord.js on the same machine with the same mock
Discord servers: decoding, an event flood, memory per server, REST throughput. The numbers
are in docs/VS_NODE.md.