#discord-api #discord #discord-bot #ecosystem #gateway #individual #cache

twilight

Twilight生态系统广告crate;请使用以下单独的crate

26个版本 (16个破坏性版本)

0.16.0-rc.12024年2月21日
0.15.1 2023年9月10日
0.15.0 2023年2月5日
0.14.0 2022年11月14日
0.0.0 2020年3月24日

Web编程 中排名第306


用于 stv_bot

ISC许可证

13KB

twilight

codecov badge discord badge github badge license badge rust badge

project logo

twilight 是一个强大、灵活且可扩展的Rust库生态系统,用于Discord API。

这个一等crate生态系统包括 twilight-cache-inmemorytwilight-gatewaytwilight-httptwilight-model 以及更多。这些将在下文中详细介绍。

主要的 twilight crate 完全是一个广告crate:它没有任何功能。请使用以下列出的单独crate代替!

安装

Twilight支持Rust 1.67的MSRV。

我们建议大多数用户从以下crate开始

如果您需要Twilight提供的其他任何功能,只需添加该依赖项即可。

核心crate

这些是大多数用户将一起使用的必要crate,以获得完整的开发体验。您可能不需要所有这些 - 例如 twilight-cache-inmemory - 但它们通常一起使用来完成您需要的绝大多数功能。

twilight-model

定义整个Discord API的结构、枚举和位标志的模型。它分为多个子模块,例如 gateway 用于包含WebSocket网关类型,guild 用于包含由公会(服务器)拥有的类型,voice 包含用于Voice WebSocket API的类型,等等。

这些都在一个crate中,这样您就可以使用 gateway 模型而无需依赖于 twilight-gateway。一个用例是如果您编写自己的WebSocket网关实现。

twilight-cache-inmemory

基于进程内内存的缓存,用于存储从网关接收到的对象。它负责管理和维护有关公会、频道、角色信息、语音状态等来自 Discord 的事件信息。

twilight-gateway

实现 Discord 的分片网关会话。这负责实时接收 Discord 的状态事件并发送一些状态信息。

twilight-http

支持所有 Discord REST API 的 HTTP 客户端。它基于 hyper。它符合 Discord 的速率限制要求,并支持代理。

twilight-standby

事件处理器,允许任务等待事件到来。例如,当你有一个反应菜单并希望等待特定反应到来时,这非常有用。

额外 Crates

这些是 Twilight 官方支持的 Crates,但由于是特定供应商的或对大多数用户不是必需的,所以不被视为核心 Crates。

作为 twilight 生态系统的一部分,为 Lavalink 提供的客户端。

它包括管理多个节点的支持、为每个公会方便地使用玩家发送事件和检索信息的玩家管理器,以及用于创建请求的 HTTP 模块,这些请求使用 http Crate 并提供用于反序列化其响应的模型。

twilight-mention

为各种模型类型创建显示格式化器,用于格式化提及。例如,它可以创建用于提及频道或表情符号的格式化器,或者用于 ping 角色或用户的格式化器。

twilight-util

实用程序 Crate,为 twilight 生态系统添加不适用于其他任何 Crate 的实用工具。目前,它包含

  • 一个 trait,使从 Discord 标识符(雪花)提取数据更容易;
  • 一个计算公会或频道成员权限的计算器。

twilight-gateway-queue

由网关使用以进行速率限制身份验证调用的一些 trait 和实现。开发者应优先使用通过网关的这些 Crate 的重导出。

示例

以下示例是使用 Twilight 的 HTTP 和网关客户端及其内存缓存启动新机器人的模板。为了运行此示例,请将新项目的 main.rs 文件的内容替换为以下内容。请确保将 DISCORD_TOKEN 环境变量设置为您的机器人令牌。您还必须在您的 Cargo.toml 中依赖 tokiotwilight-cache-inmemorytwilight-gatewaytwilight-httptwilight-model

use std::{env, error::Error, sync::Arc};
use twilight_cache_inmemory::{DefaultInMemoryCache, ResourceType};
use twilight_gateway::{Event, EventTypeFlags, Intents, Shard, ShardId, StreamExt as _};
use twilight_http::Client as HttpClient;

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

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

    // Use intents to only receive guild message events.
    let mut shard = Shard::new(
        ShardId::ONE,
        token.clone(),
        Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT,
    );

    // HTTP is separate from the gateway, so create a new client.
    let http = Arc::new(HttpClient::new(token));

    // Since we only care about new messages, make the cache only
    // cache new messages.
    let cache = DefaultInMemoryCache::builder()
        .resource_types(ResourceType::MESSAGE)
        .build();

    // Process each event as they come in.
    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;
        };

        // Update the cache with the event.
        cache.update(&event);

        tokio::spawn(handle_event(event, Arc::clone(&http)));
    }

    Ok(())
}

async fn handle_event(
    event: Event,
    http: Arc<HttpClient>,
) -> Result<(), Box<dyn Error + Send + Sync>> {
    match event {
        Event::MessageCreate(msg) if msg.content == "!ping" => {
            http.create_message(msg.channel_id)
                .content("Pong!")
                .await?;
        }
        // Other events here...
        _ => {}
    }

    Ok(())
}

许可证

所有第一方 Crates 都在 ISC 许可下。

没有运行时依赖