RIG中文文档非官方中文译本

构建 Discord 机器人

实战指南官网快照 · 2026-11-10阅读英文原文 ↗
Rig 0.46.0 实际适配版

本页 4 个 Rust 代码块均有编译检查记录;片段已补齐所需上下文。 1 个代码块已更新。

查看逐块编译结果、运行前提与示例项目 →

本教程用 Rig 和 Serenity Discord 库构建机器人。机器人通过检索增强生成(RAG),依据 Markdown 知识库回答问题:每次提问时,Rig 为查询生成嵌入,从向量存储取出最接近的文档,再把文档和问题一起交给模型。

实现分为两部分:

  1. Rig Agent(rig_agent.rs):加载 Markdown 文件、生成嵌入并构建 RAG Agent。这一部分没有 Discord 代码,可以独立测试。
  2. Discord 层(main.rs):注册 /ask 斜杠命令、监听提及机器人,并把两种请求都转交 Agent。

如果不熟悉 Rig 中的 RAG,先浏览向量存储与 RAG和构建 RAG 系统指南。

mermaid
sequenceDiagram
participant User
participant DiscordBot
participant RigAgent
User->>DiscordBot: /ask or @mention
DiscordBot->>RigAgent: question
RigAgent->>RigAgent: retrieve docs + call model
RigAgent->>DiscordBot: answer
DiscordBot->>User: reply

前置条件#

  • Rust
  • Discord 机器人应用及其 token。按照 Discord 的入门指南操作,并在机器人设置页启用 Message Content intent。
  • 一个 OpenAI API Key

项目准备#

bash
cargo new discord_rig_bot
cd discord_rig_bot
mkdir documents

Cargo.toml:

toml
[dependencies]
rig = "=0.46.0"
serenity = "0.12"
tokio = { version = "1", features = ["full"] }
anyhow = "1"

将知识库以 Markdown 文件放在 documents/ 中。该目录下的所有 .md 文件都会加载,可以先放几页项目文档、FAQ 或一些示例。

在环境变量中设置两个密钥:

bash
export DISCORD_TOKEN=your_discord_bot_token
export OPENAI_API_KEY=your_openai_api_key

Rig Agent(rig_agent.rs)#

build_agent 读取目录中的每个 Markdown 文件,使用 OpenAI 的 text-embedding-3-small 分别生成嵌入,存入内存向量存储,然后创建一个 Agent,在每次提问时将最接近的两份文档加入上下文。

rust
use std::path::Path;


use anyhow::{Context, Result};
use rig::embeddings::EmbeddingsBuilder;
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
use rig::vector_store::in_memory_store::InMemoryVectorStore;


const PREAMBLE: &str = "\
You are a helpful assistant in a Discord server. Answer questions using the documents \
provided in your context, and say so when they do not cover the question. Keep answers \
short: Discord messages are limited to 2000 characters. Format code as Markdown code \
blocks tagged with their language.";


pub async fn build_agent(documents_dir: &Path) -> Result<Agent> {
    let client = OpenAI::from_env()?;
    let embedding_model = client.embedding(openai::TEXT_EMBEDDING_3_SMALL, None);


    let documents = load_markdown(documents_dir)?;
    let embeddings = EmbeddingsBuilder::new(embedding_model.clone())
        .documents(documents)?
        .build()
        .await?;


    let index = InMemoryVectorStore::from_documents(embeddings).index(embedding_model);


    Ok(AgentBuilder::new(client.completion(openai::GPT_5_5))
        .preamble(PREAMBLE)
        .dynamic_context(2, index)
        .build())
}


fn load_markdown(dir: &Path) -> Result<Vec<String>> {
    let mut documents = Vec::new();
    for entry in std::fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
        let path = entry?.path();
        if path.extension().is_some_and(|ext| ext == "md") {
            let text = std::fs::read_to_string(&path)
                .with_context(|| format!("reading {}", path.display()))?;
            documents.push(text);
        }
    }
    Ok(documents)
}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

  • client.embedding(model, None) 创建嵌入模型;None 保留模型默认的向量维度。
  • EmbeddingsBuilder 为每份文档生成嵌入。String 直接嵌入其自身内容;结构化文档则派生 Embed,并标记需要嵌入的字段,见向量嵌入。
  • dynamic_context(2, index) 将检索变成 Agent 的组成部分:每次模型调用之前,用提示词搜索 index,将前两份文档加入请求。

Agent 克隆成本低,可安全地跨任务共享,Discord 处理器依赖这一点。

先脱离 Discord 测试 Agent#

添加 Discord 之前,先确认检索和模型能工作:

rust
let agent = rig_agent::build_agent(std::path::Path::new("documents")).await?;
let answer = agent.prompt("What is this project about?").await?.output();
println!("{answer}");

完整代码与上下文 ↗编译通过 · Rig 0.46.0

Discord 层(main.rs)#

处理器持有 Agent。收到 ready 时注册 /ask 命令;收到 /ask 交互时,先延迟回复确认(模型调用可能超过 Discord 的三秒确认窗口),再向 Agent 提问,最后把答案更新进回复。收到提及机器人的消息时,去掉提及内容并在频道中回复。

rust
mod rig_agent;


use anyhow::Result;
use rig::prelude::*;
use serenity::all::{
    async_trait, Command, CommandInteraction, CommandOptionType, Context, CreateCommand,
    CreateCommandOption, EditInteractionResponse, EventHandler, GatewayIntents, Interaction,
    Message, Ready,
};


