Struct serenity::client::Client [] [src]

pub struct Client {
    pub data: Arc<Mutex<ShareMap>>,
    // some fields omitted
}

The Client is the way to be able to start sending authenticated requests over the REST API, as well as initializing a WebSocket connection through Shards. Refer to the documentation on using sharding for more information.

Event Handlers

Event handlers can be configured. For example, the event handler on_message will be dispatched to whenever a Event::MessageCreate is received over the connection.

Note that you do not need to manually handle events, as they are handled internally and then dispatched to your event handlers.

Examples

Creating a Client instance and adding a handler on every message receive, acting as a "ping-pong" bot is simple:

use serenity::Client;

let mut client = Client::new("my token here");

client.on_message(|context, message| {
    if message.content == "!ping" {
        message.channel_id.say("Pong!");
    }
});

client.start();

Fields

A ShareMap which requires types to be Send + Sync. This is a map that can be safely shared across contexts.

The purpose of the data field is to be accessible and persistent across contexts; that is, data can be modified by one context, and will persist through the future and be accessible through other contexts. This is useful for anything that should "live" through the program: counters, database connections, custom user caches, etc.

In the meaning of a context, this data can be accessed through Context::data.

Examples

Create a MessageEventCounter to track the following events:

extern crate serenity;
extern crate typemap;

use serenity::Client;
use std::collections::HashMap;
use std::env;
use typemap::Key;

struct MessageEventCounter;

impl Key for MessageEventCounter {
    type Value = HashMap<String, u64>;
}

let mut client = Client::new(&env::var("DISCORD_TOKEN").unwrap());

{
    let mut data = client.data.lock().unwrap();
    data.insert::<MessageEventCounter>(HashMap::default());
}

macro_rules! reg {
    ($ctx:ident $name:expr) => {
        {
            let mut data = $ctx.data.lock().unwrap();
            let counter = data.get_mut::<MessageEventCounter>().unwrap();
            let entry = counter.entry($name).or_insert(0);
            *entry += 1;
        }
    };
}

client.on_message(|ctx, _| reg!(ctx "MessageCreate"));
client.on_message_delete(|ctx, _| reg!(ctx "MessageDelete"));
client.on_message_delete_bulk(|ctx, _| reg!(ctx "MessageDeleteBulk"));
client.on_message_update(|ctx, _| reg!(ctx "MessageUpdate"));

Refer to example 05 for an example on using the data field.

Methods

impl Client
[src]

Creates a Client for a bot user.

Discord has a requirement of prefixing bot tokens with "Bot ", which this function will automatically do for you if not already included.

Examples

Create a Client, using a token from an environment variable:

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

let token = env::var("DISCORD_TOKEN")?;
let client = Client::new(&token);

Deprecated since 0.1.5

: Use new instead

Alias of new.

Deprecated since 0.2.1

: Use new instead

Alias for new.

Sets a framework to be used with the client. All message events will be passed through the framework after being passed to the on_message event handler.

See the framework module-level documentation for more information on usage.

Examples

Create a simple framework that responds to a ~ping command:

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

let mut client = Client::new(&env::var("DISCORD_TOKEN")?);
client.with_framework(|f| f
    .configure(|c| c.prefix("~"))
    .command("ping", |c| c.exec_str("Pong!")));

Refer to the documentation for the framework module for more in-depth information.

Establish the connection and start listening for events.

This will start receiving events in a loop and start dispatching the events to your registered handlers.

Note that this should be used only for users and for bots which are in less than 2500 guilds. If you have a reason for sharding and/or are in more than 2500 guilds, use one of these depending on your use case:

Refer to the Gateway documentation for more information on effectively using sharding.

Examples

Starting a Client with only 1 shard, out of 1 total:

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

let mut client = Client::new(&env::var("DISCORD_TOKEN")?);

if let Err(why) = client.start() {
    println!("Err with client: {:?}", why);
}

Establish the connection(s) and start listening for events.

This will start receiving events in a loop and start dispatching the events to your registered handlers.

This will retrieve an automatically determined number of shards to use from the API - determined by Discord - and then open a number of shards equivalent to that amount.

Refer to the Gateway documentation for more information on effectively using sharding.

Examples

Start as many shards as needed using autosharding:

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

let mut client = Client::new(&env::var("DISCORD_TOKEN")?);

if let Err(why) = client.start_autosharded() {
    println!("Err with client: {:?}", why);
}

Errors

Returns a ClientError::Shutdown when all shards have shutdown due to an error.

Establish a sharded connection and start listening for events.

This will start receiving events and dispatch them to your registered handlers.

This will create a single shard by ID. If using one shard per process, you will need to start other processes with the other shard IDs in some way.

Refer to the Gateway documentation for more information on effectively using sharding.

Examples

Start shard 3 of 5:

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

let mut client = Client::new(&env::var("DISCORD_TOKEN")?);

if let Err(why) = client.start_shard(3, 5) {
    println!("Err with client: {:?}", why);
}

Start shard 0 of 1 (you may also be interested in start or start_autosharded):

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

let mut client = Client::new(&env::var("DISCORD_TOKEN")?);

if let Err(why) = client.start_shard(0, 1) {
    println!("Err with client: {:?}", why);
}

Errors

Returns a ClientError::Shutdown when all shards have shutdown due to an error.

Establish sharded connections and start listening for events.

