twilight

repository·main·Indexed 21 days ago

https://github.com/twilight-rs/twilight

A modular ecosystem of Rust libraries for the Discord API. It consists of several specialized crates, including twilight-model for API structures, twilight-gateway for sharding gateway sessions, twilight-http for REST API interaction with ratelimiting, twilight-cache-inmemory for object caching, and twilight-standby for event processing. Additional crates provide support for Lavalink, mention formatting, and gateway identify rate limiting.

Tokens
63.6K
Snippets
179
Records
286
Agent score
74%

What's inside twilight

  1. Overview of twilight-http-ratelimiting

    main
    The twilight-http-ratelimiting crate provides functionality for managing rate limits on HTTP requests. This is specifically designed to handle Discord's rate-limiting behavior, which applies limits both globally and on a per-route basis. To implement this correctly, you should refer to Discord's official documentation regarding their specific rate-limiting algorithms and headers.
  2. Overview of twilight-util

    main

    twilight-util is a utility crate designed for the twilight-rs ecosystem. It provides supplementary types and functions to augment or enhance the default functionality of core twilight crates.

    Key features include:

    • builder: Builders for managing large structs.
    • link: Parsing and formatting entity URLs (e.g., webhook URLs).
    • permission-calculator: Tools to determine member permissions within guilds or channels.
    • snowflake: The Snowflake trait for extracting structured information from Discord snowflakes.
  3. Overview of twilight-lavalink

    main

    twilight-lavalink is a client for [Lavalink] designed to work within the twilight ecosystem. It provides several key capabilities:

    • Node Management: Support for managing multiple Lavalink nodes.
    • Player Manager: A convenient way to use players to send events and retrieve information for each guild.
    • HTTP Support: An HTTP module that uses the twilight-http crate to create requests and provides models for deserializing responses.
    • Automatic Voice Updates: It automatically handles sending voice channel updates to Lavalink by processing events via the Lavarink::process method.

    Important: You must call lavalink.process(&event) with every Voice State Update and Voice Server Update you receive from the Discord gateway to ensure voice connectivity works correctly.

  4. Overview of Twilight Additional Crates

    main

    Twilight provides several officially supported crates for specialized functionality:

    • twilight-lavalink: A client for Lavalink, including multi-node support, a player manager, and an HTTP module.
    • twilight-mention: Provides display formatters for mentioning Discord entities like channels, emojis, roles, or users.
    • twilight-util: Contains general utilities, such as a trait for extracting data from Discord Snowflakes and a calculator for member permissions.
    • twilight-gateway-queue: Provides traits and implementations for ratelimiting identify calls within the gateway.
  5. Overview of Twilight Core Crates

    main

    Twilight is a modular ecosystem of Rust libraries for the Discord API. Instead of using a single monolithic crate, you should depend on the specific crates required for your project. The core crates typically used together are:

    • twilight-model: Defines all structures, enums, and bitflags for the Discord API (e.g., gateway, guild, and voice modules).
    • twilight-gateway: Handles Discord's sharding gateway sessions for real-time stateful events.
    • twilight-http: A hyper-based HTTP client for the Discord REST API that handles ratelimiting and proxying.
    • twilight-cache-inmemory: An in-process memory cache for objects received via the gateway (e.g., guilds, channels, roles, voice states).
    • twilight-standby: An event processor used to make tasks wait for specific incoming events (e.g., waiting for a reaction on a menu).
  6. What is twilight-gateway?

    main

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

    The core abstraction is the Shard, which provides a stateful interface to maintain a WebSocket connection to Discord's gateway. You can use Shard to receive gateway events or raw WebSocket messages, which is useful for microservices or load balancing.

  7. Use twilight-lavalink to manage Lavalink nodes

    main

    twilight-lavalink is a client for Lavalink designed to work with twilight-model events from the twilight-gateway.

    Key capabilities include:

    • Node Management: Support for managing multiple Lavalink nodes.
    • Player Manager: A convenient way to use players to send events and retrieve information for each guild.
    • HTTP Support: An HTTP module for creating requests using the http crate and providing models to deserialize responses (enabled by default via the http-support feature).
  8. Use twilight-model for Discord API types

    main

    The twilight-model crate provides a centralized, versioned definition of the Discord API using serde. It is designed to be a single point of truth for data structures used across the entire Twilight ecosystem (e.g., twilight-lavalink or Embed Builder).

    Key characteristics:

    • Reproducible: Serializing and deserializing a type will result in the same instance.
    • Modular: Types are organized into modules based on resource categories (e.g., gateway for gateway API types, guild for guild-related types).
    • Lightweight: Other crates depend on twilight-model directly to avoid heavy transitive dependencies.
  9. Understanding the Twilight ecosystem

    main

    Twilight is an asynchronous, flexible, and scalable ecosystem of Rust libraries designed for the Discord API. Unlike opinionated, 'batteries-included' libraries (like serenity), Twilight provides modular crates that allow you to build your own architecture. This is ideal for developers who need fine-grained control over how they structure their bots or need to scale to high volumes of data.

    The ecosystem is divided into several core components:

    • twilight-model: Data structures and types.
    • twilight-gateway: Handling the WebSocket connection to Discord.
    • twilight-http: Making REST API requests.
    • twilight-cache-inmemory: Managing local state and resource caching.
    • twilight-standby: (And other specialized crates for advanced use cases).
  10. Use twilight-gateway to connect to the Discord WebSocket Gateway

    main

    twilight-gateway provides a client implementation for Discord's websocket gateway. The primary abstraction is the Shard type. A Shard handles connecting to the gateway, receiving messages, parsing and processing them, and managing connectivity lifecycle tasks such as automatic reconnection, resuming, and identifying.

    use std::{env, error::Error};
    use twilight_gateway::{EventTypeFlags, Intents, Shard, ShardId, StreamExt as _};
    
    #[tokio::main]
    async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
        // Initialize the tracing subscriber.
        tracing_subscriber::fmt::init();
    
        // Select rustls backend
        rustls::crypto::ring::default_provider().install_default().unwrap();
    
        let token = env::var("DISCORD_TOKEN")?;
        let intents = Intents::GUILD_MESSAGES;
        let mut shard = Shard::new(ShardId::ONE, token, intents);
        tracing::info!("created shard");
    
        while let Some(item) = shard.next_event(EventTypeFlags::all()).await {
            let Ok(event) = item else {
                tracing::warn!(source = ?item.unwrap_err(), "error receiving event");
    
                continue;
            };
    
            tracing::debug!(?event, "event");
        }
    
        Ok(())
    }
  11. Use twilight-validate for manual model validation

    main
    While twilight-validate is used internally by twilight-http, it is available for end-users to manually validate models from the twilight-model crate. It provides the necessary constants, methods, and error types to ensure request parameters adhere to expected constraints within the twilight-rs ecosystem.