Skip to main content

Crate twilight_gateway

Crate twilight_gateway 

Source
Expand description

§twilight-gateway

codecov badge discord badge github badge license badge rust badge

twilight-gateway is an implementation of Discord’s sharding gateway sessions. This is responsible for receiving stateful events in real-time from Discord and sending some stateful information.

The primary type is the Shard, a stateful interface to maintain a Websocket connection to Discord’s gateway. Much of its functionality can be configured, and it’s used to receive gateway events or raw Websocket messages, useful for load balancing and microservices.

Multiple shards may be created with the bucket function, and optionally with a per-shard config.

use twilight_gateway::{Config, Shard};

fn shared(config: Config, shards: u32) -> impl Iterator<Item = Shard> {
    unique(std::iter::repeat_n(config, shards as usize))
}

fn unique(iter: impl ExactSizeIterator<Item = Config>) -> impl Iterator<Item = Shard> {
    let bucket_id = 0;
    let buckets = 1;
    let shards = iter.len() as u32;
    iter.zip(twilight_gateway::bucket(bucket_id, buckets, shards))
        .map(|(config, shard_id)| Shard::with_config(shard_id, config))
}

§Features

  • simd-json: use simd-json instead of serde_json for deserializing events
  • TLS (mutually exclusive)
    • native-tls: platform’s native TLS implementation via native-tls
    • rustls-native-roots: rustls using native root certificates
    • rustls-platform-verifier (default): rustls using operating system’s certificate facilities via rustls-platform-verifier
    • rustls-webpki-roots: rustls using webpki-roots for root certificates, useful for scratch containers
  • twilight-http (default): enable the stream::create_recommended function
  • Transport compression (mutually exclusive)
    • zlib: Zlib transport compression using zlib-rs1
    • zstd (default): Zstandard transport compression using zstd-sys

§Examples

Create a shard and loop over guild events:

use std::env;
use twilight_gateway::{EventTypeFlags, Intents, Shard, ShardId, StreamExt as _};

#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
    // Initialize the tracing subscriber.
    tracing_subscriber::fmt::init();

    // Select rustls backend
    rustls::crypto::ring::default_provider().install_default().unwrap();

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

    // Initialize the first and only shard in use by a bot.
    let mut shard = Shard::new(ShardId::ONE, token, Intents::GUILDS);

    tracing::info!("started shard");

    while let Some(event) = shard.next_event(EventTypeFlags::all()).await {
        match event {
            Ok(event) => tracing::info!(?event, "received event"),
            Err(source) => tracing::warn!(?source, "failed to receive event"),
        }
    }

    Ok(())
}

There are a few additional examples located in the repository. Check out our template to get started quickly.


  1. Except for the s390x arch, where zlib-ng-sys is used instead. 

Re-exports§

pub use twilight_gateway_queue as queue;
pub use twilight_model::gateway::event::Event;
pub use twilight_model::gateway::event::EventType;

Modules§

error
Errors returned by gateway operations.

Structs§

CloseFrame
Information about a close message.
CommandRatelimiter
Ratelimiter for sending commands over the gateway to Discord.
Config
Configuration used by the shard to identify with the gateway and operate.
ConfigBuilder
Builder to customize the operation of a shard.
EventTypeFlags
Important optimization for narrowing requested event types.
Intents
Gateway intents.
Latency
Shard’s gateway connection latency.
MessageSender
Channel to send messages over a Shard to the Discord gateway.
Session
Gateway session information for a shard’s active connection.
Shard
Gateway API client responsible for up to 2500 guilds.
ShardId
Shard identifier to calculate if it receivies a given event.

Enums§

Message
Message to send over the connection to the remote.
ShardState
Current state of a Shard.

Constants§

API_VERSION
Discord Gateway API version used by this crate.

Traits§

Command
Trait marker denoting what can be provided to Shard::command.
StreamExt
An extension trait for the [Stream] trait.

Functions§

bucket
Creates an iterator of a single bucket’s worth of shard identifiers.
create_bucketDeprecated
Create a single bucket’s worth of shards.
create_iteratorDeprecated
Create a iterator of shards.
create_recommendedtwilight-http
Create a range of shards from Discord’s recommendation.
parse
Parse a JSON encoded gateway event into a GatewayEvent if wanted_event_types contains its type.