Struct twilight_gateway::shard::Shard
source · pub struct Shard { /* private fields */ }
Expand description
Shard to run and manage a session with the gateway.
Shards are responsible for handling incoming events, process events relevant to the operation of shards - such as requests from the gateway to re-connect or invalidate a session - and then pass the events on to the user via an event stream.
Shards will go through a queue to initialize new ratelimited sessions with the ratelimit. Refer to Discord’s documentation on shards to have a better understanding of what they are.
Using a shard in multiple tasks
To use a shard instance in multiple tasks, consider wrapping it in an
std::sync::Arc
or std::rc::Rc
.
Examples
Create and start a shard and print new and deleted messages:
use futures::stream::StreamExt;
use std::env;
use twilight_gateway::{Event, EventTypeFlags, Intents, Shard};
// Use the value of the "DISCORD_TOKEN" environment variable as the bot's
// token. Of course, you may pass this into your program however you want.
let token = env::var("DISCORD_TOKEN")?;
let event_types = EventTypeFlags::MESSAGE_CREATE | EventTypeFlags::MESSAGE_DELETE;
let (shard, mut events) = Shard::builder(token, Intents::GUILD_MESSAGES)
.event_types(event_types)
.build();
// Start the shard.
shard.start().await?;
// Create a loop of only new message and deleted message events.
while let Some(event) = events.next().await {
match event {
Event::MessageCreate(message) => {
println!("message received with content: {}", message.content);
}
Event::MessageDelete(message) => {
println!("message with ID {} deleted", message.id);
}
_ => {}
}
}
Implementations§
source§impl Shard
impl Shard
sourcepub fn new(token: String, intents: Intents) -> (Self, Events)
pub fn new(token: String, intents: Intents) -> (Self, Events)
Create a new unconfigured shard.
Use start
to initiate the gateway session.
Examples
Create a new shard and start it, wait a second, and then print its current connection stage:
use std::{env, time::Duration};
use tokio::time as tokio_time;
use twilight_gateway::{Intents, Shard};
let token = env::var("DISCORD_TOKEN")?;
let intents = Intents::GUILD_MESSAGES | Intents::GUILD_MESSAGE_TYPING;
let (shard, _) = Shard::new(token, intents);
shard.start().await?;
tokio_time::sleep(Duration::from_secs(1)).await;
let info = shard.info()?;
println!("Shard stage: {}", info.stage());
sourcepub fn builder(token: String, intents: Intents) -> ShardBuilder
pub fn builder(token: String, intents: Intents) -> ShardBuilder
Create a builder to configure and construct a shard.
Refer to the builder for more information.
sourcepub fn config(&self) -> &Config
pub fn config(&self) -> &Config
Return an immutable reference to the configuration used for this client.
sourcepub async fn start(&self) -> Result<(), ShardStartError>
pub async fn start(&self) -> Result<(), ShardStartError>
Start the shard, connecting it to the gateway and starting the process of receiving and processing events.
The same shard can’t be started multiple times. If you stop a shard via
shutdown
or shutdown_resumable
you need to create a new instance
of the shard.
Errors
Returns a ShardStartErrorType::AlreadyStarted
error type if the
shard has already been started.
Returns a ShardStartErrorType::Establishing
error type if
establishing a connection to the gateway failed.
Returns a ShardStartErrorType::ParsingGatewayUrl
error type if the
gateway URL couldn’t be parsed.
sourcepub fn info(&self) -> Result<Information, SessionInactiveError>
pub fn info(&self) -> Result<Information, SessionInactiveError>
Retrieve information about the running of the shard, such as the current connection stage.
Errors
Returns a SessionInactiveError
if the shard’s session is inactive.
sourcepub async fn command(&self, value: &impl Command) -> Result<(), CommandError>
pub async fn command(&self, value: &impl Command) -> Result<(), CommandError>
Send a command over the gateway.
Examples
Updating the shard’s presence after identifying can be done by sending
an UpdatePresence
command. For example, updating the active presence
with the custom status “running on twilight”:
use std::env;
use twilight_gateway::{shard::Shard, Intents};
use twilight_model::gateway::{
payload::outgoing::UpdatePresence,
presence::{Activity, ActivityType, MinimalActivity, Status},
};
let intents = Intents::GUILDS;
let token = env::var("DISCORD_TOKEN")?;
let (shard, _events) = Shard::new(token, intents);
shard.start().await?;
let minimal_activity = MinimalActivity {
kind: ActivityType::Custom,
name: "running on twilight".to_owned(),
url: None,
};
let command = UpdatePresence::new(
Vec::from([Activity::from(minimal_activity)]),
false,
Some(1),
Status::Online,
)?;
shard.command(&command).await?;
Errors
Returns a CommandErrorType::Sending
error type if the message could
not be sent over the websocket. This indicates the shard is currently
restarting.
Returns a CommandErrorType::Serializing
error type if the provided
value failed to serialize into JSON.
Returns a CommandErrorType::SessionInactive
error type if the shard
has not been started.
sourcepub async fn send(&self, message: Message) -> Result<(), SendError>
pub async fn send(&self, message: Message) -> Result<(), SendError>
Send a raw websocket message.
Examples
Send a ping message:
use std::env;
use twilight_gateway::{
shard::{raw_message::Message, Shard},
Intents,
};
let token = env::var("DISCORD_TOKEN")?;
let (shard, _) = Shard::new(token, Intents::GUILDS);
shard.start().await?;
shard.send(Message::Ping(Vec::new())).await?;
Send a normal close (you may prefer to use shutdown
):
use std::{borrow::Cow, env};
use twilight_gateway::{
shard::{
raw_message::{CloseFrame, Message},
Shard,
},
Intents,
};
let token = env::var("DISCORD_TOKEN")?;
let (shard, _) = Shard::new(token, Intents::GUILDS);
shard.start().await?;
let close = CloseFrame::from((1000, ""));
let message = Message::Close(Some(close));
shard.send(message).await?;
Errors
Returns a SendErrorType::HeartbeaterNotStarted
error type if the
shard hasn’t started the heartbeater.
Returns a SendErrorType::Sending
error type if there is an issue
with sending via the shard’s session. This may occur when the shard is
between sessions.
Returns a SendErrorType::SessionInactive
error type when the shard
has not been started.
sourcepub fn shutdown(&self)
pub fn shutdown(&self)
Shut down the shard.
The shard will cleanly close the connection by sending a normal close code, causing Discord to show the bot as being offline. The session will not be resumable.
sourcepub fn shutdown_resumable(&self) -> (u64, Option<ResumeSession>)
pub fn shutdown_resumable(&self) -> (u64, Option<ResumeSession>)
Shut down the shard in a resumable fashion.
The shard will cleanly close the connection by sending a restart close
code, causing Discord to keep the bot as showing online. The connection
will be resumable by using the provided session resume information
to ClusterBuilder::resume_sessions
.