Skip to main content

Context

Struct Context 

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

Everything an event handler needs to act: the REST client, the cache and the shard that received the event.

Cheap to clone (a single reference count increment). B is the cache backend of the Client (D-172); code that does not name it gets the default.

discord.js counterpart: the client reachable from every structure (message.client).

Implementations§

Source§

impl<B: Backend> Context<B>

Collectors by ID, for code that holds IDs rather than the channel or the message.

Source

pub fn message_collector( &self, channel: ChannelId, ) -> CollectorBuilder<Arc<MessageCreate>>

A collector of the messages sent in channel (D-263, D-269).

It ends at its limits, or when the channel, thread or guild is deleted. Needs the GUILD_MESSAGES or DIRECT_MESSAGES intent (and MESSAGE_CONTENT to read guild messages’ content).

discord.js counterpart: TextChannel#createMessageCollector.

§Examples
let mut messages = ctx
    .message_collector(msg.channel_id)
    .time(Duration::from_secs(60))
    .build();
while let Some(message) = messages.next().await {
    println!("{}: {}", message.author.username, message.content);
}
Source

pub fn await_messages( &self, channel: ChannelId, ) -> CollectorBuilder<Arc<MessageCreate>, All>

Collects the messages sent in channel until the collector ends, like message_collector; set a limit (time, max, …), or it only ends with the channel.

discord.js counterpart: TextChannel#awaitMessages.

Source

pub fn component_collector( &self, channel: ChannelId, ) -> CollectorBuilder<ComponentInteraction>

A collector of the component interactions (buttons, select menus) on every message of channel.

discord.js counterpart: TextChannel#createMessageComponentCollector.

Source

pub fn await_component( &self, channel: ChannelId, ) -> CollectorBuilder<ComponentInteraction, First>

Waits for one component interaction on any message of channel; set a time, or it only ends with the channel.

§Errors

CollectorError with the reason if the collector ended first.

discord.js counterpart: TextChannel#awaitMessageComponent.

Source§

impl<B: Backend> Context<B>

Source

pub fn application_id(&self) -> Option<ApplicationId>

Returns the bot’s application ID, known from the first READY (D-245); None only in handlers that run before it (ShardError, Invalidated, ShardDisconnect while logging in).

discord.js counterpart: client.application.id.

Source

pub fn rest(&self) -> &Rest

Returns the REST client.

discord.js counterpart: Client#rest.

Source

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

Returns the cache, if the client has one (ClientBuilder::cache, D-170). The event being handled is already applied to it (D-171).

discord.js counterpart: the managers’ cache collections (client.guilds.cache, …).

Source

pub fn shard_id(&self) -> ShardId

Returns the ID of the shard that received the event.

discord.js counterpart: the shardId some discord.js events pass; Guild#shardId.

Source

pub fn shard(&self) -> &MessageSender

Returns a sender for gateway commands on the shard that received the event.

discord.js counterpart: Guild#shard.

Source

pub fn shutdown(&self)

Asks the client to disconnect, as Client::shutdown does: every shard closes, the session is invalidated (the bot appears offline) and Client::login returns Ok(()). Has no effect once the client has stopped.

discord.js counterpart: client.destroy() (through message.client).

§Examples
use djs_rs::{model::id::UserId, prelude::*};

const OWNER: UserId = UserId::new(123_456_789_012_345_678);
client.on(Events::MessageCreate, |ctx, msg| async move {
    if msg.content == "!stop" && msg.author.id == OWNER {
        msg.reply(&ctx, "Bye!").await?;
        ctx.shutdown();
    }
    Ok(())
});
Source§

impl<B: Backend> Context<B>

Converts REST objects to the cached types through the context’s cache (D-230, D-233), with the code compiled in djs-rs (D-289).

Source

pub const fn guilds(&self) -> GuildManager<'_, B>

Returns the guild manager (D-229).

discord.js counterpart: Client#guilds.

Source

pub const fn channels(&self) -> ChannelManager<'_, B>

Returns the channel manager.

discord.js counterpart: Client#channels.

Source

pub const fn guild_channels( &self, guild_id: GuildId, ) -> GuildChannelManager<'_, B>

Returns the manager of a guild’s channels as a whole: create, list, positions (D-234).

discord.js counterpart: Guild#channels.

Source

pub const fn users(&self) -> UserManager<'_, B>

Returns the user manager.

discord.js counterpart: Client#users.

Source

pub const fn members(&self, guild_id: GuildId) -> MemberManager<'_, B>

Returns the manager of a guild’s members.

discord.js counterpart: Guild#members.

Source

pub const fn messages(&self, channel_id: ChannelId) -> MessageManager<'_, B>

Returns the manager of a channel’s messages.

discord.js counterpart: TextChannel#messages (and TextChannel#send).

Source

pub const fn roles(&self, guild_id: GuildId) -> RoleManager<'_, B>

