Expand description
§twilight-gateway
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: usesimd-jsoninstead ofserde_jsonfor deserializing events- TLS (mutually exclusive)
native-tls: platform’s native TLS implementation vianative-tlsrustls-native-roots:rustlsusing native root certificatesrustls-platform-verifier(default):rustlsusing operating system’s certificate facilities viarustls-platform-verifierrustls-webpki-roots:rustlsusingwebpki-rootsfor root certificates, useful forscratchcontainers
twilight-http(default): enable thestream::create_recommendedfunction- Transport compression (mutually exclusive)
§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.
Except for the s390x arch, where
zlib-ng-sysis 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§
- Close
Frame - Information about a close message.
- Command
Ratelimiter - Ratelimiter for sending commands over the gateway to Discord.
- Config
- Configuration used by the shard to identify with the gateway and operate.
- Config
Builder - Builder to customize the operation of a shard.
- Event
Type Flags - Important optimization for narrowing requested event types.
- Intents
- Gateway intents.
- Latency
Shard’s gateway connection latency.- Message
Sender - Channel to send messages over a
Shardto 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.
- Shard
State - 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. - Stream
Ext - An extension trait for the [
Stream] trait.
Functions§
- bucket
- Creates an iterator of a single bucket’s worth of shard identifiers.
- create_
bucket Deprecated - Create a single bucket’s worth of shards.
- create_
iterator Deprecated - Create a iterator of shards.
- create_
recommended twilight-http - Create a range of shards from Discord’s recommendation.
- parse
- Parse a JSON encoded gateway event into a
GatewayEventifwanted_event_typescontains its type.