Struct serenity::gateway::Shard

source ·
pub struct Shard {
    pub client: WsClient,
    pub started: Instant,
    pub token: String,
    pub intents: GatewayIntents,
    /* private fields */
}
Available on crate feature gateway only.
Expand description

A Shard is a higher-level handler for a websocket connection to Discord’s gateway. The shard allows for sending and receiving messages over the websocket, such as setting the active activity, reconnecting, syncing guilds, and more.

Refer to the module-level documentation for information on effectively using multiple shards, if you need to.

Note that there are additional methods available if you are manually managing a shard yourself, although they are hidden from the documentation since there are few use cases for doing such.

§Stand-alone shards

You may instantiate a shard yourself - decoupled from the Client - if you need to. For most use cases, you will not need to do this, and you can leave the client to do it.

This can be done by passing in the required parameters to Self::new. You can then manually handle the shard yourself.

Note: You really do not need to do this. Just call one of the appropriate methods on the Client.

§Examples

See the documentation for Self::new on how to use this.

Fields§

§client: WsClient§started: Instant

Instant of when the shard was started.

§token: String§intents: GatewayIntents

Implementations§

source§

impl Shard

source

pub async fn new( ws_url: Arc<Mutex<String>>, token: &str, shard_info: ShardInfo, intents: GatewayIntents, presence: Option<PresenceData> ) -> Result<Shard>

Instantiates a new instance of a Shard, bypassing the client.

Note: You should likely never need to do this yourself.

§Examples

Instantiating a new Shard manually for a bot with no shards, and then listening for events:

use std::sync::Arc;

use serenity::gateway::Shard;
use serenity::model::gateway::{GatewayIntents, ShardInfo};
use serenity::model::id::ShardId;
use tokio::sync::Mutex;
let token = std::env::var("DISCORD_BOT_TOKEN")?;
let shard_info = ShardInfo {
    id: ShardId(0),
    total: 1,
};

// retrieve the gateway response, which contains the URL to connect to
let gateway = Arc::new(Mutex::new(http.get_gateway().await?.url));
let shard = Shard::new(gateway, &token, shard_info, GatewayIntents::all(), None).await?;

// at this point, you can create a `loop`, and receive events and match
// their variants
§Errors

On Error, will return either Error::Gateway, Error::Tungstenite or a Rustls/native TLS error.

source

