Struct serenity::client::Context [] [src]

pub struct Context {
    pub channel_id: Option<ChannelId>,
    pub shard: Arc<Mutex<Shard>>,
    // 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.

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.

Methods

impl Context
[src]

Accepts the given invite.

Refer to the documentation for rest::accept_invite for restrictions on accepting an invite.

Note: Requires that the current user be a user account.

Errors

Returns a ClientError::InvalidOperationAsBot if the current user is a bot user.

Marks a 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.

Bans a User from a Guild, removing their messages sent in the last X number of days.

Refer to the documentation for rest::ban_user for more information.

Note: Requires that you have the Ban Members permission.

Examples

Ban the user that sent a message for 7 days:

// assuming you are in a context
context.ban_user(context.guild_id, context.message.author, 7);

Errors

Returns a ClientError::DeleteMessageDaysAmount if the number of days given is over the maximum allowed.

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.

Examples

// assuming you are in a context
context.broadcast_typing(context.channel_id);

Creates a GuildChannel in the given Guild.

Refer to rest::create_channel for more information.

Note: Requires the Manage Channels permission.

Examples

Create a voice channel in a guild with the name test:

use serenity::model::ChannelType;

context.create_channel(context.guild_id, "test", ChannelType::Voice);

Creates an emoji in the given guild with a name and base64-encoded image. The utils::read_image function is provided for you as a simple method to read an image and encode it into base64, if you are reading from the filesystem.

Note: Requires the Manage Emojis permission.

Examples

See the EditProfile::avatar example for an in-depth example as to how to read an image from the filesystem and encode it as base64. Most of the example can be applied similarly for this method.

Creates a guild with the data provided.

Only a PartialGuild will be immediately returned, and a full Guild will be received over a Shard.

Note: This endpoint is usually only available for user accounts. Refer to Discord's information for the endpoint here for more information. If you require this as a bot, re-think what you are doing and if it really needs to be doing this.

Examples

Create a guild called "test" in the US West region with no icon:

use serenity::model::Region;

context.create_guild("test", Region::UsWest, None);

Creates an Integration for a Guild.

Note: Requires the Manage Guild permission.

Creates an invite for the channel, providing a builder so that fields may optionally be set.

See the documentation for the CreateInvite builder for information on how to use this and the default values that it provides.

Note: Requires the Create Invite permission.

Creates a permission overwrite for either a single Member or Role within a Channel.

Refer to the documentation for PermissionOverwrites for more information.

Note: Requires the Manage Channels permission.

Examples

Creating a permission overwrite for a member by specifying the PermissionOverwrite::Member variant, allowing it the [Send Messages] permission, but denying the Send TTS Messages and Attach Files permissions:

use serenity::model::{ChannelId, PermissionOverwrite, permissions};

// assuming you are in a context

let channel_id = 7;
let user_id = 8;

let allow = permissions::SEND_MESSAGES;
let deny = permissions::SEND_TTS_MESSAGES | permissions::ATTACH_FILES;
let overwrite = PermissionOverwrite {
    allow: allow,
    deny: deny,
    kind: PermissionOverwriteType::Member(user_id),
};

let _result = context.create_permission(channel_id, overwrite);

Creating a permission overwrite for a role by specifying the [PermissionOverwrite::Role] variant, allowing it the Manage Webhooks permission, but denying the Send TTS Messages and Attach Files permissions:

use serenity::model::{ChannelId, PermissionOverwrite, permissions};

// assuming you are in a context

let channel_id = 7;
let user_id = 8;

let allow = permissions::SEND_MESSAGES;
let deny = permissions::SEND_TTS_MESSAGES | permissions::ATTACH_FILES;
let overwrite = PermissionOverwrite {
    allow: allow,
    deny: deny,
    kind: PermissionOverwriteType::Member(user_id),
};

let _result = context.create_permission(channel_id, overwrite);

Creates a direct message channel between the current user and another User. This can also retrieve the channel if one already exists.

React to a Message with a custom Emoji or unicode character.

Message::react may be a more suited method of reacting in most cases.

Note: Requires the Add Reactions permission, if the current user is the first user to perform a react with a certain emoji.

Creates a Role in guild with given Id. Second argument is a closure, and you can use it to automatically configure role.

Examples

This creates a role which can be mentioned, with name 'test':

let role = context.create_role(guild_id, |r| r
    .hoist(true)
    .name("role"));

Deletes a Channel based on the Id given.

If the channel being deleted is a GuildChannel, then the Manage Channels permission is required.

Deletes an emoji in a Guild given its Id.

Note: Requires the Manage Emojis permission.

Deletes a Guild. The current user must be the guild owner to be able to delete it.

Only a PartialGuild will be immediately returned.

Deletes an integration by Id from a guild which Id was given.

Deletes the given invite.

Refer to the documentation for Invite::delete for restrictions on deleting an invite.

Errors

Returns a ClientError::InvalidPermissions if the current user does not have the required [permission].

Deletes a Message given its Id.

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(|context, message| {
    context.delete_message(message);
});

(in practice, please do not do this)

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.

Note: This uses bulk delete endpoint which is not available for user accounts.

Deletes a profile note from a user.

Deletes all permission overrides in a channel from a member or a role.

Deletes the given Reaction.

Note: Requires the Manage Messages permission, if the current user did not perform the reaction.

Deletes a role by Id from the given guild.

Sends a message to a user through a direct message channel. This is a channel that can only be accessed by you and the recipient.

Examples

There are three ways to send a direct message to someone, the first being an unrelated, although equally helpful method.

Sending a message via User::dm:

// assuming you are in a context
let _ = context.message.author.dm("Hello!");

Sending a message to a PrivateChannel:

assuming you are in a context
let private_channel = context.create_private_channel(context.message.author.id);

let _ = context.direct_message(private_channel, "Test!");

Sending a message to a PrivateChannel given its ID:

use serenity::Client;
use std::env;

let mut client = Client::login_bot(&env::var("DISCORD_BOT_TOKEN").unwrap());

client.on_message(|context, message| {
    if message.content == "!pm-me" {
        let channel = context.create_private_channel(message.author.id)
            .unwrap();

        let _ = channel.send_message("test!");
    }
});

Edits the settings of a Channel, optionally setting new values.

Refer to EditChannel's documentation for its methods.

Examples

Change a voice channel's name and bitrate:

context.edit_channel(channel_id, |c| c
    .name("test")
    .bitrate(64000));

Edits an Emoji's name.

Edits the settings of a Guild, optionally setting new values.

Refer to EditGuild's documentation for a full list of methods.

Examples

Change a guild's icon using a file name "icon.png":

use serenity::utils;

// We are using read_image helper function from utils.
let base64_icon = utils::read_image("./icon.png")
    .expect("Failed to read image");

context.edit_guild(guild_id, |g|
    g.icon(base64_icon));

Edits the properties of member of a guild, such as muting or nicknaming them.

Refer to EditMember's documentation for a full list of methods.

Examples

Mute a member and set their roles to just one role with a predefined Id:

context.edit_member(guild_id, user_id, |m| m
    .mute(true)
    .roles(&vec![role_id]));

Edits the current user's nickname for the provided Guild via its Id.

Pass None to reset the nickname.

Note: Requires the Change Nickname permission.

Edits the current user's settings.

Refer to EditProfile's documentation for its methods.

Examples

Change our username:

context.edit_member(|p|
    p.username("meew zero"));

Edits a Role, optionally setting its new fields.

Examples

Make a role hoisted:

context.edit_role(guild_id, role_id, |r| r
    .hoist(true));

Edits a Message given its Id and the Id of the channel it belongs to.

Pass an empty string ("") to text if you are editing a message with an embed or file but no content. Otherwise, text must be given.

Edits the note that the current user has set for another user.

Use delete_note to remove a note.

Note: Requires that the current user be a user account.

Examples

Set a note for a message's author:

// assuming a `message` has been bound
let _ = context.edit_note(message.author, "test note");

Errors

Returns a ClientError::InvalidOperationAsBot if the current user is a bot user.

Gets a list of the given Guild's bans.

Requires the Ban Members permission.

Gets all of a GuildChannel's invites.

Requires the Manage Guild permission.

Gets a Channel by the given Id.

Gets all channels of a guild with given Id.

Gets an guild's emoji by Id.

Gets a list of all emojis a guild has.

Gets a guild by its Id.

Requires that the current user be in the guild.

Gets all of a guild's invites.

Requires the Manage Guild permission.

Gets the number of Members that would be pruned with the given number of days.

Gets all guilds that the current user is in.

Gets all integrations of a guild via the given Id.

Gets the information about an invite.

Gets a user's Member object for a Guild, given by Id.

Gets a list of a Guild's members.

Optionally pass in the limit to limit the number of results. Maximum value is 1000. Optionally pass in after to offset the results by a User's Id.

Gets a single Message from a Channel.

Requires the Read Message History permission.

Errors

Returns a ClientError::InvalidOperationAsUser if the current user is not a user account.

Gets messages from a specific channel.

Examples

let role = context.get_messages(channel_id, |g| g
    .before(20)
    .after(100)); // Maximum is 100.

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::InvalidPermissions if the current user does not have the required [permissions].

Kicks a Member from the specified Guild if they are in it.

Requires the Kick Members permission.

Leaves a guild by its Id.

Moves a member to a specific voice channel.

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

Pins a message in the specified channel by the given Id.

Sends a message with just the given message content in the channel that a message was received from.

Note: This will only work when a Message is received.

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.

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.

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.

Example

Send a message with just the content test:

// assuming you are in a context
let _ = context.send_message(message.channel_id, |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();

fn ping(context: &Context, message: &Message, _arguments: Vec<String>) {
    let cache = CACHE.read().unwrap();
    let channel = cache.get_guild_channel(message.channel_id);

    let _ = context.send_message(message.channel_id, |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
            })));
}

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.

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

Deletes an undefined amount of members from the given guild based on the amount of days they've been offline for.

Note: This will trigger GuildMemberRemove events

Starts integration synchronization by the given integration Id.

Unbans a User from a Guild.

Requires the Ban Members permission.

Unpins a Message in the specified Channel given each Id.

Trait Implementations

impl Clone for Context
[src]

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more