[][src]Struct twilight_gateway::shard::Shard

pub struct Shard(_);

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.

Cloning

The shard internally wraps its data within an Arc. This means that the shard can be cloned and passed around tasks and threads cheaply.

Examples

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

use futures::stream::StreamExt;
use std::env;
use twilight_gateway::{EventTypeFlags, Event, 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 mut shard = Shard::new(token, Intents::GUILD_MESSAGES);

// Start the shard.
shard.start().await?;

// Create a loop of only new message and deleted message events.
let event_types = EventTypeFlags::MESSAGE_CREATE | EventTypeFlags::MESSAGE_DELETE;
let mut events = shard.some_events(event_types);

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

impl Shard[src]

pub fn new(token: impl Into<String>, intents: Intents) -> Self[src]

Create a new unconfingured 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 twilight_gateway::{Intents, Shard};
use std::{env, time::Duration};
use tokio::time as tokio_time;

let token = env::var("DISCORD_TOKEN")?;

let intents = Intents::GUILD_MESSAGES | Intents::GUILD_MESSAGE_TYPING;
let mut 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());

pub fn builder(token: impl Into<String>, intents: Intents) -> ShardBuilder[src]

Create a builder to configure and construct a shard.

Refer to the builder for more information.

pub fn config(&self) -> &Config[src]

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

pub async fn start(&mut self) -> Result<(), ShardStartError>[src]

Start the shard, connecting it to the gateway and starting the process of receiving and processing events.

Errors

Returns ShardStartError::Establishing if establishing a connection to the gateway failed.

Returns ShardStartError::ParsingGatewayUrl if the gateway URL couldn't be parsed.

Returns ShardStartError::RetrievingGatewayUrl if the gateway URL couldn't be retrieved from the HTTP API.

pub fn events(&self) -> Events[src]

Create a new stream of events from the shard.

There can be multiple streams of events. All events will be broadcast to all streams of events.

Note that we highly recommend specifying only the events that you need via some_events, especially if performance is a concern. This will ensure that events you don't care about aren't deserialized from received websocket messages. Gateway intents only allow specifying categories of events, but using some_events will filter it further on the client side.

The returned event stream implements futures::stream::Stream.

All event types except for EventType::ShardPayload are enabled. If you need to enable it, consider calling some_events instead.

pub fn some_events(&self, event_types: EventTypeFlags) -> Events[src]

Create a new filtered stream of events from the shard.

Only the events specified in the bitflags will be sent over the stream.

The returned event stream implements futures::stream::Stream.

Examples

Filter the events so that you only receive the Event::ShardConnected and Event::ShardDisconnected events:

use twilight_gateway::{EventTypeFlags, Event, Intents, Shard};
use futures::StreamExt;
use std::env;

let mut shard = Shard::new(env::var("DISCORD_TOKEN")?, Intents::empty());
shard.start().await?;

let event_types = EventTypeFlags::SHARD_CONNECTED | EventTypeFlags::SHARD_DISCONNECTED;
let mut events = shard.some_events(event_types);

while let Some(event) = events.next().await {
    match event {
        Event::ShardConnected(_) => println!("Shard is now connected"),
        Event::ShardDisconnected(_) => println!("Shard is now disconnected"),
        // No other event will come in through the stream.
        _ => {},
    }
}

pub fn info(&self) -> Result<Information, SessionInactiveError>[src]

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.

pub fn sink(&self) -> Result<ShardSink, SessionInactiveError>[src]

Retrieve an interface implementing the Sink trait which can be used to send messages.

This sink is only valid for the current websocket connection. If the shard's session is invalidated, or network connectivity is lost, or anything else happens that causes a need to create a new connection, then the sink will be invalidated.

Errors

Returns a SessionInactiveError if the shard's session is inactive.

pub async fn command(&self, value: &impl Serialize) -> Result<(), CommandError>[src]

Send a command over the gateway.

Errors

Returns CommandError::Sending if the message could not be sent over the websocket. This indicates the shard is currently restarting.

Returns CommandError::Serializing if the provided value failed to serialize into JSON.

Returns CommandError::SessionInactive if the shard has not been started.

pub async fn command_raw(&self, value: Vec<u8>) -> Result<(), CommandError>[src]

Send a raw command over the gateway.

This method should be used with caution, command should be preferred.

Errors

Returns CommandError::Sending if the message could not be sent over the websocket. This indicates the shard is currently restarting.

Returns CommandError::Serializing if the provided value failed to serialize into JSON.

Returns CommandError::SessionInactive if the shard has not been started.

pub fn shutdown(&self)[src]

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.

pub fn shutdown_resumable(&self) -> (u64, Option<ResumeSession>)[src]

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

impl Clone for Shard[src]

impl Debug for Shard[src]

Auto Trait Implementations

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T> Instrument for T[src]

impl<T> Instrument for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> Same<T> for T

type Output = T

Should always be Self

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.

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