Skip to main content

Client

Struct Client 

Source
pub struct Client<B: Backend = DashMapBackend> { /* private fields */ }
Expand description

A Discord bot client: connects to the gateway, keeps the session alive and dispatches events to registered handlers.

Cheap to Clone; clones share the same handlers, connection and cache.

The client keeps a Cache only when one is configured with ClientBuilder::cache (D-170); unlike discord.js, a bot that does not need one pays nothing for it. B is the cache’s storage Backend (D-172): code that does not name it gets DashMapBackend, and ClientBuilder::cache_backend picks another.

discord.js counterpart: Client.

§Examples

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
}

Implementations§

Source§

impl Client

Source

pub fn builder(token: impl Into<String>) -> ClientBuilder

Returns a builder for a client authenticated with token (without the Bot prefix).

discord.js counterpart: new Client(options).

Source§

impl<B: Backend> Client<B>

Source

pub fn on<E, F, Fut>(&self, event: E, handler: F) -> &Self
where E: Event, F: Fn(Context<B>, Arc<E::Payload>) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,

Registers a handler for an event.

The handler receives a Context and the event payload behind an Arc (shared by all handlers of the event). It returns Result<(), HandlerError>: use ? freely — errors are logged through tracing at error level. Handlers can be added at any time, including while the client is running.

discord.js counterpart: client.on(event, listener).

§Examples
client.on(Events::MessageCreate, |ctx, msg| async move {
    if msg.content == "!ping" {
        msg.reply(&ctx, "Pong!").await?;
    }
    Ok(())
});
Source

pub fn command<F, Fut>(&self, name: &str, handler: F) -> &Self
where F: Fn(Context<B>, CommandInteraction) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,

Routes the command name to handler (the router, D-251–D-253).

name is the command’s full name as Discord shows it, with single spaces: "ping", "mod ban" (a subcommand), "mod config set" (a subcommand in a group), or the name of a user or message command. A route for "mod" or "mod config" also receives the subcommands below it that have no route of their own. Registering a name again replaces its handler; routes can be added while the client runs.

The handler receives a CommandInteraction: the command’s data (get_string, …) and its responses (reply, …). Like event handlers it returns Result<(), HandlerError>, and errors are logged. The router only routes: commands are registered with Discord through Context::commands (D-255), and Events::InteractionCreate still fires.

discord.js has no counterpart (a switch on interaction.commandName).

§Examples
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(())
});
Source

pub fn autocomplete<F, Fut>(&self, name: &str, handler: F) -> &Self
where F: Fn(Context<B>, AutocompleteInteraction) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,

Routes the autocomplete interactions of the command name to handler; name is matched like in command. The handler receives an AutocompleteInteraction and answers with respond.

discord.js counterpart: an interactionCreate listener checking isAutocomplete() and commandName.

§Examples
client.autocomplete("search", |ctx, search| async move {
    let typed = search.focused_value().unwrap_or_default();
    let choices = vec![Choice::new(format!("{typed}…"), typed.into())];
    search.respond(&ctx, AutocompleteChoices::String(choices)).await?;
    Ok(())
});
Source

pub fn component<F, Fut>(&self, name: &str, handler: F) -> &Self
where F: Fn(Context<B>, ComponentInteraction) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,

Routes the buttons and select menus whose custom ID is name, or starts with name:, to handler (D-254). What follows the : is the handler’s args: a button delete:123 reaches the route "delete" with the arguments 123. Registering a name again replaces its handler.

discord.js counterpart: an interactionCreate listener checking isMessageComponent() and customId.

§Panics

Panics if name contains a : (it could never match).

§Examples
client.component("delete", |ctx, button| async move {
    let message_id = button.args();
    button.update(&ctx, format!("Deleted {message_id}")).await?;
    Ok(())
});
Source

pub fn modal<F, Fut>(&self, name: &str, handler: F) -> &Self
where F: Fn(Context<B>, ModalInteraction) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,

Routes the modals whose custom ID is name, or starts with name:, to handler, like component. The handler receives a ModalInteraction with the submitted fields.

discord.js counterpart: an interactionCreate listener checking isModalSubmit() and customId.

§Panics

Panics if name contains a : (it could never match).

§Examples
client.modal("feedback", |ctx, modal| async move {
    let text = modal.text_value("text").unwrap_or_default();
    modal.reply(&ctx, format!("Thanks for: {text}")).await?;
    Ok(())
});
Source

pub fn required_intents(&self) -> Intents

The intents the registered handlers, routes and running collectors need (D-272): the union of their events’ Event::INTENTS, to print or compare with the client’s.

Requesting all of them receives every such event; a bot may still leave some out (for example DIRECT_MESSAGES when it only reads guild messages). It does not include Intents::MESSAGE_CONTENT, which changes what message events contain rather than which arrive. The client’s intents stay what ClientBuilder::intents set; at login it warns about events none of them covers (D-271).

discord.js has no counterpart.

§Examples
let client = Client::builder("token").intents(Intents::GUILDS).build();
client.on(Events::MessageReactionAdd, |_ctx, _reaction| async move { Ok(()) });
assert!(client.required_intents().contains(Intents::GUILD_MESSAGE_REACTIONS));
Source

pub fn events(&self) -> EventStream

Returns a stream of every event the client receives (D-029).

This is the alternative to on for full control. Each call creates an independent subscriber that receives every event from the moment it was created.

Note: the stream is unbounded — consume it promptly, or drop it, to avoid accumulating events in memory.

discord.js counterpart: none (discord.js delivers events to listeners only).

§Examples
let mut events = client.events();
tokio::spawn(async move {
    while let Some(event) = events.next().await {
        if let Dispatch::MessageCreate(message) = event.event {
            println!("{}", message.content);
        }
    }
});
client.login().await.unwrap();
Source

