Skip to main content

Crate djs_rs

Crate djs_rs 

Source
Expand description

§djs-rs

A high-performance, discord.js-style framework for building Discord bots in Rust.

Status: alpha. A complete client: automatic sharding, every discord.js event (with the previous state from the cache), managers for every resource with methods on the structures, interaction responses, typed option getters and routers, collectors, a WebhookClient, an optional cache, multi-process sharding (sharding) and voice (voice). The API may still change between alpha releases; see the changelog.

discord.js counterpart: discord.js

§Example

use djs_rs::prelude::*;

#[tokio::main]
async fn main() -> Result<(), djs_rs::Error> {
    let client = Client::builder(std::env::var("DISCORD_TOKEN").unwrap())
        .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(())
    });

    client.login().await
}

A runnable version lives in examples/ping.rs.

§More examples

Each example is one file in examples/, run with cargo run --example <name>, its setup explained at the top. They read DISCORD_TOKEN (and their other settings) from the environment or a git-ignored .env (see .env.example).

ExampleWhat it shows
pingthe smallest bot: !ping → Pong!
slash_commandsguild command registration, the router, options and subcommands, autocomplete, a modal awaited with await_modal_submit, ephemeral and deferred replies
componentsa paginated button menu with a component collector, a quiz with await_messages, a reaction poll with await_reactions
moderationjoin, leave, ban, edit and deletion logs with the cached previous state, /timeout, /ban, /purge and /members (fetch_all) limited to moderators
advancedShards::Auto, a changing presence, the events() stream, HandlerMode::Sequential, WebhookClient, mimalloc

The examples that register commands remove them again with -- --cleanup.

§How it fits together

djs-rs wires the lower-level crates into a discord.js-like client:

LayerCrateRe-exported as
Discord API typesdjs-modeldjs_rs::model
REST clientdjs-restdjs_rs::rest
Gatewaydjs-gatewaydjs_rs::gateway
Cachedjs-cachedjs_rs::cache
Builders (embeds, commands, components, modals)djs-buildersdjs_rs::builders
Formatters (mentions, timestamps, markdown, escaping)djs-formattersdjs_rs::formatters
Collection (insertion-ordered map with discord.js’ helpers)djs-collectiondjs_rs::collection

§Events

Events has discord.js’ events by their names (Events::GuildMemberAdd, Events::MessageUpdate, …), the gateway dispatches discord.js has no event for, the shard lifecycle (ShardReady, ShardReconnecting, ShardResume, Invalidated, ShardError, ShardDisconnect) and Raw, which hands every dispatch as it was decoded.

  • Most handlers receive the djs-model payload unchanged (behind an Arc).
  • Where discord.js hands an old or a removed object, the payload has old — what the cache held before the event, None without a cache — and new, and reads like new: update.old and update.content in a MessageUpdate handler.
  • GuildCreate (joined) and GuildAvailable (back from READY or an outage) are told apart with or without a cache; the per-emoji and per-sticker events need those in the cache.
  • ClientReady fires once, at the READY of the last shard, without waiting for the guilds (unlike discord.js, the cache may still be filling).
use djs_rs::prelude::*;

fn log_edits(client: &Client) {
    client.on(Events::MessageUpdate, |_ctx, update| async move {
        if let Some(old) = &update.old {
            println!("edited: {:?} -> {:?}", old.content, update.content);
        }
        Ok(())
    });
}

Handlers run concurrently in their own tokio tasks by default (like discord.js); switch to HandlerMode::Sequential for strictly ordered processing. If you prefer an explicit loop, client.events() returns a stream of every event (all but Raw).

§Intents and partials

Discord only sends an event if the client requests one of its intents (Event::INTENTS; MessageCreate comes with GUILD_MESSAGES for guilds and DIRECT_MESSAGES for DMs). At login the client warns about handlers, routes and collectors whose events none of its intents covers (D-271), and client.required_intents() shows what they need (D-272); the intents themselves stay explicit. Reading guild messages’ content also needs the privileged MESSAGE_CONTENT intent.

There is no partials option (D-273): every event arrives even when the cache does not hold its objects — old is None and payloads carry IDs — and the managers’ fetch completes them. The documentation of the djs_rs::event module maps each discord.js partial to what djs-rs hands instead.

