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

The Id of the relevant channel, if there is one. This is present on the on_message handler, for example.

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.

The queue of messages that are sent after context goes out of scope.

Methods

impl Context
[src]

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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"));

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.

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.

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.

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();

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.

Gets the list of Users 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.

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.

Gets the list of Messages which are pinned to the specified Channel.

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:

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.

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.

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.

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.

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.

Sets the current user as being Online. This maintains the current game and afk setting.

Sets the current user as being Idle. This maintains the current game and afk setting.

Sets the current user as being DoNotDisturb. This maintains the current game and afk setting.

Sets the current user as being Invisible. This maintains the current game and afk setting.

"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.

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"));

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.

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);

Unpins a Message in the contextual channel given by its Id.

Requires the Manage Messages permission.

Trait Implementations

impl Clone for Context
[src]

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

impl Drop for Context
[src]

Combines and sends all queued messages.