Crates.io | Rust-Discord-API |
lib.rs | Rust-Discord-API |
version | |
source | src |
created_at | 2024-07-15 06:24:02.102755 |
updated_at | 2024-07-15 07:59:02.034971 |
description | A Discord bot framework written in Rust. |
homepage | https://github.com/BeyondJacob/Rust-Discord-API |
repository | |
max_upload_size | |
id | 1303530 |
size | 0 |
A Discord bot framework written in Rust. It provides a structured and easy way to create and manage commands for your Discord bot.
tokio
.Add Rust-Discord-API
to your 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"
Define a Command To define a command, implement the Command trait:
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(())
}
}
Register your commands with the 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 can be organized in subdirectories for better structure. In your project, you have the flexibility to have sub-directories within your 'commands' directory. The library will auto handle your respective mod.rs files for you, for example:
├── commands/ <--- Your project commmands directory.
│ ├── mod.rs (generated by build.rs)
│ ├── ping.rs
│ ├── admin/
│ │ ├── mod.rs (generated by build.rs)
│ │ ├── kick.rs
│ │ ├── ban.rs
pub mod ping;
pub mod admin {
pub mod kick;
pub mod ban;
}
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(())
}
}
This project is licensed under the MIT License. See the LICENSE file for details.