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
impl Client
Sourcepub fn builder(token: impl Into<String>) -> ClientBuilder
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>
impl<B: Backend> Client<B>
Sourcepub fn on<E, F, Fut>(&self, event: E, handler: F) -> &Self
pub fn on<E, F, Fut>(&self, event: E, handler: F) -> &Self
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(())
});Sourcepub fn command<F, Fut>(&self, name: &str, handler: F) -> &Selfwhere
F: Fn(Context<B>, CommandInteraction) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,
pub fn command<F, Fut>(&self, name: &str, handler: F) -> &Selfwhere
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(())
});Sourcepub fn autocomplete<F, Fut>(&self, name: &str, handler: F) -> &Selfwhere
F: Fn(Context<B>, AutocompleteInteraction) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,
pub fn autocomplete<F, Fut>(&self, name: &str, handler: F) -> &Selfwhere
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(())
});Sourcepub fn component<F, Fut>(&self, name: &str, handler: F) -> &Selfwhere
F: Fn(Context<B>, ComponentInteraction) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,
pub fn component<F, Fut>(&self, name: &str, handler: F) -> &Selfwhere
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(())
});Sourcepub fn modal<F, Fut>(&self, name: &str, handler: F) -> &Selfwhere
F: Fn(Context<B>, ModalInteraction) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), HandlerError>> + Send + 'static,
pub fn modal<F, Fut>(&self, name: &str, handler: F) -> &Selfwhere
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(())
});Sourcepub fn required_intents(&self) -> Intents
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));Sourcepub fn events(&self) -> EventStream
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();Sourcepub fn voice(&self) -> &VoiceManager
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?);Sourcepub fn cache(&self) -> Option<&Cache<B>>
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(())
});Sourcepub fn cluster(&self) -> Option<ClusterClient<B>>
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).
impl<B: Backend> Client<B>
Logging in and running the shards (the gateway feature, D-395).
Sourcepub fn login(&self) -> impl Future<Output = Result<(), Error>> + Send + '_
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).
Sourcepub fn set_presence(&self, presence: &UpdatePresence) -> Result<(), SendError>
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§impl<B: Backend> Client<B>
impl<B: Backend> Client<B>
Sourcepub fn interactions_endpoint(
&self,
public_key: &str,
) -> Result<InteractionsEndpoint<B>, InvalidPublicKey>
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§
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> Classify for T
impl<T> Classify for T
type Classified = T
fn classify(self) -> T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<T> Declassify for T
impl<T> Declassify for T
type Declassified = T
fn declassify(self) -> T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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