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
Shard
s. 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
data: Arc<Mutex<ShareMap>>
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]
fn new(token: &str) -> Self
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);
fn login_bot(token: &str) -> Self
: Use new
instead
Alias of new
.
fn login(token: &str) -> Self
: Use new
instead
Alias for new
.
fn with_framework<F>(&mut self, f: F) where
F: FnOnce(Framework) -> Framework + Send + Sync + 'static,
F: FnOnce(Framework) -> Framework + Send + Sync + 'static,
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.
fn start(&mut self) -> Result<()>
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); }
fn start_autosharded(&mut self) -> Result<()>
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.
fn start_shard(&mut self, shard: u64, shards: u64) -> Result<()>
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.
fn start_shards(&mut self, total_shards: u64) -> Result<()>
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.
fn start_shard_range(
&mut self,
range: [u64; 2],
total_shards: u64
) -> Result<()>
&mut self,
range: [u64; 2],
total_shards: u64
) -> Result<()>
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.
fn on_channel_create<F>(&mut self, handler: F) where
F: Fn(Context, Channel) + Send + Sync + 'static,
F: Fn(Context, Channel) + Send + Sync + 'static,
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); } } });
fn on_channel_delete<F>(&mut self, handler: F) where
F: Fn(Context, Channel) + Send + Sync + 'static,
F: Fn(Context, Channel) + Send + Sync + 'static,
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); } } });
fn on_channel_pins_update<F>(&mut self, handler: F) where
F: Fn(Context, ChannelPinsUpdateEvent) + Send + Sync + 'static,
F: Fn(Context, ChannelPinsUpdateEvent) + Send + Sync + 'static,
Attaches a handler for when a ChannelPinsUpdate
is received.
fn on_guild_create<F>(&mut self, handler: F) where
F: Fn(Context, Guild) + Send + Sync + 'static,
F: Fn(Context, Guild) + Send + Sync + 'static,
Attaches a handler for when a GuildCreate
is received.
fn on_guild_emojis_update<F>(&mut self, handler: F) where
F: Fn(Context, GuildId, HashMap<EmojiId, Emoji>) + Send + Sync + 'static,
F: Fn(Context, GuildId, HashMap<EmojiId, Emoji>) + Send + Sync + 'static,
Attaches a handler for when a GuildEmojisUpdate
is received.
The HashMap
of emojis is the new full list of emojis.
fn on_guild_integrations_update<F>(&mut self, handler: F) where
F: Fn(Context, GuildId) + Send + Sync + 'static,
F: Fn(Context, GuildId) + Send + Sync + 'static,
Attaches a handler for when a GuildIntegrationsUpdate
is received.
fn on_guild_member_add<F>(&mut self, handler: F) where
F: Fn(Context, GuildId, Member) + Send + Sync + 'static,
F: Fn(Context, GuildId, Member) + Send + Sync + 'static,
Attaches a handler for when a GuildMemberAdd
is received.
fn on_guild_members_chunk<F>(&mut self, handler: F) where
F: Fn(Context, GuildId, HashMap<UserId, Member>) + Send + Sync + 'static,
F: Fn(Context, GuildId, HashMap<UserId, Member>) + Send + Sync + 'static,
Attaches a handler for when a GuildMembersChunk
is received.
fn on_guild_role_create<F>(&mut self, handler: F) where
F: Fn(Context, GuildId, Role) + Send + Sync + 'static,
F: Fn(Context, GuildId, Role) + Send + Sync + 'static,
Attaches a handler for when a GuildRoleCreate
is received.
Attaches a handler for when a GuildUnavailable
is received.
fn on_member_ban<F>(&mut self, handler: F) where
F: Fn(Context, GuildId, User) + Send + Sync + 'static,
F: Fn(Context, GuildId, User) + Send + Sync + 'static,
Attaches a handler for when a GuildBan
is received.
fn on_member_unban<F>(&mut self, handler: F) where
F: Fn(Context, GuildId, User) + Send + Sync + 'static,
F: Fn(Context, GuildId, User) + Send + Sync + 'static,
Attaches a handler for when a GuildUnban
is received.
fn on_message<F>(&mut self, handler: F) where
F: Fn(Context, Message) + Send + Sync + 'static,
F: Fn(Context, Message) + Send + Sync + 'static,
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();
fn on_message_delete<F>(&mut self, handler: F) where
F: Fn(Context, ChannelId, MessageId) + Send + Sync + 'static,
F: Fn(Context, ChannelId, MessageId) + Send + Sync + 'static,
Attaches a handler for when a MessageDelete
is received.
fn on_message_delete_bulk<F>(&mut self, handler: F) where
F: Fn(Context, ChannelId, Vec<MessageId>) + Send + Sync + 'static,
F: Fn(Context, ChannelId, Vec<MessageId>) + Send + Sync + 'static,
Attaches a handler for when a MessageDeleteBulk
is received.
fn on_message_update<F>(&mut self, handler: F) where
F: Fn(Context, MessageUpdateEvent) + Send + Sync + 'static,
F: Fn(Context, MessageUpdateEvent) + Send + Sync + 'static,
Attaches a handler for when a MessageUpdate
is received.
fn on_presence_replace<F>(&mut self, handler: F) where
F: Fn(Context, Vec<Presence>) + Send + Sync + 'static,
F: Fn(Context, Vec<Presence>) + Send + Sync + 'static,
Attaches a handler for when a PresencesReplace
is received.
fn on_presence_update<F>(&mut self, handler: F) where
F: Fn(Context, PresenceUpdateEvent) + Send + Sync + 'static,
F: Fn(Context, PresenceUpdateEvent) + Send + Sync + 'static,
Attaches a handler for when a PresenceUpdate
is received.
fn on_reaction_add<F>(&mut self, handler: F) where
F: Fn(Context, Reaction) + Send + Sync + 'static,
F: Fn(Context, Reaction) + Send + Sync + 'static,
Attached a handler for when a ReactionAdd
is received.
fn on_reaction_remove<F>(&mut self, handler: F) where
F: Fn(Context, Reaction) + Send + Sync + 'static,
F: Fn(Context, Reaction) + Send + Sync + 'static,
Attached a handler for when a ReactionRemove
is received.
fn on_reaction_remove_all<F>(&mut self, handler: F) where
F: Fn(Context, ChannelId, MessageId) + Send + Sync + 'static,
F: Fn(Context, ChannelId, MessageId) + Send + Sync + 'static,
Attached a handler for when a ReactionRemoveAll
is received.
fn on_ready<F>(&mut self, handler: F) where
F: Fn(Context, Ready) + Send + Sync + 'static,
F: Fn(Context, Ready) + Send + Sync + 'static,
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); });
fn on_recipient_add<F>(&mut self, handler: F) where
F: Fn(Context, ChannelId, User) + Send + Sync + 'static,
F: Fn(Context, ChannelId, User) + Send + Sync + 'static,
Attaches a handler for when a ChannelRecipientAdd
is received.
fn on_recipient_remove<F>(&mut self, handler: F) where
F: Fn(Context, ChannelId, User) + Send + Sync + 'static,
F: Fn(Context, ChannelId, User) + Send + Sync + 'static,
Attaches a handler for when a ChannelRecipientRemove
is received.
fn on_resume<F>(&mut self, handler: F) where
F: Fn(Context, ResumedEvent) + Send + Sync + 'static,
F: Fn(Context, ResumedEvent) + Send + Sync + 'static,
Attaches a handler for when a Resumed
is received.
fn on_typing_start<F>(&mut self, handler: F) where
F: Fn(Context, TypingStartEvent) + Send + Sync + 'static,
F: Fn(Context, TypingStartEvent) + Send + Sync + 'static,
Attaches a handler for when a TypingStart
is received.
fn on_unknown<F>(&mut self, handler: F) where
F: Fn(Context, String, Value) + Send + Sync + 'static,
F: Fn(Context, String, Value) + Send + Sync + 'static,
Attaches a handler for when an Unknown
is received.
fn on_voice_server_update<F>(&mut self, handler: F) where
F: Fn(Context, VoiceServerUpdateEvent) + Send + Sync + 'static,
F: Fn(Context, VoiceServerUpdateEvent) + Send + Sync + 'static,
Attaches a handler for when a VoiceServerUpdate
is received.
fn on_voice_state_update<F>(&mut self, handler: F) where
F: Fn(Context, Option<GuildId>, VoiceState) + Send + Sync + 'static,
F: Fn(Context, Option<GuildId>, VoiceState) + Send + Sync + 'static,
Attaches a handler for when a VoiceStateUpdate
is received.
fn on_webhook_update<F>(&mut self, handler: F) where
F: Fn(Context, GuildId, ChannelId) + Send + Sync + 'static,
F: Fn(Context, GuildId, ChannelId) + Send + Sync + 'static,
Attaches a handler for when a WebhookUpdate
is received.
impl Client
[src]
fn on_channel_update<F>(&mut self, handler: F) where
F: Fn(Context, Option<Channel>, Channel) + Send + Sync + 'static,
F: Fn(Context, Option<Channel>, Channel) + Send + Sync + 'static,
Attaches a handler for when a ChannelUpdate
is received.
Optionally provides the version of the channel before the update.
fn on_guild_delete<F>(&mut self, handler: F) where
F: Fn(Context, PartialGuild, Option<Arc<RwLock<Guild>>>) + Send + Sync + 'static,
F: Fn(Context, PartialGuild, Option<Arc<RwLock<Guild>>>) + Send + Sync + 'static,
Attaches a handler for when a GuildDelete
is received.
Returns a partial guild as well as - optionally - the full guild, with
data like Role
s. 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.
fn on_guild_member_remove<F>(&mut self, handler: F) where
F: Fn(Context, GuildId, User, Option<Member>) + Send + Sync + 'static,
F: Fn(Context, GuildId, User, Option<Member>) + Send + Sync + 'static,
Attaches a handler for when a GuildMemberRemove
is received.
Returns the user's associated Member
object, if it existed in the
cache.
fn on_guild_member_update<F>(&mut self, handler: F) where
F: Fn(Context, Option<Member>, Member) + Send + Sync + 'static,
F: Fn(Context, Option<Member>, Member) + Send + Sync + 'static,
Attaches a handler for when a GuildMemberUpdate
is received.
fn on_guild_role_delete<F>(&mut self, handler: F) where
F: Fn(Context, GuildId, RoleId, Option<Role>) + Send + Sync + 'static,
F: Fn(Context, GuildId, RoleId, Option<Role>) + Send + Sync + 'static,
Attaches a handler for when a GuildRoleDelete
is received.
fn on_guild_role_update<F>(&mut self, handler: F) where
F: Fn(Context, GuildId, Option<Role>, Role) + Send + Sync + 'static,
F: Fn(Context, GuildId, Option<Role>, Role) + Send + Sync + 'static,
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.
fn on_guild_update<F>(&mut self, handler: F) where
F: Fn(Context, Option<Arc<RwLock<Guild>>>, PartialGuild) + Send + Sync + 'static,
F: Fn(Context, Option<Arc<RwLock<Guild>>>, PartialGuild) + Send + Sync + 'static,
Attaches a handler for when a GuildUpdate
is received.
fn on_user_update<F>(&mut self, handler: F) where
F: Fn(Context, CurrentUser, CurrentUser) + Send + Sync + 'static,
F: Fn(Context, CurrentUser, CurrentUser) + Send + Sync + 'static,
Attaches a handler for when a UserUpdate
is received.
The old current user will be provided as well.