twilight is a powerful, flexible, and scalable ecosystem of Rust libraries
for the Discord API.
The ecosystem of first-class crates includes twilight-cache-inmemory,
twilight-gateway, twilight-http, twilight-model, and more. These
are explained in detail below.
The main twilight crate is purely an advertisement crate: it has no
functionality. Please use the individual crates listed below instead!
Twilight supports a MSRV of Rust 1.89. We do not consider changes to the MSRV semver-incompatible, therefore it may change in minor or patch releases.
We recommend that most users start out with these crates:
If you need any other functionality that Twilight provides, you can just add that dependency in.
These are essential crates that most users will use together for a full
development experience. You may not need all of these - such as
twilight-cache-inmemory - but they are often used together to accomplish
most of what you need.
Models defining structures, enums, and bitflags for the entirety of the
Discord API. It is split into a number of sub-modules, such as gateway for
containing the WebSocket gateway types, guild for containing types owned
by guilds (servers), voice containing the types used by the Voice
WebSocket API, and more.
These are all in a single crate so that you can use gateway models without
depending on twilight-gateway. One use case is if you write your own
WebSocket gateway implementation.
In-process-memory based cache over objects received from the gateway. It's responsible for holding and managing information about things like guilds, channels, role information, voice states, and any other events that come from Discord.
Implementation of Discord's sharding gateway sessions. This is responsible for receiving stateful events in real-time from Discord and sending some stateful information.
HTTP client supporting all of the Discord REST API. It is based on hyper.
It meets Discord's ratelimiting requirements and supports proxying.
Event processor that allows for tasks to wait for an event to come in. This is useful, for example, when you have a reaction menu and want to wait for a specific reaction on it to come in.
These are crates that are officially supported by Twilight, but aren't considered core crates due to being vendor-specific or non-essential for most users.
Client for Lavalink as part of the twilight ecosystem.
It includes support for managing multiple nodes, a player manager for
conveniently using players to send events and retrieve information for each
guild, and an HTTP module for creating requests using the http crate and
providing models to deserialize their responses.
Create display formatters for various model types that format mentions. For example, it can create formatters for mentioning a channel or emoji, or pinging a role or user.
Utility crate that adds utilities to the twilight ecosystem that do not fit in any other crate. Currently, it contains:
- A trait to make extracting data from Discord identifiers (Snowflakes) easier;
- A calculator to calculate the permissions of a member in a guild or channel.
A trait and some implementations that are used by the gateway to ratelimit identify calls. Developers should prefer to use the re-exports of these crates through the gateway.
The following example is a template for bootstrapping a new bot using
Twilight's HTTP and gateway clients with its in-memory cache. In order to
run this, replace the contents of a new project's main.rs file with the
following. Be sure to set the DISCORD_TOKEN environment variable to your
bot's token. You must also depend on rustls, tokio, twilight-cache-inmemory,
twilight-gateway, twilight-http, and twilight-model in your Cargo.toml.
mod context {
use std::{ops::Deref, sync::OnceLock};
use twilight_cache_inmemory::DefaultInMemoryCache;
use twilight_http::Client;
pub static CONTEXT: Handle = Handle(OnceLock::new());
#[derive(Debug)]
pub struct Context {
pub cache: DefaultInMemoryCache,
pub http: Client,
}
pub fn initialize(cache: DefaultInMemoryCache, http: Client) {
let context = Context { cache, http };
assert!(CONTEXT.0.set(context).is_ok());
}
pub struct Handle(OnceLock<Context>);
impl Deref for Handle {
type Target = Context;
fn deref(&self) -> &Self::Target {
self.0.get().unwrap()
}
}
}
use context::CONTEXT;
use std::env;
use twilight_cache_inmemory::{DefaultInMemoryCache, ResourceType};
use twilight_gateway::{Event, EventTypeFlags, Intents, Shard, ShardId, StreamExt as _};
use twilight_http::Client;
use twilight_model::gateway::payload::incoming::MessageCreate;
// Use event type flags to only deserialize message create events.
const EVENT_TYPES: EventTypeFlags = EventTypeFlags::MESSAGE_CREATE;
// Use intents to only receive guild message events.
const INTENTS: Intents = Intents::GUILD_MESSAGES.union(Intents::MESSAGE_CONTENT);
// Cache only new messages.
const RESOURCE_TYPES: ResourceType = ResourceType::MESSAGE;
#[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("DISCORD_TOKEN")?;
let cache = DefaultInMemoryCache::builder()
.resource_types(RESOURCE_TYPES)
.build();
let http = Client::new(token.clone());
// Initialize the bot context.
context::initialize(cache, http);
let shard = Shard::new(ShardId::ONE, token, INTENTS);
dispatcher(shard).await;
Ok(())
}
#[tracing::instrument(fields(shard = %shard.id()), skip_all)]
async fn dispatcher(mut shard: Shard) {
loop {
let event = match shard.next_event(EVENT_TYPES).await {
Some(Ok(event)) => event,
Some(Err(source)) => {
tracing::warn!(?source, "error receiving event");
continue;
}
None => break,
};
// Update the cache with the event.
CONTEXT.cache.update(&event);
// Route the event to a handler.
let handler = match event {
Event::MessageCreate(event) => message(event),
_ => continue,
};
tokio::spawn(async move {
if let Err(source) = handler.await {
tracing::warn!(?source, "error handling event");
}
});
}
}
#[tracing::instrument(fields(id = %event.id), skip_all)]
async fn message(event: Box<MessageCreate>) -> anyhow::Result<()> {
match &*event.content {
"!ping" => {
CONTEXT
.http
.create_message(event.channel_id)
.content("Pong!")
.await?;
}
_ => {}
}
Ok(())
}All first-party crates are licensed under ISC