This will start receiving events and dispatch them to your registered handlers.

This will create and handle all shards within this single process. If you only need to start a single shard within the process, or a range of shards, use start_shard or start_shard_range, respectively.

Refer to the Gateway documentation for more information on effectively using sharding.

Examples

Start all of 8 shards:

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

let mut client = Client::new(&env::var("DISCORD_TOKEN")?);

if let Err(why) = client.start_shards(8) {
    println!("Err with client: {:?}", why);
}

Errors

Returns a ClientError::Shutdown when all shards have shutdown due to an error.

Establish a range of sharded connections and start listening for events.

This will start receiving events and dispatch them to your registered handlers.

This will create and handle all shards within a given range within this single process. If you only need to start a single shard within the process, or all shards within the process, use start_shard or start_shards, respectively.

Refer to the Gateway documentation for more information on effectively using sharding.

Examples

For a bot using a total of 10 shards, initialize shards 4 through 7:

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

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

let _ = client.start_shard_range([4, 7], 10);
use serenity::Client;
use std::env;

let mut client = Client::new(&env::var("DISCORD_TOKEN")?);

if let Err(why) = client.start_shard_range([4, 7], 10) {
    println!("Err with client: {:?}", why);
}

Errors

Returns a ClientError::Shutdown when all shards have shutdown due to an error.

Attaches a handler for when a ChannelCreate is received.

Examples

If the channel is a guild channel, send "first" to the channel when one is created:

use serenity::model::Channel;

client.on_channel_create(|ctx, channel| {
    if let Channel::Guild(ch) = channel {
        if let Err(why) = ch.read().unwrap().say("first") {
            println!("Err sending first message: {:?}", why);
        }
    }
});

Attaches a handler for when a ChannelDelete is received.

Examples

If the channel is a guild channel, send the name of the channel to the guild's default channel.

use serenity::model::{Channel, ChannelId};

client.on_channel_delete(|ctx, channel| {
    if let Channel::Guild(channel) = channel {
        let (content, default_channel_id) = {
            let reader = channel.read().unwrap();
            let content = format!("A channel named '{}' was deleted.", reader.name);
            let id = ChannelId(reader.guild_id.0);

            (content, id)
        };

        if let Err(why) = default_channel_id.say(&content) {
            println!("Err sending message to default channel: {:?}", why);
        }
    }
});

Attaches a handler for when a ChannelPinsUpdate is received.

Attaches a handler for when a GuildCreate is received.

Attaches a handler for when a GuildEmojisUpdate is received.

The HashMap of emojis is the new full list of emojis.

Attaches a handler for when a GuildIntegrationsUpdate is received.

Attaches a handler for when a GuildMemberAdd is received.

Attaches a handler for when a GuildMembersChunk is received.

Attaches a handler for when a GuildRoleCreate is received.

Attaches a handler for when a GuildUnavailable is received.

Attaches a handler for when a GuildBan is received.

Attaches a handler for when a GuildUnban is received.

Attaches a handler for when a MessageCreate is received.

Examples

Print the contents of every received message:

use serenity::Client;

let mut client = Client::new("bot token here");

client.on_message(|_context, message| {
    println!("{}", message.content);
});

let _ = client.start();

Attaches a handler for when a MessageDelete is received.

Attaches a handler for when a MessageDeleteBulk is received.

Attaches a handler for when a MessageUpdate is received.

Attaches a handler for when a PresencesReplace is received.

Attaches a handler for when a PresenceUpdate is received.

Attached a handler for when a ReactionAdd is received.

Attached a handler for when a ReactionRemove is received.

Attached a handler for when a ReactionRemoveAll is received.

Register an event to be called whenever a Ready event is received.

Registering a handler for the ready event is good for noting when your bot has established a connection to the gateway through a Shard.

Note: The Ready event is not guarenteed to be the first event you will receive by Discord. Do not actively rely on it.

Examples

Print the current user's name on ready:

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

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

client.on_ready(|_context, ready| {
    println!("{} is connected", ready.user.name);
});

Attaches a handler for when a ChannelRecipientAdd is received.

Attaches a handler for when a ChannelRecipientRemove is received.

Attaches a handler for when a Resumed is received.

Attaches a handler for when a TypingStart is received.

Attaches a handler for when an Unknown is received.

Attaches a handler for when a VoiceServerUpdate is received.

Attaches a handler for when a VoiceStateUpdate is received.

Attaches a handler for when a WebhookUpdate is received.

impl Client
[src]

Attaches a handler for when a ChannelUpdate is received.

Optionally provides the version of the channel before the update.

Attaches a handler for when a GuildDelete is received.

Returns a partial guild as well as - optionally - the full guild, with data like Roles. This can be None in the event that it was not in the Cache.

Note: The relevant guild is removed from the Cache when this event is received. If you need to keep it, you can either re-insert it yourself back into the Cache or manage it in another way.

Attaches a handler for when a GuildMemberRemove is received.

Returns the user's associated Member object, if it existed in the cache.

Attaches a handler for when a GuildMemberUpdate is received.

Attaches a handler for when a GuildRoleDelete is received.

Attaches a handler for when a GuildRoleUpdate is received.

The optional Role is the role prior to updating. This can be None if it did not exist in the Cache before the update.

Attaches a handler for when a GuildUpdate is received.

Attaches a handler for when a UserUpdate is received.

The old current user will be provided as well.