Skip to main content

Crate botrs

Crate botrs 

Source
Expand description

§BotRS - Rust QQ Guild Bot Framework

§Author: YinMo19

License: MIT Rust GitHub Crates.io

本实现不是 qqbot 的官方 rust 版本实现。

BotRS 是一个用 Rust 实现的 QQ 频道机器人框架,基于 QQ 频道机器人 API。它提供了类型安全、高性能、易于使用的接口来开发 QQ 频道机器人。

§快速开始

§安装

将以下内容添加到你的 Cargo.toml:

[dependencies]
botrs = "0.11.0"
tokio = { version = "1.0", features = ["full"] }
tracing = "0.1"
tracing-subscriber = "0.3"
async-trait = "0.1"

§基础示例

use botrs::{Client, Context, EventHandler, Intents, Token, Message};
use botrs::models::gateway::Ready;
use botrs::models::message::MessageParams;
use tracing::info;

struct MyBot;

#[async_trait::async_trait]
impl EventHandler for MyBot {
    async fn ready(&self, _ctx: Context, ready: Ready) {
        info!("Bot {} is ready!", ready.user.username);
    }

    async fn message_create(&self, ctx: Context, message: Message) {
        if message.is_from_bot() {
            return;
        }

        if let Some(content) = &message.content {
            if content.trim() == "!ping" {
                info!("Received ping command from message ID: {:?}", message.id);

                // 使用新的参数结构 API
                let params = MessageParams::new_text("Pong! 🏓");
                if let Some(channel_id) = &message.channel_id {
                    if let Err(e) = ctx.api.post_message_with_params(&ctx.token, channel_id, params).await {
                        info!("Failed to reply: {}", e);
                    }
                }
            }
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    tracing_subscriber::fmt::init();

    // 创建令牌
    let token = Token::new("your_app_id", "your_secret");

    // 设置意图
    let intents = Intents::default();

    // 创建客户端
    let mut client = Client::new(token, intents, MyBot, false)?;

    // 启动机器人
    client.start().await?;

    Ok(())
}

我们强烈推荐你查看 完整文档 来进行开发。这个仓库本身参考了 botpy 和 botgo 的实现,基于 rust 的语言特性进行了深度开发。

Re-exports§

pub use api::BotApi;
pub use audio::Audio;
pub use audio::AudioControl;
pub use audio::AudioStatus;
pub use audio::PublicAudio;
pub use audio::PublicAudioType;
pub use client::Client;
pub use client::Context;
pub use client::EventHandler;
pub use connection::ConnectionSession;
pub use connection::ConnectionState;
pub use connection::Session;
pub use error::BotError;
pub use error::Result;
pub use event::ATMessageEventHandler;
pub use event::AudioEventHandler;
pub use event::C2CFriendEventHandler;
pub use event::C2CMessageEventHandler;
pub use event::ChannelEventHandler;
pub use event::DirectMessageDeleteEventHandler;
pub use event::DirectMessageEventHandler;
pub use event::EnterAIOEventHandler;
pub use event::ErrorNotifyHandler;
pub use event::ForumAuditEventHandler;
pub use event::GroupATMessageEventHandler;
pub use event::GuildEventHandler;
pub use event::GuildMemberEventHandler;
pub use event::InteractionEventHandler;
pub use event::MessageAuditEventHandler;
pub use event::MessageDeleteEventHandler;
pub use event::MessageEventHandler;
pub use event::MessageReactionEventHandler;
pub use event::ParseAndHandle;
pub use event::ParseData;
pub use event::PlainEventHandler;
pub use event::PostEventHandler;
pub use event::PublicMessageDeleteEventHandler;
pub use event::ReadyHandler;
pub use event::RegisterHandler;
pub use event::RegisterHandlers;
pub use event::ReplyEventHandler;
pub use event::SubscribeMsgStatusEventHandler;
pub use event::ThreadEventHandler;
pub use facade::DefaultImpl;
pub use facade::NewOpenAPI;
pub use facade::NewSandboxOpenAPI;
pub use facade::RegisterDispatchEventHandler;
pub use facade::SelectOpenAPIVersion;
pub use facade::SetLogger;
pub use facade::SetOpenAPIClient;
pub use facade::SetSessionManager;
pub use facade::SetWebsocketClient;
pub use forum::Content;
pub use forum::Format;
pub use forum::ForumAuditResult;
pub use forum::OpenThread;
pub use forum::Post;
pub use forum::PostInfo;
pub use forum::Reply;
pub use forum::ReplyInfo;
pub use forum::Thread;
pub use forum::ThreadInfo;
pub use forum::Title;
pub use intents::Intents;
pub use interaction::Interaction;
pub use interaction::InteractionData;
pub use interaction::InteractionDataType;
pub use interaction::InteractionType;
pub use interaction::SearchInputResolved;
pub use interaction::SearchLayout;
pub use interaction::SearchRecord;
pub use interaction::SearchRsp;
pub use log::Debug;
pub use log::Debugf;
pub use log::DefaultLogger;
pub use log::Error as LogError;
pub use log::Errorf;
pub use log::Info;
pub use log::Infof;
pub use log::Logger;
pub use log::Sync;
pub use log::Warn;
pub use log::Warnf;
pub use manage::C2CManageEvent;
pub use manage::EnterAioEvent;
pub use manage::GroupManageEvent;
pub use manage::ManageEventType;
pub use manage::SubscribeMessageStatusData;
pub use manage::SubscribeMsgTemplateResult;
pub use models::gateway::Ready;
pub use openapi::APIPermissionsAPI;
pub use openapi::AnnouncesAPI;
pub use openapi::AudioAPI;
pub use openapi::Base;
pub use openapi::ChannelAPI;
pub use openapi::ChannelPermissionsAPI;
pub use openapi::DirectMessageAPI;
pub use openapi::DoReqFilterChains;
pub use openapi::DoRespFilterChains;
pub use openapi::FilterContext;
pub use openapi::GuildAPI;
pub use openapi::HTTPFilter;
pub use openapi::InteractionAPI;
pub use openapi::IsSuccessStatus;
pub use openapi::MemberAPI;
pub use openapi::MessageAPI;
pub use openapi::MessageReactionAPI;
pub use openapi::MessageSettingAPI;
pub use openapi::OpenAPI;
pub use openapi::PinsAPI;
pub use openapi::Register as RegisterOpenAPI;
pub use openapi::RegisterReqFilter;
pub use openapi::RegisterRespFilter;
pub use openapi::RoleAPI;
pub use openapi::ScheduleAPI;
pub use openapi::UserAPI;
pub use openapi::WebhookAPI;
pub use openapi::WebsocketAPI;
pub use options::OpenApiOption;
pub use options::Options;
pub use options::WithHideTip;
pub use options::WithURL;
pub use reaction::Emoji as ReactionEmoji;
pub use reaction::MessageReaction;
pub use reaction::MessageReactionPager;
pub use reaction::MessageReactionUsers;
pub use reaction::Reaction;
pub use reaction::ReactionTarget;
pub use reaction::ReactionTargetType;
pub use reaction::ReactionUsers;
pub use remote::ErrGotLockFailed;
pub use remote::ErrProduceFailed;
pub use remote::ErrSessionMarshalFailed;
pub use remote::ErrorNotOk;
pub use remote::Lock;
pub use remote::Option as RemoteOption;
pub use remote::RedisManager;
pub use remote::WithClusterKey;
pub use search::Config as SearchConfig;
pub use search::SimulateSearch;
pub use session_manager::CalcInterval;
pub use session_manager::CanNotIdentify;
pub use session_manager::CanNotIdentifyErrSet;
pub use session_manager::CanNotResume;
pub use session_manager::CanNotResumeErrSet;
pub use session_manager::ChanManager;
pub use session_manager::CheckSessionLimit;
pub use session_manager::NewSessionManager;
pub use session_manager::Session as ManagedSession;
pub use session_manager::SessionManager;
pub use session_manager::calc_interval;
pub use session_manager::new_session_manager;
pub use session_manager::set_session_manager_factory;
pub use signature::Generate;
pub use signature::HeaderSig;
pub use signature::HeaderTimestamp;
pub use signature::Verify;
pub use token::NewQQBotTokenSource;
pub use token::QQBotCredentials;
pub use token::QQBotTokenSource;
pub use token::StartRefreshAccessToken;
pub use token::Token;
pub use token::TypeBearer;
pub use token::TypeQQBot;
pub use version::version_string;
pub use webhook::DefaultGetSecretFunc;
pub use webhook::GenDispatchACK;
pub use webhook::GenHeartbeatACK;
pub use webhook::GenValidationACK;
pub use webhook::HTTPHandler;
pub use websocket::ClientImpl;
pub use websocket::DefaultQueueSize;
pub use websocket::PanicBufLen;
pub use websocket::PanicHandler;
pub use websocket::Register as RegisterWebSocket;
pub use websocket::RegisterHandlers as RegisterWebSocketHandlers;
pub use websocket::RegisterResumeSignal;
pub use websocket::ResumeSignal;
pub use websocket::WebSocket;
pub use constant::*;
pub use models::*;

Modules§

api
Bot API implementation for the QQ Guild Bot API.
audio
Audio-related functionality for QQ Bot
client
Main client implementation for the QQ Guild Bot API.
connection
Connection state management for QQ Bot
constant
Botgo-compatible constants.
error
Error types for the BotRS library.
event
Botgo-style event registration and dispatch helpers.
facade
Top-level facade providing Go-style entry points for the QQ Bot Open API.
forum
Forum-related functionality for QQ Bot
gateway
WebSocket gateway implementation for the QQ Guild Bot API.
http
HTTP client implementation for the QQ Guild Bot API.
intents
Intent flags for controlling which events the bot receives.
interaction
Interaction-related functionality for QQ Bot
log
Botgo-style logging facade backed by tracing.
manage
Management event functionality for QQ Bot
models
Data models for the BotRS library.
openapi
OpenAPI extension points used to register custom client versions and filters.
options
Botgo-compatible OpenAPI request options.
reaction
Reaction-related functionality for QQ Bot
remote
Botgo-compatible remote session-manager facade.
search
Botgo-compatible inline search simulator.
session_manager
Botgo-style websocket session management helpers.
signature
Botgo-compatible ed25519 signature helpers for interaction callbacks.
token
Authentication token management for QQ Guild Bot API.
version
Botgo-compatible SDK version helpers.
webhook
Botgo-compatible interaction webhook helpers.
websocket
Botgo-style websocket facade.

Constants§

DEFAULT_API_URL
Default API base URL for QQ Guild API
DEFAULT_TIMEOUT
Default timeout for HTTP requests in seconds
DEFAULT_WS_URL
Default WebSocket URL for QQ Guild API
SANDBOX_API_URL
Sandbox API base URL for testing
VERSION
The current version of the library