pub fn rest(&self) -> &Rest

Returns the REST client.

discord.js counterpart: Client#rest.

Source

pub fn voice(&self) -> &VoiceManager

Returns the bot’s voice calls: join voice channels, play audio, leave (D-345).

The manager is there from the start; the client sends its Opcode 4 through the guild’s shard and passes it the voice events. Joins need the client logged in, with the guild’s shard in this process, and the GUILD_VOICE_STATES intent: the first call warns when the intent is missing (D-346). shutdown leaves every call (D-348).

discord.js counterpart: joinVoiceChannel({ adapterCreator: guild.voiceAdapterCreator, … }) of @discordjs/voice.

§Examples
use djs_rs::voice::Input;

let call = client.voice().join(guild, channel).await?;
call.play(Input::ogg_file("song.opus").await?);
Source

pub fn cache(&self) -> Option<&Cache<B>>

Returns the cache, or None if the client was built without one (the default, D-170).

Every event is applied to the cache before its handlers run (D-171), so a handler sees the state after its event. Handlers reach the cache through Context::cache too.

discord.js counterpart: the managers’ cache collections (client.guilds.cache, client.users.cache, …), which always exist there.

§Examples
use djs_rs::{cache::CacheConfig, prelude::*};

let client = Client::builder("token")
    .intents(Intents::GUILDS)
    .cache(CacheConfig::default())
    .build();

client.on(Events::MessageCreate, |ctx, msg| async move {
    let cache = ctx.cache().expect("the client has a cache");
    if let Some(guild) = msg.guild_id.and_then(|id| cache.guilds().get(id)) {
        println!("a message in {}", guild.name);
    }
    Ok(())
});
Source

pub fn cluster(&self) -> Option<ClusterClient<B>>

This process’s cluster, for a client built with ClientBuilder::cluster: its assignment, the commands it handles and its requests to the other clusters (D-301). None for any other client.

discord.js counterpart: Client#shard.

Source§

impl<B: Backend> Client<B>

Logging in and running the shards (the gateway feature, D-395).

Source

pub fn login(&self) -> impl Future<Output = Result<(), Error>> + Send + '_

Connects to Discord and processes events until shutdown is called or the connection fails fatally.

The connection heals itself: disconnects are resumed and failures retried with backoff.

The client asks Discord (Get Gateway Bot) for the gateway URL, the recommended shard count and max_concurrency, then runs every shard chosen with ClientBuilder::shards in its own task. A fatal error on any shard stops them all. Get Gateway Bot is skipped if both ClientBuilder::gateway_url and a fixed shard count are configured (shards then identify one at a time), and in a cluster process (ClientBuilder::cluster, with the sharding feature), which gets them from its manager.

discord.js counterpart: Client#login.

§Errors

Returns Error::Rest if the gateway URL cannot be fetched (for example because the token is invalid), Error::SessionStartLimit if Discord’s daily session start limit does not allow starting every shard, Error::Gateway on a fatal gateway close (invalid token, disallowed intents, …), or Error::AlreadyRunning if the client is already logged in.

§Panics

Re-raises a panic of a shard’s task (only possible with HandlerMode::Sequential, when a handler panics).

Source

pub fn set_presence(&self, presence: &UpdatePresence) -> Result<(), SendError>

Updates the bot’s presence (status and activities) on every running shard. Each shard also keeps it for its later sessions (D-148).

Has no effect if the client is not running; set the presence to start with through ClientBuilder::presence.

discord.js counterpart: ClientUser#setPresence.

§Errors

Returns SendError::Closed if a shard has stopped (the client is shutting down); the other shards are still updated.

§Examples
use djs_rs::{
    model::gateway::{Activity, Status, payload::UpdatePresence},
    prelude::*,
};

let handle = client.clone();
client.on(Events::MessageCreate, move |_ctx, msg| {
    let client = handle.clone();
    async move {
        if msg.content == "!busy" {
            let busy = UpdatePresence::new(Status::DoNotDisturb, [Activity::custom("Busy")]);
            client.set_presence(&busy)?;
        }
        Ok(())
    }
});
Source

pub fn shutdown(&self)

Asks a running client to disconnect; login then returns Ok(()).

The session is invalidated (the bot appears offline). Has no effect if the client is not running.

discord.js counterpart: Client#destroy.

Source§

impl<B: Backend> Client<B>

Source

pub fn interactions_endpoint( &self, public_key: &str, ) -> Result<InteractionsEndpoint<B>, InvalidPublicKey>

Returns an endpoint answering the interactions Discord posts to the app’s Interactions Endpoint URL with this client’s routes and handlers (D-398): see http_interactions. public_key is the app’s public key from the Developer Portal (General Information), in hexadecimal.

The client needs no login for it; a client that is also logged in (a hybrid bot) gives HTTP interactions the context of their guild’s shard (D-403).

discord.js counterpart: none (discord.js only receives interactions over the gateway).

§Errors

Returns InvalidPublicKey if public_key is not 64 hexadecimal digits of a valid Ed25519 key.

Trait Implementations§

Source§

impl<B: Backend> Clone for Client<B>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<B: Backend> Debug for Client<B>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<B = DashMapBackend> !RefUnwindSafe for Client<B>

§

impl<B = DashMapBackend> !UnwindSafe for Client<B>

§

impl<B> Freeze for Client<B>

§

impl<B> Send for Client<B>

§

impl<B> Sync for Client<B>

§

impl<B> Unpin for Client<B>

§

impl<B> UnsafeUnpin for Client<B>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<T> Classify for T

§

type Classified = T

§

fn classify(self) -> T

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> Declassify for T

§

type Declassified = T

§

fn declassify(self) -> T

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more