§Managers and structure methods

The operations of a resource live on a manager reached from the handler Context: ctx.guilds(), ctx.channels(), ctx.guild_channels(guild), ctx.users(), ctx.members(guild), ctx.messages(channel), ctx.roles(guild), ctx.bans(guild), ctx.emojis(guild), ctx.stickers(guild), ctx.scheduled_events(guild), ctx.stage_instances(guild), ctx.soundboard_sounds(guild), ctx.threads(channel), ctx.thread_members(thread), ctx.auto_moderation_rules(guild), ctx.commands(), ctx.guild_commands(guild), ctx.application_emojis(), ctx.invites() and ctx.webhooks() (discord.js’ client.guilds, guild.channels, guild.members, channel.threads, client.application.commands, …).

  • fetch(id) returns the cached value without a request, and asks Discord otherwise; the answer is cached. .force() always asks Discord; .is_cached() tells beforehand.
  • Lists (ctx.roles(guild).list(), ctx.messages(channel).list(&query), …) are Collections in Discord’s order.
  • Managers return the type the cache keeps, behind an Arc (Arc<CachedMember>, Arc<CachedMessage>, Arc<Channel>, …), whether the value came from the cache or from Discord, and with or without a cache. Bans, which are never cached, are djs-model types.
  • Deleting through a manager only sends the request: the cache changes when the gateway event arrives, so the delete event still carries the previous state.
  • Some answers come through the gateway: ctx.members(guild).fetch_all(), .fetch_by_query("ab") and .fetch_many(ids) gather the member chunks of their request (D-270), and ctx.guilds().fetch_soundboard_sounds(ids, time) the sounds of several guilds.

Structures stay plain data; behaviour such as msg.reply(&ctx, …) comes from extension traits in the prelude (MessageExt, ChannelExt, UserExt, MemberExt, GuildExt) that take the Context explicitly — no client reference is stored in every structure. They work on the model types, the cached types and the event payloads that dereference to them.

use djs_rs::{model::util::Timestamp, prelude::*};

fn moderate(client: &Client) {
    client.on(Events::MessageCreate, |ctx, msg| async move {
        let Some(guild_id) = msg.guild_id else { return Ok(()) };
        if msg.content.contains("discord.gg/") {
            msg.delete(&ctx).await?;
            let member = ctx.members(guild_id).fetch(msg.author.id).await?;
            let in_ten_minutes = Timestamp::from_unix_secs(Timestamp::now().as_unix_secs() + 600);
            member.timeout(&ctx, in_ten_minutes, Some("invite link")).await?;
            msg.author.send(&ctx, "Invite links are not allowed here.").await?;
        }
        Ok(())
    });
}

§Interactions

Slash commands, context menus, buttons, select menus, modals and autocomplete all arrive as Events::InteractionCreate (as in discord.js). interaction.command(), component(), modal() and autocomplete() return the typed data of that kind, whose getters read the options and fields with their resolved users, members, roles and channels — get_string("reason"), get_user("target"), subcommand(), text_value("feedback"), selected_roles("roles"), … (discord.js’ CommandInteractionOptionResolver and ModalSubmitFields). InteractionExt in the prelude answers: reply, defer_reply, edit_reply, follow_up, update, defer_update, show_modal, respond, … — one method per Discord callback; the order Discord requires is documented on the trait.

use djs_rs::{model::message::MessageFlags, prelude::*};

fn interactions(client: &Client) {
    client.on(Events::InteractionCreate, |ctx, interaction| async move {
        if let Some(command) = interaction.command() {
            match command.name.as_str() {
                "greet" => {
                    let who = command.get_user("user").map_or("stranger", |user| &user.username);
                    interaction.reply(&ctx, format!("Hello, {who}!")).await?;
                }
                "report" => {
                    interaction.defer_reply(&ctx, MessageFlags::EPHEMERAL).await?;
                    // … slow work, up to 15 minutes …
                    interaction.edit_reply(&ctx, "Report sent").await?;
                }
                _ => {}
            }
        } else if let Some(modal) = interaction.modal() {
            let feedback = modal.text_value("feedback").unwrap_or_default();
            interaction.reply(&ctx, format!("Thanks for: {feedback}")).await?;
        }
        Ok(())
    });
}

