[][src]Struct twilight_gateway::cluster::Cluster

pub struct Cluster(_);

A manager for multiple shards.

The Cluster can be cloned and will point to the same cluster, so you can pass it around as needed.

Cloning

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

Examples

Refer to the module-level documentation for examples.

Implementations

impl Cluster[src]

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

Create a new unconfigured cluster.

Use builder to configure and construct a cluster.

Errors

Returns ClusterStartError::RetrievingGatewayInfo if there was an HTTP error Retrieving the gateway information.

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

Create a builder to configure and construct a cluster.

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

Return an immutable reference to the configuration of this cluster.

pub async fn up(&self)[src]

Bring up the cluster, starting all of the shards that it was configured to manage.

Examples

Bring up a cluster, starting shards all 10 shards that a bot uses:

use twilight_gateway::{cluster::{Cluster, ShardScheme}, Intents};
use std::{
    convert::TryFrom,
    env,
};

let token = env::var("DISCORD_TOKEN")?;
let scheme = ShardScheme::try_from((0..=9, 10))?;
let cluster = Cluster::builder(token, Intents::GUILD_MESSAGES)
    .shard_scheme(scheme)
    .build()
    .await?;

// Finally, bring up the cluster.
cluster.up().await;

pub fn down(&self)[src]

Bring down the cluster, stopping all of the shards that it's managing.

pub fn down_resumable(&self) -> HashMap<u64, ResumeSession>[src]

Bring down the cluster in a resumable way and returns all info needed for resuming.

The returned map is keyed by the shard's ID to the information needed to resume. If a shard can't resume, then it is not included in the map.

Note: Discord only allows resuming for a few minutes after disconnection. You may also not be able to resume if you missed too many events already.

pub fn shard(&self, id: u64) -> Option<Shard>[src]

Return a Shard by its ID.

pub fn shards(&self) -> Vec<Shard>[src]

Return a list of all the shards.

pub fn info(&self) -> HashMap<u64, Information>[src]

Return information about all shards.

Examples

After waiting a minute, print the ID, latency, and stage of each shard:

use twilight_gateway::{Cluster, Intents};
use std::{env, time::Duration};

let cluster = Cluster::new(env::var("DISCORD_TOKEN")?, Intents::empty()).await?;
cluster.up().await;

tokio::time::sleep(Duration::from_secs(60)).await;

for (shard_id, info) in cluster.info() {
    println!(
        "Shard {} is {} with an average latency of {:?}",
        shard_id,
        info.stage(),
        info.latency().average(),
    );
}

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

Send a command to the specified shard.

Errors

Returns ClusterCommandError::Sending if the shard exists, but sending it failed.

Returns ClusterCommandError::ShardNonexistent if the provided shard ID does not exist in the cluster.

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

Send a raw command to the specified shard.

Errors

Returns ClusterCommandError::Sending if the shard exists, but sending it failed.

Returns ClusterCommandError::ShardNonexistent if the provided shard ID does not exist in the cluster.

pub fn events(&self) -> impl Stream<Item = (u64, Event)>[src]

Return a stream of events from all shards managed by this Cluster.

Each item in the stream contains both the shard's ID and the event itself.

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.

pub fn some_events(
    &self,
    types: EventTypeFlags
) -> impl Stream<Item = (u64, Event)>
[src]

Like events, but filters the events so that the stream consumer receives only the selected event types.

Examples

Retrieve a stream of events when a message is created, deleted, or updated:

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

let cluster = Cluster::new(env::var("DISCORD_TOKEN")?, Intents::GUILD_MESSAGES).await?;
cluster.up().await;

let types = EventTypeFlags::MESSAGE_CREATE
    | EventTypeFlags::MESSAGE_DELETE
    | EventTypeFlags::MESSAGE_UPDATE;
let mut events = cluster.some_events(types);

while let Some((shard_id, event)) = events.next().await {
    match event {
        Event::MessageCreate(_) => println!("Shard {} got a new message", shard_id),
        Event::MessageDelete(_) => println!("Shard {} got a deleted message", shard_id),
        Event::MessageUpdate(_) => println!("Shard {} got an updated message", shard_id),
        // No other events will come in through the stream.
        _ => {},
    }
}

Trait Implementations

impl Clone for Cluster[src]

impl Debug for Cluster[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>,