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

source

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

pub fn builder(token: String, intents: Intents) -> ShardBuilder

Create a builder to configure and construct a shard.

Refer to the builder for more information.

source

pub fn config(&self) -> &Config

Return an immutable reference to the configuration used for this client.

source

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.

source

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.

source

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.

source

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.

source

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.

source

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.

Trait Implementations§

source§

impl Debug for Shard

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Shard

§

impl Send for Shard

§

impl Sync for Shard

§

impl Unpin for Shard

§

impl !UnwindSafe for Shard

Blanket Implementations§

source§

impl<T> Any for Twhere
T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere
T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere
T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere
U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for Twhere
U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere
U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere
V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where
S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more