§The router

Instead of one match in InteractionCreate, handlers can be routed by name (D-251–D-255): client.command("mod ban", …) for a subcommand (a route for "mod" catches the subcommands without their own), client.autocomplete(…), and client.component("vote", …) / client.modal(…) by the custom_id part before : — vote:42 reaches "vote" with args() = "42". Each handler gets a typed wrapper that dereferences to the data and answers like the interaction. The router does not register commands with Discord (use ctx.commands().set(…)), and InteractionCreate still fires for every interaction.

use djs_rs::prelude::*;

fn routes(client: &Client) {
    client.command("ping", |ctx, cmd| async move {
        cmd.reply(&ctx, "Pong!").await?;
        Ok(())
    });
    client.command("mod ban", |ctx, cmd| async move {
        let reason = cmd.get_string("reason").unwrap_or("no reason");
        cmd.reply(&ctx, format!("Banned: {reason}")).await?;
        Ok(())
    });
    client.component("vote", |ctx, button| async move {
        button.update(&ctx, format!("Voted for {}", button.args())).await?;
        Ok(())
    });
}

§Collectors

A collector yields what arrives where it watches — the messages of a channel, the reactions or components of a message, the components of an interaction’s reply, the modals a user submits — as a stream, until its time, idle or max limit, its stop(), or the deletion of what it watches (D-263–D-269). The await_* shortcuts wait for one click or modal (Result, with the reason on failure) or collect until the end (a Collection with reason()). Events reach collectors through an index by ID, so a thousand open menus cost an event one lookup, and they still reach the handlers and the router.

use std::time::Duration;

use djs_rs::prelude::*;

fn quiz(client: &Client) {
    client.on(Events::MessageCreate, |ctx, msg| async move {
        if msg.content != "!quiz" {
            return Ok(());
        }
        msg.reply(&ctx, "What is 6 × 7?").await?;
        let author = msg.author.id;
        let answers = ctx
            .await_messages(msg.channel_id)
            .filter(move |answer| answer.author.id == author)
            .max(1)
            .time(Duration::from_secs(30))
            .await;
        let verdict = match answers.first() {
            Some(answer) if answer.content.trim() == "42" => "Correct!",
            Some(_) => "No, it is 42.",
            None => "Time is up.",
        };
        msg.reply(&ctx, verdict).await?;
        Ok(())
    });
}

With the Sequential handler mode a handler waiting for a collector blocks its shard, so the collector receives nothing from it; keep the default Concurrent mode (D-267).

§Webhooks without a bot

WebhookClient sends through a webhook URL — from a script, a CI job or a server — with no bot token and no gateway connection (discord.js’ WebhookClient):

use djs_rs::WebhookClient;

let webhook = WebhookClient::from_url(&std::env::var("WEBHOOK_URL")?)?;
webhook.send("Build passed").await?;

§The cache

Unlike discord.js, the client keeps a cache only when asked to: a bot that does not read it pays nothing for it. ClientBuilder::cache takes a CacheConfig choosing what to keep (by default guilds, channels and roles; CacheConfig::discord_js() keeps what discord.js keeps). Every event is applied to the cache before its handlers run, and the client runs the configured periodic sweeps while it is logged in.

use djs_rs::{
    cache::{CacheConfig, Limit},
    prelude::*,
};

#[tokio::main]
async fn main() -> Result<(), djs_rs::Error> {
    let client = Client::builder(std::env::var("DISCORD_TOKEN").unwrap())
        .intents(Intents::GUILDS | Intents::GUILD_MEMBERS | Intents::GUILD_MESSAGES)
        .cache(CacheConfig::builder().members(Limit::Unlimited).build())
        .build();

    client.on(Events::MessageCreate, |ctx, msg| async move {
        let cache = ctx.cache().expect("the client has a cache");
        if let Some(member) = msg.guild_id.and_then(|id| cache.members(id).get(msg.author.id)) {
            println!("{} wrote a message", member.display_name());
        }
        Ok(())
    });

    client.login().await
}