/// Discord rejects messages longer than 2000 characters.
fn truncate(text: String) -> String {
    match text.char_indices().nth(1990) {
        Some((cut, _)) => format!("{}…", &text[..cut]),
        None => text,
    }
}


struct Handler {
    agent: Agent,
}


impl Handler {
    async fn answer(&self, question: &str) -> String {
        match self.agent.prompt(question).await {
            Ok(response) => truncate(response.output()),
            Err(e) => {
                eprintln!("agent error: {e}");
                "Sorry, something went wrong while answering.".to_string()
            }
        }
    }


    async fn ask(&self, ctx: &Context, command: &CommandInteraction) -> serenity::Result<()> {
        command.defer(&ctx.http).await?;
        let question = command
            .data
            .options
            .first()
            .and_then(|option| option.value.as_str())
            .unwrap_or_default();
        let answer = self.answer(question).await;
        command
            .edit_response(&ctx.http, EditInteractionResponse::new().content(answer))
            .await?;
        Ok(())
    }
}


#[async_trait]
impl EventHandler for Handler {
    async fn ready(&self, ctx: Context, ready: Ready) {
        println!("{} is connected", ready.user.name);
        let ask = CreateCommand::new("ask")
            .description("Ask the bot a question")
            .add_option(
                CreateCommandOption::new(CommandOptionType::String, "query", "Your question")
                    .required(true),
            );
        if let Err(e) = Command::create_global_command(&ctx.http, ask).await {
            eprintln!("failed to register /ask: {e}");
        }
    }


    async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
        if let Interaction::Command(command) = interaction {
            if command.data.name == "ask" {
                if let Err(e) = self.ask(&ctx, &command).await {
                    eprintln!("failed to answer /ask: {e}");
                }
            }
        }
    }


    async fn message(&self, ctx: Context, msg: Message) {
        if msg.author.bot || !msg.mentions_me(&ctx).await.unwrap_or(false) {
            return;
        }
        let mention = format!("<@{}>", ctx.cache.current_user().id);
        let question = msg.content.replace(&mention, "");
        let _ = msg.channel_id.broadcast_typing(&ctx.http).await;
        let answer = self.answer(question.trim()).await;
        if let Err(e) = msg.channel_id.say(&ctx.http, answer).await {
            eprintln!("failed to reply: {e}");
        }
    }
}


#[tokio::main]
async fn main() -> Result<()> {
    let token = std::env::var("DISCORD_TOKEN")?;
    let agent = rig_agent::build_agent(std::path::Path::new("documents")).await?;


    let intents = GatewayIntents::GUILDS
        | GatewayIntents::GUILD_MESSAGES
        | GatewayIntents::DIRECT_MESSAGES
        | GatewayIntents::MESSAGE_CONTENT;
    let mut client = serenity::Client::builder(&token, intents)
        .event_handler(Handler { agent })
        .await?;
    client.start().await?;
    Ok(())
}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

运行与测试#

bash
cargo run

日志打印 <bot name> is connected 后,将机器人邀请进服务器:

  1. 在 Discord Developer Portal 打开应用,进入 OAuth2 → URL Generator。
  2. 在 Scopes 下选择 bot 和 applications.commands。
  3. 在 Bot Permissions 下选择 Send Messages 和 Read Message History。
  4. 打开生成的 URL,选择你的服务器。

然后试试:

  • /ask query: How do I get started?
  • @YourBot what does the FAQ say about pricing?

全局斜杠命令第一次可能需要几分钟才会出现在 Discord 客户端中。

机器人响应 /ask 命令

原站图片链接当前返回 404,未能取得原图。

查看原始图片地址 ↗
机器人回答问题

原站图片链接当前返回 404,未能取得原图。

查看原始图片地址 ↗

记住对话#

上面的机器人独立回答每个问题。要让它跟随对话,为每个频道或线程保存历史,并使用 agent.chat;该方法将历史与提示词一起发送,再追加新的用户和助手消息:

rust
let mut histories: HashMap<u64, Vec<Message>> = HashMap::new();


let history = histories.entry(channel_id).or_default();
let answer = agent.chat("And how do I configure it?", history).await?.output();

完整代码与上下文 ↗编译通过 · Rig 0.46.0

在处理器中,用 tokio::sync::RwLock 或 Mutex 保护这个 map,让并发事件能读取和更新。Rig 的 discord_bot 示例 正是这样做的:/new 命令创建线程,线程中的每条消息都会携带该线程历史来回答。

故障排查#

  • 机器人从不响应提及:Message Content intent 未开启。在 Developer Portal 中启用,并在 main 中保留 GatewayIntents::MESSAGE_CONTENT。
  • /ask 显示“The application did not respond”:模型调用之前没有延迟回复确认,确保第一步执行 command.defer。
  • reading documents 错误:从项目根目录运行机器人,或给 build_agent 传绝对路径。

另请参阅#

本文译自 Rig 官方英文文档,中文翻译未经官方审核。代码已按 Rig 0.46.0 更新;英文快照保存在 source,验证范围见版本说明。
原文版权归 Playgrounds / Rig 作者所有 · MIT 许可 · 升级与验证记录 · 站点地图

搜索中文概念、方法名或英文术语。