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

pub struct Cluster(_);
Expand description

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

Create a new unconfigured cluster.

Use builder to configure and construct a cluster.

Examples

Create a cluster, receiving a stream of events:

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

let types = EventTypeFlags::MESSAGE_CREATE
    | EventTypeFlags::MESSAGE_DELETE
    | EventTypeFlags::MESSAGE_UPDATE;

let (cluster, mut events) = Cluster::builder(env::var("DISCORD_TOKEN")?, Intents::GUILD_MESSAGES)
    .event_types(types)
    .build()
    .await?;
cluster.up().await;

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.
        _ => {},
    }
}

Errors

Returns a ClusterStartErrorType::RetrievingGatewayInfo error type if there was an HTTP error Retrieving the gateway information.

Create a builder to configure and construct a cluster.

Examples

Create a cluster, receiving 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 token = env::var("DISCORD_TOKEN")?;
let types = EventTypeFlags::MESSAGE_CREATE
    | EventTypeFlags::MESSAGE_DELETE
    | EventTypeFlags::MESSAGE_UPDATE;

let (cluster, mut events) = Cluster::builder(token, Intents::GUILD_MESSAGES)
    .event_types(types)
    .build()
    .await?;
cluster.up().await;

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.
        _ => {},
    }
}

Return an immutable reference to the configuration of this cluster.

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;

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

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.

Return a Shard by its ID.

Return a list of all the shards.

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(),
    );
}

Send a command to the specified shard.

Errors

Returns a ClusterCommandErrorType::Sending error type if the shard exists, but sending it failed.

Returns a ClusterCommandErrorType::ShardNonexistent error type if the provided shard ID does not exist in the cluster.

👎 Deprecated since 0.3.0:

Use send which is more versatile

Send a raw command to the specified shard.

Errors

Returns a ClusterCommandErrorType::Sending error type if the shard exists, but sending it failed.

Returns a ClusterCommandErrorType::ShardNonexistent error type if the provided shard ID does not exist in the cluster.

Send a raw websocket message.

Examples

Send a restart close to shard ID 7:

use std::env;
use twilight_gateway::{
    cluster::Cluster,
    shard::raw_message::{CloseFrame, Message},
    Intents,
};

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

// some time later..
let close = CloseFrame::from((1012, ""));
let message = Message::Close(Some(close));
cluster.send(7, message).await?;

Errors

Returns ClusterCommandErrorType::Sending error type if the shard exists, but sending the close code failed.

Returns a ClusterCommandErrorType::ShardNonexistent error type if the provided shard ID does not exist in the cluster.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

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

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Performs the conversion.

Should always be Self

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.