Skip to main content

Shard

Struct Shard 

Source
pub struct Shard { /* private fields */ }
Expand description

A single connection to the Discord gateway.

A shard is poll-driven (D-037): calling next_event is what drives the connection — it connects, identifies or resumes, sends heartbeats, detects zombied connections and reconnects, all while waiting for the next event. Nothing happens while no one is polling, and there are no background tasks or internal event channels.

Before identifying, a shard waits for its turn in the IdentifyQueue of its Config; shards created from clones of one configuration (as create_shards does) share it. Resuming does not identify and does not wait.

Commands (presence updates, member requests, …) can be sent from other tasks through a MessageSender; they are delivered once the session is active, paced to stay under Discord’s send limit.

discord.js counterpart: WebSocketShard from @discordjs/ws.

§Examples

use djs_gateway::Shard;
use djs_model::gateway::{DispatchEvent, GatewayEvent, Intents, ShardId};

let token = std::env::var("DISCORD_TOKEN").unwrap();
let mut shard = Shard::new(ShardId::ONE, token, Intents::GUILDS | Intents::GUILD_MESSAGES);

while let Some(event) = shard.next_event().await {
    match event {
        Ok(GatewayEvent::Dispatch(_, DispatchEvent::Ready(ready))) => {
            println!("logged in as {}", ready.user.username);
        }
        Ok(_) => {}
        Err(error) if error.is_fatal() => {
            eprintln!("fatal: {error}");
            break;
        }
        Err(error) => eprintln!("recoverable: {error}"),
    }
}

Implementations§

Source§

impl Shard

Source

pub fn new(id: ShardId, token: impl Into<String>, intents: Intents) -> Self

Creates a shard with the default Config. It does not connect until next_event is called.

Pass the raw token, without the Bot prefix.

discord.js counterpart: new WebSocketShard(strategy, id) (@discordjs/ws).

Source

pub fn with_config(id: ShardId, config: Config) -> Self

Creates a shard with a custom Config.

discord.js counterpart: new WebSocketShard(strategy, id) (@discordjs/ws).

Source

pub const fn id(&self) -> ShardId

Returns the shard’s ID.

discord.js counterpart: WebSocketShard#id (@discordjs/ws).

Source

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

Returns the shard’s configuration.

discord.js counterpart: the options of WebSocketManager (@discordjs/ws).

Source

pub const fn state(&self) -> ShardState

Returns the current connection state.

discord.js counterpart: WebSocketShard#status (@discordjs/ws).

Source

pub const fn latency(&self) -> Option<Duration>

Returns the round-trip time of the last acknowledged heartbeat.

discord.js counterpart: WebSocketShard#ping / client.ws.ping.

Source

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

Returns the current session ID, if a session is established.

discord.js counterpart: the sessionId of SessionInfo (@discordjs/ws).

Source

pub const fn sequence(&self) -> Option<u64>

Returns the sequence number of the last dispatch received.

discord.js counterpart: the sequence of SessionInfo (@discordjs/ws).

Source

pub fn sender(&self) -> MessageSender

Returns a handle to send commands to this shard from anywhere.

Commands are queued and sent once the session is active, in order, paced to stay under Discord’s send limit (see MessageSender).

discord.js counterpart: WebSocketShard#send (@discordjs/ws).

Source

pub async fn next_event(&mut self) -> Option<Result<GatewayEvent, ReceiveError>>

Waits for the next event, driving the connection meanwhile.

Returns None once the shard has been closed or fatally closed by Discord. Every gateway payload is returned, including control payloads such as [GatewayEvent::Hello], which the shard has already acted upon.

discord.js counterpart: WebSocketShard#connect and its dispatch event (@discordjs/ws).

§Cancel safety

This method is cancel safe in the sense that cancelling it never corrupts the shard: it can be used in tokio::select!. An event being processed at the moment of cancellation may be lost.

Source

pub async fn close(&mut self)

Closes the connection and invalidates the session (the bot appears offline). Afterwards next_event returns None.

discord.js counterpart: WebSocketShard#destroy.

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 !Freeze for Shard

§

impl !RefUnwindSafe for Shard

§

impl !UnwindSafe for Shard

§

impl Send for Shard

§

impl Sync for Shard

§

impl Unpin for Shard

§

impl UnsafeUnpin for Shard

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<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<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