pub fn set_application_id_callback( &mut self, callback: impl FnOnce(ApplicationId) + Send + Sync + 'static )

Sets a callback to be called when the gateway receives the application’s ID from Discord.

Used internally by serenity to set the Http’s internal application ID automatically.

source

pub fn presence(&self) -> &PresenceData

Retrieves the current presence of the shard.

source

pub fn last_heartbeat_sent(&self) -> Option<Instant>

Retrieves the value of when the last heartbeat was sent.

source

pub fn last_heartbeat_ack(&self) -> Option<Instant>

Retrieves the value of when the last heartbeat ack was received.

source

pub async fn heartbeat(&mut self) -> Result<()>

Sends a heartbeat to the gateway with the current sequence.

This sets the last heartbeat time to now, and Self::last_heartbeat_acknowledged to false.

§Errors

Returns GatewayError::HeartbeatFailed if there was an error sending a heartbeat.

source

pub fn heartbeat_interval(&self) -> Option<Duration>

Returns the heartbeat interval dictated by Discord, if the Hello packet has been received.

source

pub fn last_heartbeat_acknowledged(&self) -> bool

source

pub fn seq(&self) -> u64

source

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

source

pub fn set_activity(&mut self, activity: Option<ActivityData>)

source

pub fn set_presence( &mut self, activity: Option<ActivityData>, status: OnlineStatus )

source

pub fn set_status(&mut self, status: OnlineStatus)

source

pub fn shard_info(&self) -> ShardInfo

Retrieves a copy of the current shard information.

For example, if using 3 shards in total, and if this is shard 1, then it can be read as “the second of three shards”.

source

pub fn stage(&self) -> ConnectionStage

Returns the current connection stage of the shard.

source

pub fn handle_event( &mut self, event: &Result<GatewayEvent> ) -> Result<Option<ShardAction>>

Handles an event from the gateway over the receiver, requiring the receiver to be passed if a reconnect needs to occur.

The best case scenario is that one of two values is returned:

  • Ok(None): a heartbeat, late hello, or session invalidation was received;
  • Ok(Some((event, None))): an op0 dispatch was received, and the shard’s voice state will be updated, if the voice feature is enabled.
§Errors

Returns a GatewayError::InvalidAuthentication if invalid authentication was sent in the IDENTIFY.

Returns a GatewayError::InvalidShardData if invalid shard data was sent in the IDENTIFY.

Returns a GatewayError::NoAuthentication if no authentication was sent in the IDENTIFY.

Returns a GatewayError::OverloadedShard if the shard would have too many guilds assigned to it.

source

pub async fn do_heartbeat(&mut self) -> bool

Does a heartbeat if needed. Returns false if something went wrong and the shard should be restarted.

true is returned under one of the following conditions:

  • the heartbeat interval has not elapsed
  • a heartbeat was successfully sent
  • there is no known heartbeat interval yet

false is returned under one of the following conditions:

  • a heartbeat acknowledgement was not received in time
  • an error occurred while heartbeating
source

pub fn latency(&self) -> Option<StdDuration>

Calculates the heartbeat latency between the shard and the gateway.

source

pub fn should_reconnect(&mut self) -> Option<ReconnectType>

Performs a deterministic reconnect.

The type of reconnect is deterministic on whether a Self::session_id.

If the session_id still exists, then a RESUME is sent. If not, then an IDENTIFY is sent.

Note that, if the shard is already in a stage of ConnectionStage::Connecting, then no action will be performed.

source

pub fn reconnection_type(&self) -> ReconnectType

source

pub async fn chunk_guild( &mut self, guild_id: GuildId, limit: Option<u16>, presences: bool, filter: ChunkGuildFilter, nonce: Option<&str> ) -> Result<()>

Requests that one or multiple Guilds be chunked.

This will ask the gateway to start sending member chunks for large guilds (250 members+). If a guild is over 250 members, then a full member list will not be downloaded, and must instead be requested to be sent in “chunks” containing members.

Member chunks are sent as the Event::GuildMembersChunk event. Each chunk only contains a partial amount of the total members.

If the cache feature is enabled, the cache will automatically be updated with member chunks.

§Examples

Chunk a single guild by Id, limiting to 2000 Members, and not specifying a query parameter:

use serenity::model::id::GuildId;

shard.chunk_guild(GuildId::new(81384788765712384), Some(2000), false, ChunkGuildFilter::None, None).await?;

Chunk a single guild by Id, limiting to 20 members, and specifying a query parameter of "do" and a nonce of "request":

use serenity::model::id::GuildId;

shard
    .chunk_guild(
        GuildId::new(81384788765712384),
        Some(20),
        false,
        ChunkGuildFilter::Query("do".to_owned()),
        Some("request"),
    )
    .await?;
source

pub async fn identify(&mut self) -> Result<()>

Sets the shard as going into identifying stage, which sets:

source

pub async fn initialize(&mut self) -> Result<WsClient>

Initializes a new WebSocket client.

This will set the stage of the shard before and after instantiation of the client.

source

pub async fn reset(&mut self)

source

pub async fn resume(&mut self) -> Result<()>

source

pub async fn reconnect(&mut self) -> Result<()>

source

pub async fn update_presence(&mut self) -> Result<()>

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

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 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> Same for T

§

type Output = T

Should always be Self
source§

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

§

type Error = Infallible

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

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

Performs the conversion.
source§

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

§

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<V, T> VZip<V> for T
where 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