#http-client #discord-bot #bot-framework #bot #discord #discord-api #framework

Rust-Discord-API

使用 Rust 编写的 Discord 机器人框架

2 个版本

0.1.1 2024 年 7 月 15 日
0.1.0 2024 年 7 月 15 日

#498 in 网络编程

MIT 许可协议

125KB
1.5K SLoC

Rust Discord API

使用 Rust 编写的 Discord 机器人框架。它提供了一种结构化和简单的方式来创建和管理 Discord 机器人的命令。

特性

  • 易于注册和管理命令。
  • 使用 tokio 实现异步命令执行。
  • 支持按子目录组织命令。

安装

Rust-Discord-API 添加到您的 Cargo.toml

[dependencies]
rust-discord-api = "0.1.0"
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12.5", features = ["json"] }
async-trait = "0.1"

用法

定义命令 要定义命令,实现 Command 特性

use async_trait::async_trait;
use reqwest::Client;
use exampleapp::Command;
use std::error::Error;

pub struct PingCommand;

#[async_trait]
impl Command for PingCommand {
    async fn execute(&self, client: &Client, token: &str, channel_id: &str, _args: &str) -> Result<(), Box<dyn Error>> {
        // Implement your message sending logic here
        println!("Pong!");
        Ok(())
    }
}

注册命令

使用 CommandRouter 注册您的命令

use exampleapp::{CommandRouter, Command};
use std::sync::Arc;
use tokio::sync::RwLock;
use reqwest::Client;
use std::env;
use async_trait::async_trait;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");

    let client = Client::new();
    let mut command_router = CommandRouter::new();

    command_router.register_command("!ping", Arc::new(PingCommand));

    let command_router = Arc::new(RwLock::new(command_router));

    // Simulated message handling loop
    let simulated_messages = vec![
        ("!ping", "channel_id_1"),
    ];

    for (content, channel_id) in simulated_messages {
        let router = command_router.read().await;
        router.dispatch(&client, &token, channel_id, content).await?;
    }

    Ok(())
}

在子目录中组织命令

命令可以按子目录组织以获得更好的结构。在您的项目中,您可以在 'commands' 目录内拥有子目录。该库将自动为您处理相应的 mod.rs 文件,例如

├── commands/ <--- Your project commmands directory.
│   ├── mod.rs (generated by build.rs)
│   ├── ping.rs
│   ├── admin/
│   │   ├── mod.rs (generated by build.rs)
│   │   ├── kick.rs
│   │   ├── ban.rs

示例 src/commands/mod.rs

pub mod ping;
pub mod admin {
    pub mod kick;
    pub mod ban;
}

示例 src/commands/ping.rs

use async_trait::async_trait;
use reqwest::Client;
use exampleapp::Command;
use std::error::Error;

pub struct PingCommand;

#[async_trait]
impl Command for PingCommand {
    async fn execute(&self, client: &Client, token: &str, channel_id: &str, _args: &str) -> Result<(), Box<dyn Error>> {
        println!("Pong!");
        Ok(())
    }
}

许可协议

本项目采用 MIT 许可协议。有关详细信息,请参阅 LICENSE 文件。

依赖项

~6–17MB
~249K SLoC