Skip to main content

Shard

Struct Shard 

Source
pub struct Shard<Q = InMemoryQueue> { /* private fields */ }
Expand description

Gateway API client responsible for up to 2500 guilds.

Shards are responsible for maintaining the gateway connection by processing events relevant to the operation of shards—such as requests from the gateway to re-connect or invalidate a session—and then to pass them on to the user.

Shards start out disconnected, but will on the first successful call to poll_next try to reconnect to the gateway. poll_next must then be repeatedly called in order for the shard to maintain its connection and update its internal state.

Shards go through an identify queue that rate limits concurrent Identify events (across all shards) per 5 seconds. Exceeding this limit invalidates the shard’s session and it is therefore very important to reuse the same queue for all shards.

§Sharding

A shard may not be connected to more than 2500 guilds, so large bots must split themselves across multiple shards. See the Discord Docs/Sharding and ShardId documentation for more info.

§Examples

Create and start a shard and print new and deleted messages:

use std::env;
use twilight_gateway::{Event, EventTypeFlags, Intents, Shard, ShardId, StreamExt as _};

// Use the value of the "DISCORD_TOKEN" environment variable as the bot's
// token. Of course, this value may be passed into the program however is
// preferred.
let token = env::var("DISCORD_TOKEN")?;
let wanted_event_types = EventTypeFlags::MESSAGE_CREATE | EventTypeFlags::MESSAGE_DELETE;

let mut shard = Shard::new(ShardId::ONE, token, Intents::GUILD_MESSAGES);

while let Some(item) = shard.next_event(EventTypeFlags::all()).await {
    let Ok(event) = item else {
        tracing::warn!(source = ?item.unwrap_err(), "error receiving event");

        continue;
    };

    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(id: ShardId, token: String, intents: Intents) -> Self

Create a new shard with the default configuration.

Source§

impl<Q> Shard<Q>

Source

pub fn with_config(shard_id: ShardId, config: Config<Q>) -> Self

Create a new shard with the provided configuration.

Source

pub const fn config(&self) -> &Config<Q>

Immutable reference to the configuration used to instantiate this shard.

Source

pub const fn id(&self) -> ShardId

ID of the shard.

Source

pub const fn state(&self) -> ShardState

State of the shard.

Source

pub const fn latency(&self) -> &Latency

Shard latency statistics, including average latency and recent heartbeat latency times.

Reset when reconnecting to the gateway.

Source

pub const fn ratelimiter(&self) -> Option<&CommandRatelimiter>

Statistics about the number of available commands and when the command ratelimiter will refresh.

This won’t be present if ratelimiting was disabled via ConfigBuilder::ratelimit_messages or if the shard is disconnected.

Source

pub fn resume_url(&self) -> Option<&str>

Immutable reference to the gateways current resume URL.

A resume URL might not be present if the shard had its session invalidated and has not yet reconnected.

Source

pub const fn session(&self) -> Option<&Session>

Immutable reference to the active gateway session.

An active session may not be present if the shard had its session invalidated and has not yet reconnected.

Source

pub fn command(&self, command: &impl Command)

Queue a command to be sent to the gateway.

Serializes the command and then calls send.

Source

pub fn send(&self, json: String)

Queue a JSON encoded gateway event to be sent to the gateway.

Source

pub fn close(&self, close_frame: CloseFrame<'static>)

Queue a websocket close frame.

Invalidates the session and shows the application’s bot as offline if the close frame code is 1000 or 1001. Otherwise Discord will continue showing the bot as online until its presence times out.

To read all remaining messages, continue calling poll_next until it returns Message::Close.

§Example

Close the shard and process remaining messages:

use tokio_stream::StreamExt;
use twilight_gateway::{CloseFrame, Message, error::ReceiveMessageErrorType};

shard.close(CloseFrame::NORMAL);

while let Some(item) = shard.next().await {
    match item {
        Ok(Message::Close(_)) => break,
        Ok(Message::Text(_)) => unimplemented!(),
        Err(source) => unimplemented!(),
    }
}
Source

pub fn sender(&self) -> MessageSender

Retrieve a channel to send messages over the shard to the gateway.

This is primarily useful for sending to other tasks and threads where the shard won’t be available.

§Example

Queue a command in another process:

use tokio_stream::StreamExt;

while let Some(item) = shard.next().await {
    match item {
        Ok(message) => {
            let sender = shard.sender();
            tokio::spawn(async move {
                let command = unimplemented!();
                sender.send(command);
            });
        }
        Err(source) => unimplemented!(),
    }
}

Trait Implementations§

Source§

impl<Q: Debug> Debug for Shard<Q>

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<Q: Queue + Unpin> Stream for Shard<Q>

Source§

type Item = Result<Message, ReceiveMessageError>

Values yielded by the stream.
Source§

fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Self::Item>>

Attempt to pull out the next value of this stream, registering the current task for wakeup if the value is not yet available, and returning None if the stream is exhausted. Read more
§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. Read more

Auto Trait Implementations§

§

impl<Q = InMemoryQueue> !Freeze for Shard<Q>

§

impl<Q = InMemoryQueue> !RefUnwindSafe for Shard<Q>

§

impl<Q = InMemoryQueue> !Sync for Shard<Q>

§

impl<Q = InMemoryQueue> !UnwindSafe for Shard<Q>

§

impl<Q> Forget for Shard<Q>

§

impl<Q> Move for Shard<Q>

§

impl<Q> Send for Shard<Q>
where Config<Q>: Send,

§

impl<Q> Unpin for Shard<Q>
where Config<Q>: Unpin,

§

impl<Q> UnsafeUnpin for Shard<Q>
where Config<Q>: UnsafeUnpin,

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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 T
where U: From<T>,

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<St> StreamExt for St
where St: Stream<Item = Result<Message, ReceiveMessageError>> + ?Sized,

Source§

fn next_event( &mut self, wanted_event_types: EventTypeFlags, ) -> NextEvent<'_, Self>
where Self: Unpin,

Consumes and returns the next wanted Event in the stream or None if the stream is finished. Read more
Source§

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

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

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

Source§

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

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.
§

impl<S, T, E> TryStream for S
where S: Stream<Item = Result<T, E>> + ?Sized,

§

type Ok = T

The type of successful values yielded by this future
§

type Error = E

The type of failures yielded by this future
§

fn try_poll_next( self: Pin<&mut S>, cx: &mut Context<'_>, ) -> Poll<Option<Result<<S as TryStream>::Ok, <S as TryStream>::Error>>>

Poll this TryStream as if it were a Stream. Read more
§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

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