The cache’s storage is pluggable: ClientBuilder::cache_backend takes any djs_rs::cache::Backend, and the client’s type follows it (Client<MyBackend>); code that does not name a backend uses the default DashMapBackend.

§Performance: the global allocator

With the default concurrent handlers, events are decoded on the shard’s task and dropped on tokio worker threads. The default allocator on Linux (glibc) handles this producer/consumer pattern poorly. In the stress tests (tests/stress_mimalloc.rs, see docs/PERFORMANCE.md), using mimalloc as the bot’s global allocator raised the throughput by about 80 % with 10 handlers per event, by 30–50 % with an events() stream and by about 15 % with one handler; with HandlerMode::Sequential it made no difference. These are rates of hundreds of thousands of events per second per shard, so only very large bots need to care. To switch, add mimalloc = "0.1" to your bot’s dependencies and declare:

#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

§Cargo features

FeatureDefaultDescription
zstd-stream✅zstd-stream gateway compression (needs a C compiler)
zlib-streamzlib-stream gateway compression in pure Rust (no C compiler)
gateway✓The gateway: Client::login, shards, the gateway events, presence and the gateway requests (fetch_all, …). Without it (and without hyper, given a Rest with a Transport) djs-rs builds for wasm32-unknown-unknown, for HTTP interactions on Cloudflare Workers
hyper✓The REST client’s default transport, hyper with rustls (djs-rest’s hyper); without it, give ClientBuilder::rest a Rest with a Transport
native-rootsAlso trust the operating system’s root certificates (e.g. a corporate proxy’s CA), in addition to the bundled Mozilla roots, for REST, gateway and voice connections
shardingMulti-process sharding: djs_rs::sharding and its ClusterManager
voiceVoice: client.voice() joins voice channels and plays audio, with DAVE end-to-end encryption (djs_rs::voice, the djs-voice crate)
http-interactionsHTTP interactions: client.interactions_endpoint(public_key) answers the requests Discord posts to the app’s Interactions Endpoint URL with the same routes and handlers, in any HTTP server (djs_rs::http_interactions)

§License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Re-exports§

pub use self::client::Client;
pub use self::client::ClientBuilder;
pub use self::client::EventStream;
pub use self::client::HandlerMode;
pub use self::context::Context;
pub use self::error::Error;
pub use self::event::Events;
pub use self::handler::HandlerError;
pub use self::webhook::WebhookClient;
pub use djs_model as model;
pub use djs_rest as rest;
pub use djs_gateway as gateway;
pub use djs_cache as cache;
pub use djs_builders as builders;
pub use djs_formatters as formatters;
pub use djs_collection as collection;

Modules§

collector
Collectors: streams of the messages, reactions, component interactions and modal submissions that arrive while a bot waits for them (D-263–D-269).
event
Typed client events (D-222).
ext
Methods on Discord structures (discord.js-style “structures” behaviour, D-220).
http_interactions
HTTP interactions (D-395, D-398–D-403): answering the interactions Discord posts to the app’s Interactions Endpoint URL with the same routes and handlers as a gateway bot.
manager
Managers: the operations of one resource, reached from the Context (D-229).
prelude
The most commonly used items, for a single glob import:
router
The interaction router (D-251–D-255): handlers registered by command name or by component and modal custom_id, next to Events::InteractionCreate.
sharding
Multi-process sharding (D-284): a ClusterManager runs a bot’s shards in several processes of the same executable (D-296), shards_per_process shards each (D-297).
voice
Voice: djs-voice plugged into the Client (D-315, D-345–D-348), behind the voice feature.
webhook
Webhooks without a bot: WebhookClient (D-238), and the errors of the webhook methods.

Structs§

Client
A Discord bot client: connects to the gateway, keeps the session alive and dispatches events to registered handlers.
ClientBuilder
Configures and builds a Client. Created by Client::builder.
Context
Everything an event handler needs to act: the REST client, the cache and the shard that received the event.
EventStream
A stream of every event a Client receives. Created by Client::events.

Enums§

Error
An error that stops Client::login.
HandlerMode
How event handlers are executed (D-028).
Shards
Which shards a Client runs (D-146).

Type Aliases§

HandlerError
The error type event handlers may return. Any error type converts into it with ?.