Struct serenity::client::Context
[−]
[src]
pub struct Context { pub channel_id: Option<ChannelId>, pub data: Arc<Mutex<ShareMap>>, pub shard: Arc<Mutex<Shard>>, pub queue: String, // some fields omitted }
The context is a general utility struct provided on event dispatches, which
helps with dealing with the current "context" of the event dispatch,
and providing helper methods where possible. The context also acts as a
general high-level interface over the associated Shard
which
received the event, or the low-level rest
module.
For example, when the Client::on_message
handler is dispatched to, the
context will contain the Id of the Channel
that the message was created
for. This allows for using shortcuts like say
, which will
post its given argument to the associated channel for you as a Message
.
Additionally, the context contains "shortcuts", like for interacting with
the shard. Methods like set_game
will unlock the shard and perform an
update for you to save a bit of work.
A context will only live for the event it was dispatched for. After the event handler finished, it is destroyed and will not be re-used.
Automatically using the Cache
The context makes use of the Cache
being global, and will first check
the cache for associated data before hitting the REST API. This is to save
Discord requests, and ultimately save your bot bandwidth and time. This also
acts as a clean interface for retrieving from the cache without needing to
check it yourself first, and then performing a request if it does not exist.
The context ultimately acts as a means to simplify these two operations into
one.
For example, if you are needing information about a
channel within a guild, then you can
use get_channel
to retrieve it. Under most circumstances, the guild and
its channels will be cached within the cache, and get_channel
will just
pull from the cache. If it does not exist, it will make a request to the
REST API, and then insert a clone of the channel into the cache, returning
you the channel.
In this scenario, now that the cache has the channel, performing the same
request to get_channel
will instead pull from the cache, as it is now
cached.
Fields
channel_id: Option<ChannelId>
The Id of the relevant channel, if there is one. This is present on the
on_message
handler, for example.
data: Arc<Mutex<ShareMap>>
A clone of Client::data
. Refer to its documentation for more
information.
The associated shard which dispatched the event handler.
Note that if you are sharding, in relevant terms, this is the shard which received the event being dispatched.
queue: String
The queue of messages that are sent after context goes out of scope.
Methods
impl Context
[src]
fn ack<M: Into<MessageId>>(&self, message_id: M) -> Result<()>
Marks the contextual channel as being read up to a certain Message
.
Refer to the documentation for rest::ack_message
for more
information.
Errors
Returns a ClientError::InvalidOperationAsBot
if the current user is
a bot user.
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn broadcast_typing(&self) -> Result<()>
Broadcasts that you are typing to a channel for the next 5 seconds.
After 5 seconds, another request must be made to continue broadcasting that you are typing.
This should rarely be used for bots, and should likely only be used for signifying that a long-running command is still being executed.
Requires the Send Messages permission.
Examples
// assuming you are in a context let _ = context.broadcast_typing();
Errors
Returns a ClientError::InvalidOperationAsBot
if the current user is
a bot user.
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn create_permission(&self, target: PermissionOverwrite) -> Result<()>
Creates a permission overwrite for either a
single Member
or Role
within the channel.
Refer to the documentation for GuildChannel::create_permission
for
more information.
Requires the Manage Channels permission.
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn create_reaction<M, R>(&self, message_id: M, reaction_type: R) -> Result<()> where M: Into<MessageId>, R: Into<ReactionType>
React to a Message
with a custom Emoji
or unicode character.
Message::react
may be a more suited method of reacting in most
cases.
Requires the Add Reactions permission, if the current user is the first user to perform a react with a certain emoji.
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn delete_channel(&self) -> Result<Channel>
Deletes the contextual channel.
If the channel being deleted is a GuildChannel
, then the
Manage Channels permission is required.
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn delete_message<M: Into<MessageId>>(&self, message_id: M) -> Result<()>
Deletes a Message
given its Id from the contextual channel.
Refer to Message::delete
for more information.
Examples
Deleting every message that is received:
use serenity::Client; use std::env; let client = Client::login_bot(&env::var("DISCORD_BOT_TOKEN").unwrap()); client.on_message(|ctx, message| { ctx.delete_message(message); });
(in practice, please do not do this)
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn delete_messages(&self, message_ids: &[MessageId]) -> Result<()>
Deletes all messages by Ids from the given vector in the given channel.
The minimum amount of messages is 2 and the maximum amount is 100.
Requires the Manage Messages permission.
Note: This uses bulk delete endpoint which is not available for user accounts.
Note: Messages that are older than 2 weeks can't be deleted using this method.
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
Returns a ClientError::InvalidOperationAsUser
if the current user is
not a bot user.
fn delete_permission(&self,
permission_type: PermissionOverwriteType)
-> Result<()>
permission_type: PermissionOverwriteType)
-> Result<()>
Deletes all permission overrides in the contextual channel from a member or role.
Note: Requires the Manage Channel permission.
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn delete_reaction<M, R>(&self,
message_id: M,
user_id: Option<UserId>,
reaction_type: R)
-> Result<()> where M: Into<MessageId>, R: Into<ReactionType>
message_id: M,
user_id: Option<UserId>,
reaction_type: R)
-> Result<()> where M: Into<MessageId>, R: Into<ReactionType>
Deletes the given Reaction
from the contextual channel.
Note: Requires the Manage Messages permission, if the current user did not perform the reaction.
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn edit_channel<F>(&self, f: F) -> Result<GuildChannel> where F: FnOnce(EditChannel) -> EditChannel
Edits the settings of a Channel
, optionally setting new values.
Refer to EditChannel
's documentation for its methods.
Requires the Manage Channel permission.
Examples
Change a voice channel's name and bitrate:
context.edit_channel(channel_id, |c| c .name("test") .bitrate(64000));
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a guild channel.
fn edit_profile<F: FnOnce(EditProfile) -> EditProfile>(&self,
f: F)
-> Result<CurrentUser>
f: F)
-> Result<CurrentUser>
Edits the current user's profile settings.
Refer to EditProfile
's documentation for its methods.
Examples
Change the current user's username:
context.edit_profile(|p| p.username("Hakase"));
fn edit_message<F, M>(&self, message_id: M, text: &str, f: F) -> Result<Message> where F: FnOnce(CreateEmbed) -> CreateEmbed, M: Into<MessageId>
Edits a Message
given its Id and the Id of the channel it belongs
to.
Refer to Channel::edit_message
for more information.
Note: Requires that the current user be the author of the message.
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn get_channel(&self) -> Result<Channel>
Gets a fresh version of the channel over the REST API.
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn get_channel_invites(&self) -> Result<Vec<RichInvite>>
Gets all of a GuildChannel
's invites.
Requires the Manage Guild permission.
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn get_guilds(&self,
target: GuildPagination,
limit: u8)
-> Result<Vec<GuildInfo>>
target: GuildPagination,
limit: u8)
-> Result<Vec<GuildInfo>>
Gets a paginated list of guilds that the current user is in.
The limit
has a maximum value of 100.
See also: CurrentUser::guilds
.
Examples
Get the first 10 guilds after the current Message
's guild's Id:
use serenity::client::rest::GuildPagination; // assuming you are in a context let guild_id = message.guild_id().unwrap(); context.get_guilds(GuildPagination::After(guild_id, 10)).unwrap();
fn get_message<M: Into<MessageId>>(&self, message_id: M) -> Result<Message>
Gets a single Message
from the contextual channel.
Requires the Read Message History permission.
Errors
Returns a ClientError::InvalidOperationAsUser
if the current user is
not a user account.
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn get_reaction_users<M, R, U>(&self,
message_id: M,
reaction_type: R,
limit: Option<u8>,
after: Option<U>)
-> Result<Vec<User>> where M: Into<MessageId>, R: Into<ReactionType>, U: Into<UserId>
message_id: M,
reaction_type: R,
limit: Option<u8>,
after: Option<U>)
-> Result<Vec<User>> where M: Into<MessageId>, R: Into<ReactionType>, U: Into<UserId>
Gets the list of User
s who have reacted to a Message
with a
certain Emoji
.
The default limit
is 50
- specify otherwise to receive a different
maximum number of users. The maximum that may be retrieve at a time is
100
, if a greater number is provided then it is automatically reduced.
The optional after
attribute is to retrieve the users after a certain
user. This is useful for pagination.
Note: Requires the Read Message History permission.
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn pin<M: Into<MessageId>>(&self, message_id: M) -> Result<()>
Pins a Message
in the specified Channel
by its Id.
Requires the Manage Messages permission.
Errors
Returns a ClientError::NoChannelId
if the current context is not
related to a channel.
fn pins(&self) -> Result<Vec<Message>>
fn say(&self, content: &str) -> Result<Message>
Sends a message with just the given message content in the channel that a message was received from.
Supported Events
This will only work through the context of one of the following event dispatches:
ChannelCreate
ChannelPinsAck
ChannelPinsUpdate
ChannelRecipientAdd
ChannelRecipientRemove
ChannelUpdate
MessageAck
MessageDelete
MessageDeleteBulk
MessageUpdate
ReactionAdd
ReactionRemove
ReactionRemoveAll
Errors
Returns a ClientError::MessageTooLong
if the content of the message
is over the above limit, containing the number of unicode code points
over the limit.
Returns a ClientError::NoChannelId
when there is no ChannelId
directly available; i.e. when not under the context of one of the above
events.
fn queue(&mut self, content: &str) -> &mut Self
Adds a string to message queue, which is sent joined by a newline when context goes out of scope.
Note: Only works in a context where a channel is present. Refer to
say
for a list of events where this is applicable.
fn search_channel<F>(&self, f: F) -> Result<SearchResult> where F: FnOnce(Search) -> Search
Searches a Channel
's messages by providing query parameters via the
search builder.
Refer to the documentation for the Search
builder for restrictions
and defaults parameters, as well as potentially advanced usage.
Note: Bot users can not search.
Examples
Refer to the Search
builder's documentation for examples,
specifically the section on searching a channel.
Errors
If the cache
is enabled, returns a
ClientError::InvalidOperationAsBot
if the current user is a bot.
fn send_file<F, R>(&self, file: R, filename: &str, f: F) -> Result<Message> where F: FnOnce(CreateMessage) -> CreateMessage, R: Read
Sends a file along with optional message contents. The filename must be specified.
Message contents may be passed by using the CreateMessage::content
method.
An embed can not be sent when sending a file. If you set one, it will be automatically removed.
Requires the Attach Files and Send Messages permissions are required.
Note: Message contents must be under 2000 unicode code points.
Errors
If the content of the message is over the above limit, then a
ClientError::MessageTooLong
will be returned, containing the number
of unicode code points over the limit.
fn send_message<F>(&self, f: F) -> Result<Message> where F: FnOnce(CreateMessage) -> CreateMessage
Sends a message to a Channel
.
Refer to the documentation for CreateMessage
for more information
regarding message restrictions and requirements.
Note: Message contents must be under 2000 unicode code points.
Requires the Send Messages permission is required.
Example
Send a message with just the content test
:
// assuming you are in a context let _ = context.send_message(|f| f.content("test"));
Send a message on !ping
with a very descriptive Embed
. This sends
a message content of "Pong! Here's some info"
, with an embed with the
following attributes:
- Dark gold in colour;
- A description of
"Information about the message just posted"
; - A title of
"Message Information"
; - A URL of
"https://rust-lang.org"
; - An author structure containing an icon and the user's name;
- An inline field structure containing the message's content with a label;
- An inline field containing the channel's name with a label;
- A footer containing the current user's icon and name, saying that the information was generated by them.
use serenity::client::{CACHE, Client, Context}; use serenity::model::{Channel, Message}; use serenity::utils::Colour; use std::env; let mut client = Client::login_bot(&env::var("DISCORD_TOKEN").unwrap()); client.with_framework(|f| f .configure(|c| c.prefix("~")) .on("ping", ping)); client.on_ready(|_context, ready| { println!("{} is connected!", ready.user.name); }); let _ = client.start(); command!(ping(context, message) { let cache = CACHE.read().unwrap(); let channel = cache.get_guild_channel(message.channel_id); let _ = context.send_message(|m| m .content("Pong! Here's some info") .embed(|e| e .colour(Colour::dark_gold()) .description("Information about the message just posted") .title("Message information") .url("https://rust-lang.org") .author(|mut a| { a = a.name(&message.author.name); if let Some(avatar) = message.author.avatar_url() { a = a.icon_url(&avatar); } a }) .field(|f| f .inline(true) .name("Message content:") .value(&message.content)) .field(|f| f .inline(true) .name("Channel name:") .value(&channel.map_or_else(|| "Unknown", |c| &c.name))) .footer(|mut f| { f = f.text(&format!("Generated by {}", cache.user.name)); if let Some(avatar) = cache.user.avatar_url() { f = f.icon_url(&avatar); } f }))); Ok(()) });
Note that for most use cases, your embed layout will not be this ugly. This is an example of a very involved and conditional embed.
Errors
Returns a ClientError::MessageTooLong
if the content of the message
is over the above limit, containing the number of unicode code points
over the limit.
fn online(&self)
Sets the current user as being Online
. This maintains the current
game and afk
setting.
fn idle(&self)
Sets the current user as being Idle
. This maintains the current
game and afk
setting.
fn dnd(&self)
Sets the current user as being DoNotDisturb
. This maintains the
current game and afk
setting.
fn invisible(&self)
Sets the current user as being Invisible
. This maintains the current
game and afk
setting.
fn reset_presence(&self)
"Resets" the current user's presence, by setting the game to None
,
the online status to Online
, and afk
to false
.
Use set_presence
for fine-grained control over individual details.
fn set_game(&self, game: Game)
Sets the current game, defaulting to an online status of Online
, and
setting afk
to false
.
Examples
Set the current user as playing "Heroes of the Storm":
use serenity::model::Game; // assuming you are in a context context.set_game(Game::playing("Heroes of the Storm"));
fn set_game_name(&self, game_name: &str)
Sets the current game, passing in only its name. This will automatically
set the current user's OnlineStatus
to Online
, and its
GameType
as Playing
.
Use reset_presence
to clear the current game, or set_presence
for more fine-grained control.
Note: Maximum length is 128.
fn set_presence(&self, game: Option<Game>, status: OnlineStatus, afk: bool)
Sets the current user's presence, providing all fields to be passed.
Examples
Setting the current user as having no game, being Idle
,
and setting afk
to true
:
use serenity::model::OnlineStatus; // assuming you are in a context context.set_game(None, OnlineStatus::Idle, true);
Setting the current user as playing "Heroes of the Storm", being
DoNotDisturb
, and setting afk
to false
:
use serenity::model::{Game, OnlineStatus}; // assuming you are in a context let game = Game::playing("Heroes of the Storm"); let status = OnlineStatus::DoNotDisturb; context.set_game(Some(game), status, false);
fn unpin<M: Into<MessageId>>(&self, message_id: M) -> Result<()>
Unpins a Message
in the contextual channel given by its Id.
Requires the Manage Messages permission.
Trait Implementations
impl Clone for Context
[src]
fn clone(&self) -> Context
Returns a copy of the value. Read more
fn clone_from(&mut self, source: &Self)
1.0.0
Performs copy-assignment from source
. Read more
impl Drop for Context
[src]
fn drop(&mut self)
Combines and sends all queued messages.