Returns the manager of a guild’s roles.

discord.js counterpart: Guild#roles.

Source

pub const fn bans(&self, guild_id: GuildId) -> BanManager<'_, B>

Returns the manager of a guild’s bans.

discord.js counterpart: Guild#bans.

Source

pub const fn emojis(&self, guild_id: GuildId) -> EmojiManager<'_, B>

Returns the manager of a guild’s custom emojis.

discord.js counterpart: Guild#emojis.

Source

pub const fn stickers(&self, guild_id: GuildId) -> StickerManager<'_, B>

Returns the manager of a guild’s stickers.

discord.js counterpart: Guild#stickers.

Source

pub const fn scheduled_events( &self, guild_id: GuildId, ) -> ScheduledEventManager<'_, B>

Returns the manager of a guild’s scheduled events.

discord.js counterpart: Guild#scheduledEvents.

Source

pub const fn stage_instances( &self, guild_id: GuildId, ) -> StageInstanceManager<'_, B>

Returns the manager of a guild’s live stages.

discord.js counterpart: Guild#stageInstances.

Source

pub const fn soundboard_sounds( &self, guild_id: GuildId, ) -> SoundboardSoundManager<'_, B>

Returns the manager of a guild’s soundboard sounds.

discord.js counterpart: Guild#soundboardSounds.

Source

pub const fn threads(&self, channel_id: ChannelId) -> ThreadManager<'_, B>

Returns the manager of the threads of a parent channel (D-242).

discord.js counterpart: TextChannel#threads / ForumChannel#threads.

Source

pub const fn thread_members( &self, thread_id: ChannelId, ) -> ThreadMemberManager<'_, B>

Returns the manager of a thread’s members (D-242).

discord.js counterpart: ThreadChannel#members.

Source

pub async fn default_soundboard_sounds( &self, ) -> Result<Collection<SoundboardSoundId, SoundboardSound>, Error>

Discord’s default soundboard sounds, available in every guild (List Default Soundboard Sounds; D-243). They are not cached.

discord.js counterpart: Client#fetchDefaultSoundboardSounds.

§Errors

Returns the REST error if the request failed.

Source

pub fn commands(&self) -> CommandManager<'_, B>

Returns the manager of the bot’s global application commands (D-244).

discord.js counterpart: client.application.commands.

§Panics

Panics before the first READY, while the application ID is unknown (D-247): only in ShardError, Invalidated or ShardDisconnect handlers running while logging in.

Source

pub fn guild_commands(&self, guild_id: GuildId) -> GuildCommandManager<'_, B>

Returns the manager of the bot’s application commands in a guild, and their permissions there (D-244).

discord.js counterpart: Guild#commands.

§Panics

Panics before the first READY (D-247), like commands.

Source

pub fn application_emojis(&self) -> ApplicationEmojiManager<'_, B>

Returns the manager of the application’s own emojis.

discord.js counterpart: client.application.emojis.

§Panics

Panics before the first READY (D-247), like commands.

Source

pub const fn auto_moderation_rules( &self, guild_id: GuildId, ) -> AutoModerationRuleManager<'_, B>

Returns the manager of a guild’s auto moderation rules.

discord.js counterpart: Guild#autoModerationRules.

Source

pub async fn sticker(&self, sticker_id: StickerId) -> Result<Sticker, Error>

A sticker by its ID, standard or from a guild (Get Sticker). Not cached.

discord.js counterpart: Client#fetchSticker.

§Errors

Returns the REST error if the request failed.

Source

pub async fn sticker_packs( &self, ) -> Result<Collection<StickerPackId, StickerPack>, Error>

Discord’s standard sticker packs (List Sticker Packs). Not cached.

discord.js counterpart: Client#fetchStickerPacks.

§Errors

Returns the REST error if the request failed.

Source

pub async fn sticker_pack( &self, pack_id: StickerPackId, ) -> Result<StickerPack, Error>

One standard sticker pack (Get Sticker Pack). Not cached.

discord.js counterpart: Client#fetchStickerPacks({ packId }).

§Errors

Returns the REST error if the request failed.

Source

pub const fn invites(&self) -> InviteManager<'_, B>

Returns the invite manager (D-239).

discord.js counterpart: Guild#invites and Client#fetchInvite.

Source

pub const fn webhooks(&self) -> WebhookManager<'_, B>

Returns the webhook manager (D-237).

discord.js counterpart: the webhook methods of TextChannel, Guild and Client.

Trait Implementations§

Source§

impl<B: Backend> Clone for Context<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: Debug + Backend> Debug for Context<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 Context<B>

§

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

§

impl<B> Freeze for Context<B>

§

impl<B> Send for Context<B>

§

impl<B> Sync for Context<B>

§

impl<B> Unpin for Context<B>

§

impl<B> UnsafeUnpin for Context<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