├── rustfmt.toml ├── tests └── test_all_features.sh ├── .gitignore ├── README.md ├── src ├── types.rs ├── error.rs ├── lib.rs ├── logger.rs ├── utils.rs ├── bot │ ├── event │ │ ├── notice_event.rs │ │ ├── request_event.rs │ │ ├── lifecycle_event.rs │ │ ├── msg_send_from_kovi_event.rs │ │ ├── private_msg_event.rs │ │ ├── group_msg_event.rs │ │ ├── admin_msg_event.rs │ │ ├── msg_send_from_server_event.rs │ │ └── msg_event.rs │ ├── runtimebot.rs │ ├── event.rs │ ├── message │ │ └── add.rs │ ├── run.rs │ ├── connect.rs │ ├── handler.rs │ ├── runtimebot │ │ └── kovi_api.rs │ └── message.rs ├── task.rs ├── plugin.rs └── plugin │ └── plugin_builder.rs ├── README_EN.md ├── Cargo.toml ├── .github └── ISSUE_TEMPLATE │ └── bug_report.yml ├── README_Cargo.md └── LICENSE /rustfmt.toml: -------------------------------------------------------------------------------- 1 | empty_item_single_line = false 2 | format_code_in_doc_comments = true 3 | overflow_delimited_expr = true 4 | -------------------------------------------------------------------------------- /tests/test_all_features.sh: -------------------------------------------------------------------------------- 1 | cargo hack test --feature-powerset --exclude-features native-tls-vendored,rustls-tls-webpki-roots,rustls-tls-native-roots -p kovi 2 | 3 | cargo hack clippy --feature-powerset --exclude-features native-tls-vendored,rustls-tls-webpki-roots,rustls-tls-native-roots -p kovi 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | debug/ 4 | target/ 5 | 6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 8 | Cargo.lock 9 | 10 | # These are backup files generated by rustfmt 11 | **/*.rs.bk 12 | 13 | # MSVC Windows builds of rustc generate these, which store debugging information 14 | *.pdb 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | ![Badge](https://img.shields.io/badge/OneBot-11-black) [![群](https://img.shields.io/badge/QQ%E7%BE%A4-857054777-54aeff)](https://qm.qq.com/q/kmpSBOVaCI) 4 | 5 | **简体中文** | [English](README_EN.md) 6 | 7 |
8 | 9 | # Kovi 10 | 11 | Kovi 是一个 OneBot V11 的插件框架,如果你想用 Rust 来开发 OneBot V11 机器人,那么 Kovi 是一个很好的选择。 12 | 13 | 🎯 目标是 Rust 最简单 OneBot 框架!复杂的 Rust 简化写法? Kovi 已经尽力了。 14 | 15 | 🤔 让我数数,文档里面的快速上手,居然9行代码就可以实现一个最简插件。 16 | 17 | 🥁 还有 CLI 工具,方便项目开发。 18 | 19 | 🛍️ 插件商店带来绝佳 Kovi 购物体验,一键接入插件开发者们的包裹📦。 20 | 21 | 😍 本项目文档非常简单易懂,跟着来一遍保证都会了。 22 | 23 | ### ↓ 文档在这里 24 | 25 | [Kovi Docs](https://thricecola.github.io/kovi-doc/) 26 | 27 | ### ↓ 商店在这里 28 | 29 | [Kovi Shop](https://thricecola.github.io/kovi-doc/start/plugins.html) 30 | 31 | **注意⚠️,项目目前只支持 OneBot V11 正向 WebSocket 协议** 32 | 33 | 球球啦,点个星星⭐吧,这是一个很大的鼓励。 34 | 35 | 还有欢迎加Q群玩。 36 | -------------------------------------------------------------------------------- /src/types.rs: -------------------------------------------------------------------------------- 1 | use crate::{ApiReturn, bot::SendApi}; 2 | use std::{pin::Pin, sync::Arc}; 3 | use tokio::sync::oneshot; 4 | 5 | pub(crate) type KoviAsyncFn = dyn Fn() -> Pin + Send>> + Send + Sync; 6 | 7 | pub type PinFut = Pin + Send>>; 8 | 9 | // pub type MsgFn = Arc) -> PinFut + Send + Sync>; 10 | 11 | // pub type NoticeFn = Arc) -> PinFut + Send + Sync>; 12 | 13 | // pub type RequestFn = Arc) -> PinFut + Send + Sync>; 14 | // 15 | // pub type EventFn = Arc) -> PinFut + Send + Sync>; 16 | 17 | pub type NoArgsFn = Arc PinFut + Send + Sync>; 18 | 19 | pub type ApiOneshotSender = oneshot::Sender>; 20 | pub type ApiOneshotReceiver = oneshot::Receiver>; 21 | 22 | pub type ApiAndOneshot = ( 23 | SendApi, 24 | Option>>, 25 | ); 26 | 27 | pub type ApiAndRuturn = (SendApi, Result); 28 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use thiserror::Error; 2 | 3 | #[derive(Error, Debug)] 4 | pub enum MessageError { 5 | /// 解析出错 6 | #[error("Parse error: {0}")] 7 | ParseError(String), 8 | // #[error("Error, and no one knows why something went wrong")] 9 | // UnknownError(), 10 | } 11 | 12 | #[derive(Error, Debug)] 13 | pub enum BotError { 14 | /// 没有寻找到插件 15 | #[error("Plugin not found: {0}")] 16 | PluginNotFound(String), 17 | #[error("Bot's Weak reference has expired")] 18 | RefExpired, 19 | } 20 | 21 | #[derive(Error, Debug)] 22 | pub enum BotBuildError { 23 | /// 解析TOML文件失败 24 | #[error("Failed to parse TOML:\n{0}\nPlease reload the config file")] 25 | TomlParseError(String), 26 | /// 无法创建配置文件 27 | #[error("Failed to create config file: {0}")] 28 | FileCreateError(String), 29 | /// 无法读取TOML文件 30 | #[error("Failed to read TOML file: {0}")] 31 | FileReadError(String), 32 | } 33 | 34 | #[derive(Error, Debug)] 35 | pub enum EventBuildError { 36 | /// 解析出错 37 | #[error("Parse error: {0}")] 38 | ParseError(String), 39 | } 40 | -------------------------------------------------------------------------------- /README_EN.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | ![Badge](https://img.shields.io/badge/OneBot-11-black) [![群](https://img.shields.io/badge/QQ%E7%BE%A4-857054777-54aeff)](https://qm.qq.com/q/kmpSBOVaCI) 4 | 5 | [简体中文](README.md) | **English** 6 | 7 |
8 | 9 | # Kovi 10 | 11 | Kovi is a plugin framework for OneBot V11. If you want to develop OneBot V11 bots using Rust, Kovi is a great choice. 12 | 13 | 🎯 The goal is to create the simplest OneBot framework in Rust! Simplifying complex Rust syntax? Kovi has done its best. 14 | 15 | 🤔 Let me count, the quick start in the documentation only requires 9 lines of code to create the simplest plugin. 16 | 17 | 🥁 There’s also a CLI tool to make project development easier. 18 | 19 | 🛍️ The plugin shop provides an excellent Kovi shopping experience, allowing you to easily access packages from plugin developers 📦. 20 | 21 | 😍 The project documentation is very simple and easy to understand. Follow it and you’ll be good to go. 22 | 23 | ### ↓ Documentation is here 24 | 25 | [Kovi Docs](https://thricecola.github.io/kovi-doc/) 26 | 27 | ### ↓ The shop is here 28 | 29 | [Kovi Shop](https://kovi.thricecola.com/start/plugins.html) 30 | 31 | **Note ⚠️: Currently, the project only supports OneBot V11's forward WebSocket protocol.** 32 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "kovi" 3 | version = "0.12.6" 4 | authors = ["ThriceCola "] 5 | edition = "2024" 6 | description = "A OneBot V11 bot plugin framework" 7 | documentation = "https://thricecola.github.io/kovi-doc/" 8 | readme = "README_Cargo.md" 9 | repository = "https://github.com/thricecola/Kovi" 10 | license = "MPL-2.0" 11 | keywords = ["framework", "kovi", "onebot"] 12 | 13 | [lib] 14 | name = "kovi" 15 | path = "src/lib.rs" 16 | 17 | [dependencies] 18 | ahash = "0.8" 19 | chrono = "0.4" 20 | croner = "2" 21 | dialoguer = { version = "0.11", features = ["fuzzy-select"] } 22 | env_logger = { version = "0.11", default-features = false, features = [ 23 | "auto-color", 24 | "color", 25 | ], optional = true } 26 | futures-util = "0.3" 27 | http = "1" 28 | kovi-macros = { version = "0.5" } 29 | log = "0.4" 30 | parking_lot = "0.12" 31 | rand = "0.9" 32 | serde = { version = "1", features = ["derive"] } 33 | serde_json = "1" 34 | thiserror = "2" 35 | tokio = { version = "1", features = ["full", "windows-sys"] } 36 | tokio-tungstenite = "0.26" 37 | toml = "0.8" 38 | toml_edit = "0.22" 39 | 40 | [features] 41 | cqstring = [] 42 | default = ["logger", "plugin-access-control", "save_bot_status"] 43 | logger = ["env_logger"] 44 | native-tls-vendored = ["tokio-tungstenite/native-tls-vendored"] 45 | plugin-access-control = [] 46 | rustls-tls-native-roots = ["tokio-tungstenite/rustls-tls-native-roots"] 47 | rustls-tls-webpki-roots = ["tokio-tungstenite/rustls-tls-webpki-roots"] 48 | save_bot_admin = [] 49 | save_bot_status = ["save_bot_admin", "save_plugin_status"] 50 | save_plugin_status = [] 51 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # Kovi 2 | //! 3 | //! A OneBot V11 bot framework developed using Rust. 4 | //! 5 | //! More documentation can be found at [Github-Kovi](https://github.com/ThriceCola/Kovi) Or [Kovi-doc](https://thricecola.github.io/kovi-doc/) 6 | //! 7 | //! 中文文档或更多文档请查看[Github-Kovi](https://github.com/ThriceCola/Kovi) 和 [Kovi-doc](https://thricecola.github.io/kovi-doc/) 8 | #![deny(clippy::unwrap_used)] 9 | 10 | /// Everything about bots is inside 11 | pub mod bot; 12 | /// 一些错误枚举 13 | pub mod error; 14 | /// 控制台输出日志 15 | pub mod logger; 16 | /// 关于插件的一切 17 | pub mod plugin; 18 | /// task 提供 kovi 运行时的多线程处理 19 | pub mod task; 20 | /// 这里包含一些集成类型 21 | pub mod types; 22 | /// 提供一些方便的插件开发函数 23 | pub mod utils; 24 | 25 | pub use bot::ApiReturn; 26 | pub use bot::Bot; 27 | pub use bot::event; 28 | pub use bot::message::Message; 29 | pub use bot::runtimebot::RuntimeBot; 30 | pub use error::MessageError; 31 | pub use kovi_macros::plugin; 32 | pub use plugin::plugin_builder::PluginBuilder; 33 | pub use plugin::plugin_builder::event::MsgEvent; 34 | pub use plugin::plugin_builder::event::NoticeEvent; 35 | pub use plugin::plugin_builder::event::RequestEvent; 36 | pub use task::spawn; 37 | 38 | #[deprecated(since = "0.11.0", note = "请使用 `MsgEvent` 代替")] 39 | pub type AllMsgEvent = bot::plugin_builder::event::MsgEvent; 40 | #[deprecated(since = "0.11.0", note = "请使用 `NoticeEvent` 代替")] 41 | pub type AllNoticeEvent = bot::plugin_builder::event::NoticeEvent; 42 | #[deprecated(since = "0.11.0", note = "请使用 `RequestEvent` 代替")] 43 | pub type AllRequestEvent = bot::plugin_builder::event::RequestEvent; 44 | 45 | pub use chrono; 46 | pub use croner; 47 | pub use futures_util; 48 | pub use log; 49 | pub use serde_json; 50 | pub use tokio; 51 | pub use toml; 52 | 53 | pub(crate) use crate::bot::run::RUNTIME as RT; 54 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug 反馈 3 | description: 报告可能的 Kovi 异常行为 4 | title: "[BUG] " 5 | labels: potential bug 6 | body: 7 | - type: markdown 8 | attributes: 9 | value: | 10 | 欢迎来到 Kovi 的 Issue Tracker!请填写以下表格来提交 Bug。 11 | 在提交新的 Bug 反馈前,请确保您: 12 | * 已经搜索了现有的 issues,并且没有找到可以解决您问题的方法 13 | * 不与现有的某一 issue 重复 14 | 15 | - type: input 16 | id: system-version 17 | attributes: 18 | label: 系统信息 19 | description: 运行 Kovi 的系统信息 20 | placeholder: Windows 10 Pro Workstation 22H2 21 | validations: 22 | required: true 23 | - type: input 24 | id: napcat-version 25 | attributes: 26 | label: Kovi 版本 27 | description: 可在 Cargo.toml 中找到 28 | placeholder: 1.0.0 29 | validations: 30 | required: true 31 | - type: input 32 | id: onebot-server-version 33 | attributes: 34 | label: OneBot 服务端 35 | description: 连接至 Kovi 的服务端版本信息 36 | placeholder: Napcat 2.5.0 37 | validations: 38 | required: true 39 | - type: textarea 40 | id: what-happened 41 | attributes: 42 | label: 发生了什么? 43 | description: 填写你认为的 Kovi 的不正常行为 44 | validations: 45 | required: true 46 | - type: textarea 47 | id: how-reproduce 48 | attributes: 49 | label: 如何复现 50 | description: 填写应当如何操作才能触发这个不正常行为 51 | placeholder: | 52 | 1. xxx 53 | 2. xxx 54 | 3. xxx 55 | validations: 56 | required: true 57 | - type: textarea 58 | id: what-expected 59 | attributes: 60 | label: 期望的结果? 61 | description: 填写你认为 Kovi 应当执行的正常行为 62 | validations: 63 | required: true 64 | - type: textarea 65 | id: kovi-log 66 | attributes: 67 | label: kovi 运行日志 68 | description: 粘贴相关日志内容到此处,通过从 kovi.conf.json 中打开 debug 模式获取更详细的日志 69 | render: shell 70 | validations: 71 | required: true 72 | 73 | - type: textarea 74 | id: any 75 | attributes: 76 | label: 你想填写的其它内容 77 | description: 填写其它想填写的内容 78 | -------------------------------------------------------------------------------- /src/logger.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "logger")] 2 | pub fn set_logger() { 3 | use chrono::Local; 4 | use log::Level; 5 | use std::io::Write; 6 | 7 | macro_rules! _format { 8 | ($level:literal, $timestamp:ident, $record:ident, $($color:ident),+ $(,)?) => {{ 9 | let color = dialoguer::console::style($level)$(.$color())+; 10 | format!("[{}] [{}]: {}", color, $timestamp, $record.args()) 11 | }}; 12 | } 13 | 14 | let init = env_logger::Builder::from_default_env() 15 | .format(|buf, record| { 16 | let t = Local::now().format("%m-%d %H:%M:%S"); 17 | 18 | match record.level() { 19 | Level::Info => { 20 | writeln!(buf, "[{t}] {}", record.args()) 21 | } 22 | Level::Debug => { 23 | writeln!(buf, "{}", _format!("Debug", t, record, yellow, italic)) 24 | } 25 | Level::Warn => { 26 | writeln!(buf, "{}", _format!("Warn", t, record, yellow)) 27 | } 28 | Level::Error => { 29 | writeln!(buf, "{}", _format!("Error", t, record, red)) 30 | } 31 | Level::Trace => { 32 | writeln!(buf, "{}", _format!("Trace", t, record, magenta)) 33 | } 34 | } 35 | }) 36 | .try_init(); 37 | 38 | if let Err(e) = init { 39 | println!( 40 | "Kovi init env_logger failed: {e}. Very likely you've already started a logger" 41 | ); 42 | } 43 | } 44 | 45 | pub fn try_set_logger() { 46 | #[cfg(feature = "logger")] 47 | set_logger(); 48 | } 49 | 50 | #[cfg(feature = "logger")] 51 | #[test] 52 | fn test_logger() { 53 | unsafe { 54 | std::env::set_var("RUST_LOG", "trace"); 55 | } 56 | 57 | // Initialize the logger 58 | try_set_logger(); 59 | 60 | // Test different log levels 61 | log::info!("This is an info message - should appear without color"); 62 | log::debug!("This is a debug message - should appear in yellow"); 63 | log::warn!("This is a warning message - should appear in yellow"); 64 | log::error!("This is an error message - should appear in red"); 65 | log::trace!("This is a trace message - should appear in red"); 66 | } 67 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use serde::{Serialize, de::DeserializeOwned}; 2 | use std::{ 3 | fs::{self, File}, 4 | io::{Read, Write}, 5 | path::Path, 6 | }; 7 | 8 | fn save_data(data: &[u8], file_path: &Path) -> Result<(), Box> { 9 | if let Some(parent) = file_path.parent() 10 | && !parent.exists() 11 | { 12 | fs::create_dir_all(parent)?; 13 | } 14 | 15 | let mut file = File::create(file_path)?; 16 | file.write_all(data)?; 17 | 18 | Ok(()) 19 | } 20 | 21 | /// 加载本地json数据,如果没有则保存传入的数据进指定路径 22 | pub fn load_json_data(data: T, file_path: P) -> Result> 23 | where 24 | T: Serialize + DeserializeOwned, 25 | P: AsRef, 26 | { 27 | if !file_path.as_ref().exists() { 28 | let serialized_data = serde_json::to_string(&data)?; 29 | save_data(serialized_data.as_bytes(), file_path.as_ref())?; 30 | return Ok(data); 31 | } 32 | 33 | let mut file = File::open(&file_path)?; 34 | let mut contents = String::new(); 35 | file.read_to_string(&mut contents)?; 36 | let deserialized_data = serde_json::from_str(&contents)?; 37 | 38 | Ok(deserialized_data) 39 | } 40 | 41 | /// 加载本地toml数据,如果没有则保存传入的数据进指定路径 42 | pub fn load_toml_data(data: T, file_path: P) -> Result> 43 | where 44 | T: Serialize + DeserializeOwned, 45 | P: AsRef, 46 | { 47 | if !file_path.as_ref().exists() { 48 | let serialized_data = toml::to_string(&data)?; 49 | save_data(serialized_data.as_bytes(), file_path.as_ref())?; 50 | return Ok(data); 51 | } 52 | 53 | let mut file = File::open(file_path)?; 54 | let mut contents = String::new(); 55 | file.read_to_string(&mut contents)?; 56 | let deserialized_data = toml::from_str(&contents)?; 57 | 58 | Ok(deserialized_data) 59 | } 60 | 61 | /// 将json数据保存在传入的地址 62 | pub fn save_json_data(data: &T, file_path: P) -> Result<(), Box> 63 | where 64 | T: Serialize, 65 | P: AsRef, 66 | { 67 | let serialized_data = serde_json::to_string(data)?; 68 | save_data(serialized_data.as_bytes(), file_path.as_ref())?; 69 | Ok(()) 70 | } 71 | 72 | /// 将toml数据保存在传入的地址 73 | pub fn save_toml_data(data: &T, file_path: P) -> Result<(), Box> 74 | where 75 | T: Serialize, 76 | P: AsRef, 77 | { 78 | let serialized_data = toml::to_string(data)?; 79 | save_data(serialized_data.as_bytes(), file_path.as_ref())?; 80 | Ok(()) 81 | } 82 | 83 | /// 计算pskey值 84 | pub fn calculate_pskey(skey: &str) -> u32 { 85 | let mut hash: u32 = 5381; 86 | for character in skey.chars() { 87 | hash = (hash << 5) 88 | .wrapping_add(hash) 89 | .wrapping_add(character as u32); 90 | } 91 | hash & 0x7fffffff 92 | } 93 | -------------------------------------------------------------------------------- /src/bot/event/notice_event.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | bot::{ 3 | BotInformation, 4 | event::InternalEvent, 5 | plugin_builder::event::{Event, PostType}, 6 | }, 7 | error::EventBuildError, 8 | types::ApiAndOneshot, 9 | }; 10 | use serde_json::{Value, value::Index}; 11 | use tokio::sync::mpsc; 12 | 13 | #[derive(Debug, Clone)] 14 | pub struct NoticeEvent { 15 | /// 事件发生的时间戳 16 | pub time: i64, 17 | /// 收到事件的机器人 登陆号 18 | pub self_id: i64, 19 | /// 上报类型 20 | pub post_type: PostType, 21 | /// 通知类型 22 | pub notice_type: String, 23 | 24 | /// 原始的onebot消息,已处理成json格式 25 | pub original_json: Value, 26 | } 27 | impl Event for NoticeEvent { 28 | fn de( 29 | event: &InternalEvent, 30 | _: &BotInformation, 31 | _: &mpsc::Sender, 32 | ) -> Option { 33 | let InternalEvent::OneBotEvent(json_str) = event else { 34 | return None; 35 | }; 36 | Self::new(json_str).ok() 37 | } 38 | } 39 | 40 | impl NoticeEvent { 41 | pub(crate) fn new(msg: &str) -> Result { 42 | let temp: Value = 43 | serde_json::from_str(msg).map_err(|e| EventBuildError::ParseError(e.to_string()))?; 44 | let time = temp 45 | .get("time") 46 | .and_then(Value::as_i64) 47 | .ok_or(EventBuildError::ParseError("time".to_string()))?; 48 | let self_id = temp 49 | .get("self_id") 50 | .and_then(Value::as_i64) 51 | .ok_or(EventBuildError::ParseError("self_id".to_string()))?; 52 | let post_type = temp 53 | .get("post_type") 54 | .and_then(|v| serde_json::from_value::(v.clone()).ok()) 55 | .ok_or(EventBuildError::ParseError("Invalid post_type".to_string()))?; 56 | let notice_type = temp 57 | .get("notice_type") 58 | .and_then(Value::as_str) 59 | .map(String::from) 60 | .ok_or(EventBuildError::ParseError("notice_type".to_string()))?; 61 | Ok(NoticeEvent { 62 | time, 63 | self_id, 64 | post_type, 65 | notice_type, 66 | original_json: temp, 67 | }) 68 | } 69 | } 70 | 71 | impl NoticeEvent { 72 | /// 直接从原始的 Json Value 获取某值 73 | /// 74 | /// # example 75 | /// 76 | /// ```ignore 77 | /// use kovi::PluginBuilder; 78 | /// 79 | /// PluginBuilder::on_notice(|event| async move { 80 | /// let time = event.get("time").and_then(|v| v.as_i64()).unwrap(); 81 | /// 82 | /// assert_eq!(time, event.time); 83 | /// }); 84 | /// ``` 85 | pub fn get(&self, index: I) -> Option<&Value> { 86 | self.original_json.get(index) 87 | } 88 | } 89 | 90 | impl std::ops::Index for NoticeEvent 91 | where 92 | I: Index, 93 | { 94 | type Output = Value; 95 | 96 | fn index(&self, index: I) -> &Self::Output { 97 | &self.original_json[index] 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/bot/event/request_event.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | bot::{ 3 | BotInformation, 4 | event::InternalEvent, 5 | plugin_builder::event::{Event, PostType}, 6 | }, 7 | error::EventBuildError, 8 | types::ApiAndOneshot, 9 | }; 10 | use serde_json::{Value, value::Index}; 11 | use tokio::sync::mpsc; 12 | 13 | #[derive(Debug, Clone)] 14 | pub struct RequestEvent { 15 | /// 事件发生的时间戳 16 | pub time: i64, 17 | /// 收到事件的机器人 登陆号 18 | pub self_id: i64, 19 | /// 上报类型 20 | pub post_type: PostType, 21 | /// 请求类型 22 | pub request_type: String, 23 | 24 | /// 原始的onebot消息,已处理成json格式 25 | pub original_json: Value, 26 | } 27 | impl Event for RequestEvent { 28 | fn de( 29 | event: &InternalEvent, 30 | _: &BotInformation, 31 | _: &mpsc::Sender, 32 | ) -> Option { 33 | let InternalEvent::OneBotEvent(json_str) = event else { 34 | return None; 35 | }; 36 | 37 | Self::new(json_str).ok() 38 | } 39 | } 40 | 41 | impl RequestEvent { 42 | pub(crate) fn new(msg: &str) -> Result { 43 | let temp: Value = 44 | serde_json::from_str(msg).map_err(|e| EventBuildError::ParseError(e.to_string()))?; 45 | let time = temp 46 | .get("time") 47 | .and_then(Value::as_i64) 48 | .ok_or(EventBuildError::ParseError("time".to_string()))?; 49 | let self_id = temp 50 | .get("self_id") 51 | .and_then(Value::as_i64) 52 | .ok_or(EventBuildError::ParseError("self_id".to_string()))?; 53 | let post_type = temp 54 | .get("post_type") 55 | .and_then(|v| serde_json::from_value::(v.clone()).ok()) 56 | .ok_or(EventBuildError::ParseError("Invalid post_type".to_string()))?; 57 | let request_type = temp 58 | .get("request_type") 59 | .and_then(Value::as_str) 60 | .map(String::from) 61 | .ok_or(EventBuildError::ParseError("request_type".to_string()))?; 62 | Ok(RequestEvent { 63 | time, 64 | self_id, 65 | post_type, 66 | request_type, 67 | original_json: temp, 68 | }) 69 | } 70 | } 71 | 72 | impl RequestEvent { 73 | /// 直接从原始的 Json Value 获取某值 74 | /// 75 | /// # example 76 | /// 77 | /// ```ignore 78 | /// use kovi::PluginBuilder; 79 | /// 80 | /// PluginBuilder::on_request(|event| async move { 81 | /// let time = event.get("time").and_then(|v| v.as_i64()).unwrap(); 82 | /// 83 | /// assert_eq!(time, event.time); 84 | /// }); 85 | /// ``` 86 | pub fn get(&self, index: I) -> Option<&Value> { 87 | self.original_json.get(index) 88 | } 89 | } 90 | 91 | impl std::ops::Index for RequestEvent 92 | where 93 | I: Index, 94 | { 95 | type Output = Value; 96 | 97 | fn index(&self, index: I) -> &Self::Output { 98 | &self.original_json[index] 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/bot/event/lifecycle_event.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | ApiReturn, 3 | bot::{ 4 | BotInformation, SendApi, 5 | event::InternalEvent, 6 | plugin_builder::event::{Event, PostType}, 7 | }, 8 | types::ApiAndOneshot, 9 | }; 10 | use log::{error, info}; 11 | use serde::{Deserialize, Serialize}; 12 | use serde_json::json; 13 | use tokio::sync::{mpsc, oneshot}; 14 | 15 | #[derive(Debug, Clone, Deserialize)] 16 | pub struct LifecycleEvent { 17 | pub meta_event_type: String, 18 | pub post_type: PostType, 19 | pub self_id: i64, 20 | pub time: i64, 21 | pub sub_type: LifecycleAction, 22 | } 23 | 24 | #[derive(Debug, Copy, Clone, Deserialize, Serialize)] 25 | #[serde(rename_all = "lowercase")] 26 | pub enum LifecycleAction { 27 | Enable, 28 | Disable, 29 | Connect, 30 | } 31 | 32 | impl Event for LifecycleEvent { 33 | fn de( 34 | event: &InternalEvent, 35 | _: &BotInformation, 36 | _: &tokio::sync::mpsc::Sender, 37 | ) -> Option 38 | where 39 | Self: Sized, 40 | { 41 | let InternalEvent::OneBotEvent(json_str) = event else { 42 | return None; 43 | }; 44 | let event: LifecycleEvent = serde_json::from_str(json_str).ok()?; 45 | if event.meta_event_type == "lifecycle" { 46 | Some(event) 47 | } else { 48 | None 49 | } 50 | } 51 | } 52 | 53 | pub(crate) async fn handler_lifecycle_log_bot_enable(api_tx_: mpsc::Sender) { 54 | let api_msg = SendApi::new("get_login_info", json!({})); 55 | 56 | #[allow(clippy::type_complexity)] 57 | let (api_tx, api_rx): ( 58 | oneshot::Sender>, 59 | oneshot::Receiver>, 60 | ) = oneshot::channel(); 61 | 62 | api_tx_ 63 | .send((api_msg, Some(api_tx))) 64 | .await 65 | .expect("The api_tx channel closed"); 66 | 67 | let receive = match api_rx.await { 68 | Ok(v) => v, 69 | Err(e) => { 70 | error!("Lifecycle Error, get bot info failed: {e}"); 71 | return; 72 | } 73 | }; 74 | 75 | let self_info_value = match receive { 76 | Ok(v) => v, 77 | Err(e) => { 78 | error!("Lifecycle Error, get bot info failed: {e}"); 79 | return; 80 | } 81 | }; 82 | 83 | let self_id = match self_info_value.data.get("user_id") { 84 | Some(user_id) => match user_id.as_i64() { 85 | Some(id) => id, 86 | None => { 87 | error!("Expected 'user_id' to be an integer"); 88 | return; 89 | } 90 | }, 91 | None => { 92 | error!("Missing 'user_id' in self_info_value data"); 93 | return; 94 | } 95 | }; 96 | let self_name = match self_info_value.data.get("nickname") { 97 | Some(nickname) => nickname.to_string(), 98 | None => { 99 | error!("Missing 'nickname' in self_info_value data"); 100 | return; 101 | } 102 | }; 103 | info!( 104 | "Bot connection successful,Nickname:{self_name},ID:{self_id}" 105 | ); 106 | } 107 | -------------------------------------------------------------------------------- /src/task.rs: -------------------------------------------------------------------------------- 1 | use crate::{RT, plugin::PLUGIN_NAME}; 2 | use ahash::RandomState; 3 | use parking_lot::Mutex; 4 | use std::{ 5 | borrow::BorrowMut, 6 | collections::HashMap, 7 | future::Future, 8 | sync::{Arc, LazyLock}, 9 | time::Duration, 10 | }; 11 | use tokio::{ 12 | task::{AbortHandle, JoinHandle}, 13 | time::interval, 14 | }; 15 | 16 | pub(crate) static TASK_MANAGER: LazyLock = LazyLock::new(TaskManager::init); 17 | 18 | pub(crate) struct TaskManager { 19 | pub(crate) handles: Arc>, 20 | } 21 | 22 | impl TaskManager { 23 | pub(crate) fn init() -> Self { 24 | let handles = Arc::new(Mutex::new(TaskAbortHandles::default())); 25 | 26 | let handles_clone = handles.clone(); 27 | RT.spawn(async move { 28 | let mut interval = interval(Duration::from_secs(20)); // 每秒清理一次 29 | loop { 30 | interval.tick().await; 31 | log::debug!("Kovi task thread is cleaning up task handles"); 32 | 33 | let mut handles_lock = handles_clone.lock(); 34 | 35 | handles_lock.clear(); 36 | } 37 | }); 38 | 39 | Self { handles } 40 | } 41 | 42 | pub(crate) fn disable_plugin(&self, plugin_name: &str) { 43 | let mut task_manager = self.handles.lock(); 44 | 45 | let map = task_manager.map.borrow_mut(); 46 | let vec = match map.get(plugin_name) { 47 | Some(v) => v, 48 | None => return, 49 | }; 50 | 51 | for abort in vec { 52 | abort.abort(); 53 | } 54 | } 55 | } 56 | 57 | #[derive(Debug, Clone)] 58 | pub(crate) struct TaskAbortHandles { 59 | map: HashMap, RandomState>, 60 | } 61 | 62 | impl Default for TaskAbortHandles { 63 | fn default() -> Self { 64 | Self { 65 | map: HashMap::with_hasher(RandomState::new()), 66 | } 67 | } 68 | } 69 | 70 | impl TaskAbortHandles { 71 | pub(crate) fn clear(&mut self) { 72 | for vec in self.map.values_mut() { 73 | vec.retain(|abort| !abort.is_finished()); 74 | vec.shrink_to_fit(); 75 | } 76 | } 77 | } 78 | 79 | /// 生成一个新的异步线程并立即运行,另外,这个线程关闭句柄会被交给 Kovi 管理。 80 | /// 81 | /// **如果在 Kovi 管理之外的地方(新的tokio线程或者系统线程)运行此函数,此函数会 panic!** 82 | /// 83 | /// 由 Kovi 管理的地方: 84 | /// 85 | /// 1. 有 #[kovi::plugin] 的插件入口函数。 86 | /// 2. 插件的监听闭包。 87 | /// 3. 由 kovi::spawn() 创建的新线程。 88 | /// 89 | /// # panic! 90 | /// 91 | /// 如果在 Kovi 管理之外的地方(tokio线程或者系统线程)运行此函数,此函数会 panic! 92 | pub fn spawn(future: F) -> JoinHandle 93 | where 94 | F: Future + Send + 'static, 95 | F::Output: Send + 'static, 96 | { 97 | PLUGIN_NAME.with(|name| { 98 | let join = { 99 | let name = name.clone(); 100 | RT.spawn(PLUGIN_NAME.scope(name, future)) 101 | }; 102 | 103 | let about_join = join.abort_handle(); 104 | 105 | task_manager_handler(name, about_join); 106 | 107 | join 108 | }) 109 | } 110 | 111 | pub(crate) fn task_manager_handler(name: &str, about_join: AbortHandle) { 112 | let mut task_abort_handles = TASK_MANAGER.handles.lock(); 113 | 114 | let aborts = task_abort_handles.map.entry(name.to_string()).or_default(); 115 | 116 | aborts.push(about_join); 117 | } 118 | -------------------------------------------------------------------------------- /src/bot/runtimebot.rs: -------------------------------------------------------------------------------- 1 | use crate::types::{ApiAndOneshot, ApiOneshotReceiver, ApiOneshotSender}; 2 | 3 | use super::{ApiReturn, Bot, Host, SendApi}; 4 | use log::error; 5 | use parking_lot::RwLock; 6 | use serde_json::Value; 7 | use std::sync::Weak; 8 | use tokio::sync::{mpsc, oneshot}; 9 | 10 | pub mod kovi_api; 11 | pub mod onebot_api; 12 | 13 | pub use kovi_api::SetAdmin; 14 | 15 | /// 运行时的Bot,可以用来发送api,需要从PluginBuilder的.get_runtime_bot()获取。 16 | /// # Examples 17 | /// ```ignore 18 | /// use kovi::PluginBuilder; 19 | /// 20 | /// let bot = PluginBuilder::get_runtime_bot(); 21 | /// let user_id = bot.get_main_admin().unwrap(); 22 | /// 23 | /// bot.send_private_msg(user_id, "bot online") 24 | /// ``` 25 | #[derive(Clone)] 26 | pub struct RuntimeBot { 27 | pub host: Host, 28 | pub port: u16, 29 | 30 | pub(crate) bot: Weak>, 31 | pub(crate) plugin_name: String, 32 | pub api_tx: mpsc::Sender, 33 | } 34 | 35 | /// 提供给拓展 API 插件开发者的异步 API 请求发送函数,返回一个 Future ,用于等待在 Kovi 中已经缓存好的API响应。 36 | pub fn send_api_request_with_response( 37 | api_tx: &mpsc::Sender, 38 | send_api: SendApi, 39 | ) -> impl std::future::Future> { 40 | let api_rx = send_api_request(api_tx, send_api); 41 | send_api_await_response(api_rx) 42 | } 43 | 44 | /// 提供给拓展 API 插件开发者的 API 请求发送函数,返回一个 API 通道,可以用于等待 API 响应。 45 | pub fn send_api_request( 46 | api_tx: &mpsc::Sender, 47 | send_api: SendApi, 48 | ) -> ApiOneshotReceiver { 49 | let (api_tx_, api_rx): (ApiOneshotSender, ApiOneshotReceiver) = oneshot::channel(); 50 | 51 | if let Err(e) = api_tx.try_send((send_api, Some(api_tx_))) { 52 | match e { 53 | mpsc::error::TrySendError::Full(v) => { 54 | log::trace!("RuntimeBot Api Queue Full, spawn new task to send"); 55 | 56 | let api_tx = api_tx.clone(); 57 | 58 | tokio::task::spawn(async move { 59 | if let Err(e) = api_tx.send(v).await { 60 | error!("The mpsc sender failed to send API request: {e}"); 61 | } 62 | }); 63 | } 64 | mpsc::error::TrySendError::Closed(_) => { 65 | log::error!("RuntimeBot Api Queue Closed"); 66 | } 67 | } 68 | }; 69 | 70 | api_rx 71 | } 72 | 73 | /// 提供给拓展 API 插件开发者的 API 请求发送函数,忽略返回值。 74 | pub fn send_api_request_with_forget(api_tx: &mpsc::Sender, send_api: SendApi) { 75 | if let Err(e) = api_tx.try_send((send_api, None)) { 76 | match e { 77 | mpsc::error::TrySendError::Full(v) => { 78 | log::trace!("RuntimeBot Api Queue Full, spawn new task to send"); 79 | 80 | let api_tx = api_tx.clone(); 81 | 82 | tokio::task::spawn(async move { 83 | if let Err(e) = api_tx.send(v).await { 84 | error!("The mpsc sender failed to send API request: {e}"); 85 | } 86 | }); 87 | } 88 | mpsc::error::TrySendError::Closed(_) => { 89 | log::error!("RuntimeBot Api Queue Closed"); 90 | } 91 | } 92 | }; 93 | } 94 | 95 | /// 一个异步 Future ,传入一个 API 通道,可以用于等待在 Kovi 中缓存好的 API 响应。 96 | pub async fn send_api_await_response(api_rx: ApiOneshotReceiver) -> Result { 97 | match api_rx.await { 98 | Ok(v) => v, 99 | Err(e) => { 100 | error!("{e}"); 101 | panic!() 102 | } 103 | } 104 | } 105 | 106 | /// 实现这个 trait, 让用户方便地发送 API 的方法。 107 | pub trait CanSendApi { 108 | fn __get_api_tx(&self) -> &mpsc::Sender; 109 | 110 | /// 发送拓展 Api, 此方法不关注返回值,返回值将丢弃。 111 | /// 112 | /// 如需要返回值,请使用 `send_api_return()` 113 | /// 114 | /// # Arguments 115 | /// 116 | /// `action`: 拓展 Api 的方法名 117 | /// 118 | /// `params`: 参数 119 | fn send_api(&self, action: &str, params: Value) { 120 | let send_api = SendApi::new(action, params); 121 | send_api_request_with_forget(self.__get_api_tx(), send_api) 122 | } 123 | /// 发送拓展 Api, 此方法关注返回值。 124 | /// 125 | /// 如不需要返回值,推荐使用 `send_api()` 126 | /// 127 | /// # Arguments 128 | /// 129 | /// `action`: 拓展 Api 的方法名 130 | /// 131 | /// `params`: 参数 132 | fn send_api_return( 133 | &self, 134 | action: &str, 135 | params: Value, 136 | ) -> impl std::future::Future> { 137 | let send_api = SendApi::new(action, params); 138 | send_api_request_with_response(self.__get_api_tx(), send_api) 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /README_Cargo.md: -------------------------------------------------------------------------------- 1 | **English** | [简体中文](https://thricecola.github.io/kovi-doc/) 2 | 3 | # Kovi 4 | 5 | Kovi is a plugin framework for OneBot V11. If you want to develop OneBot V11 bots using Rust, Kovi is a great choice. 6 | 7 | 🎯 The goal is to create the simplest OneBot framework in Rust! Simplifying complex Rust syntax? Kovi has done its best. 8 | 9 | 🤔 Let me count, the quick start in the documentation only requires 9 lines of code to create the simplest plugin. 10 | 11 | 🥁 There’s also a CLI tool to make project development easier. 12 | 13 | 🛍️ The plugin shop provides an excellent Kovi shopping experience, allowing you to easily access packages from plugin developers 📦. 14 | 15 | 😍 The project documentation is very simple and easy to understand. Follow it and you’ll be good to go. 16 | 17 | ### ↓ Documentation is here 18 | 19 | [Kovi Docs](https://thricecola.github.io/kovi-doc/) 20 | 21 | ### ↓ The shop is here 22 | 23 | [Kovi Shop](https://kovi.thricecola.com/start/plugins.html) 24 | 25 | **Note ⚠️: Currently, the project only supports OneBot V11's forward WebSocket protocol.** 26 | 27 | ## Getting Started 28 | 29 | It's recommended to use `kovi-cli` to manage your Kovi bot project. 30 | 31 | ```bash 32 | cargo install kovi-cli 33 | ``` 34 | 35 | 1. Create a basic Rust project and add the framework. 36 | 37 | ```bash 38 | cargo kovi new my-kovi-bot 39 | cd ./my-kovi-bot 40 | ``` 41 | 42 | 2. You will see that a bot instance has been generated in **src/main.rs**. 43 | 44 | ```rust 45 | use kovi::build_bot; 46 | 47 | fn main() { 48 | let bot = build_bot!(); 49 | bot.run() 50 | } 51 | ``` 52 | 53 | On your first run, during `build_bot`, you'll be prompted to enter some information to create the `kovi.conf.toml` file, which is required for Kovi to run. 54 | 55 | ``` 56 | ✔ What is the type of the host of the OneBot server? · IPv4 57 | 58 | ✔ What is the IP of the OneBot server? · 127.0.0.1 59 | (Default: 127.0.0.1) 60 | 61 | ✔ What is the port of the OneBot server? · 8081 62 | (Default: 8081) 63 | 64 | ✔ What is the access_token of the OneBot server? (Optional) · 65 | (Default: empty) 66 | 67 | ✔ What is the ID of the main administrator? (Not used yet) 68 | (Optional) 69 | 70 | ✔ Do you want to view more optional options? · No 71 | ``` 72 | 73 | ## Plugin Development 74 | 75 | ### Creating a Plugin 76 | 77 | Follow the steps below. 78 | 79 | ```bash 80 | cargo kovi create hi 81 | ``` 82 | 83 | `kovi-cli` and `cargo` will take care of everything for you. 84 | 85 | You will see that a new `plugins/hi` directory has been created. This is also the recommended way to develop plugins, as it’s always good to manage them in a directory. 86 | 87 | ### Writing a Plugin 88 | 89 | Edit your newly created plugin in `plugins/hi/src/lib.rs`. 90 | 91 | Here's a minimal example: 92 | 93 | ```rust 94 | // Import the plugin builder structure 95 | use kovi::PluginBuilder as plugin; 96 | 97 | #[kovi::plugin] // Build the plugin 98 | async fn main() { 99 | plugin::on_msg(|event| async move { 100 | // on_msg() listens for messages, and event contains all the information of the current message. 101 | if event.borrow_text() == Some("Hi Bot") { 102 | event.reply("Hi!") // Quick reply 103 | } 104 | }); 105 | } 106 | ``` 107 | 108 | The main function is written in `lib.rs` because it will be exported later to be mounted to the bot instance. 109 | 110 | Plugins generally don't need a `main.rs`. 111 | 112 | ### Mounting the Plugin 113 | 114 | ```bash 115 | cargo kovi add hi 116 | ``` 117 | 118 | Alternatively, you can use `cargo` directly; both are the same. This will add a local dependency in the root project’s `Cargo.toml`. 119 | 120 | ```bash 121 | cargo add --path plugins/hi 122 | ``` 123 | 124 | ```rust 125 | use kovi::build_bot; 126 | 127 | fn main() { 128 | let bot = build_bot!(hi,hi2,plugin123); 129 | bot.run() 130 | } 131 | ``` 132 | 133 | ### More Plugin Examples 134 | 135 | #### Bot Taking Initiative to Send Messages 136 | 137 | ```rust 138 | use kovi::PluginBuilder as plugin; 139 | 140 | #[kovi::plugin] 141 | async fn main() { 142 | // get a RuntimeBot 143 | let bot = plugin::get_runtime_bot(); 144 | let user_id = bot.main_admin; 145 | 146 | bot.send_private_msg(user_id, "bot online") 147 | } 148 | ``` 149 | 150 | The `main()` function runs only once when plugin starts. 151 | 152 | The closure passed to `plugin::on_msg()` runs every time a message is received. 153 | 154 | Kovi has encapsulated all available OneBot standard APIs. To extend the API, you can use `RuntimeBot`'s `send_api()` to send APIs yourself. You can check out the API extension plugins available for your needs at [Kovi Plugin Shop](https://thricecola.github.io/kovi-doc/start/plugins). 155 | 156 | You can find more documentation in the [Kovi Doc](https://thricecola.github.io/kovi-doc/). 157 | -------------------------------------------------------------------------------- /src/bot/event/msg_send_from_kovi_event.rs: -------------------------------------------------------------------------------- 1 | use crate::ApiReturn; 2 | use crate::bot::BotInformation; 3 | use crate::bot::SendApi; 4 | use crate::bot::event::InternalEvent; 5 | use crate::bot::plugin_builder::event::Event; 6 | use crate::bot::runtimebot::CanSendApi; 7 | use crate::types::ApiAndOneshot; 8 | use tokio::sync::mpsc; 9 | 10 | /// 此事件会监听以下消息发送 11 | /// 12 | /// "send_msg" => MsgSendFromKoviType::SendMsg 13 | /// "send_private_msg" => MsgSendFromKoviType::SendPrivateMsg 14 | /// "send_group_msg" => MsgSendFromKoviType::SendGroupMsg 15 | /// "send_forward_msg" => MsgSendFromKoviType::SendForwardMsg 16 | /// "send_private_forward_msg" => MsgSendFromKoviType::SendPrivateForwardMsg 17 | /// "send_group_forward_msg" => MsgSendFromKoviType::SendGroupForwardMsg 18 | #[derive(Debug, Clone)] 19 | pub struct MsgSendFromKoviEvent { 20 | /// 事件类型 21 | pub event_type: MsgSendFromKoviType, 22 | /// 发送消息的API内容 23 | pub send_api: SendApi, 24 | /// 发送消息的API响应结果 25 | pub res: Result, 26 | 27 | /// 不推荐的消息发送方式 28 | pub api_tx: mpsc::Sender, 29 | } 30 | #[derive(Debug, Copy, Clone)] 31 | pub enum MsgSendFromKoviType { 32 | SendMsg, 33 | SendPrivateMsg, 34 | SendGroupMsg, 35 | SendForwardMsg, 36 | SendPrivateForwardMsg, 37 | SendGroupForwardMsg, 38 | } 39 | 40 | impl TryFrom for MsgSendFromKoviType { 41 | type Error = String; 42 | 43 | fn try_from(value: String) -> Result { 44 | match value.as_str() { 45 | "send_msg" => Ok(MsgSendFromKoviType::SendMsg), 46 | "send_private_msg" => Ok(MsgSendFromKoviType::SendPrivateMsg), 47 | "send_group_msg" => Ok(MsgSendFromKoviType::SendGroupMsg), 48 | "send_forward_msg" => Ok(MsgSendFromKoviType::SendForwardMsg), 49 | "send_private_forward_msg" => Ok(MsgSendFromKoviType::SendPrivateForwardMsg), 50 | "send_group_forward_msg" => Ok(MsgSendFromKoviType::SendGroupForwardMsg), 51 | _ => Err(format!("Invalid MsgSendFromKoviType: {value}")), 52 | } 53 | } 54 | } 55 | impl TryFrom<&str> for MsgSendFromKoviType { 56 | type Error = String; 57 | 58 | fn try_from(value: &str) -> Result { 59 | match value { 60 | "send_msg" => Ok(MsgSendFromKoviType::SendMsg), 61 | "send_private_msg" => Ok(MsgSendFromKoviType::SendPrivateMsg), 62 | "send_group_msg" => Ok(MsgSendFromKoviType::SendGroupMsg), 63 | "send_forward_msg" => Ok(MsgSendFromKoviType::SendForwardMsg), 64 | "send_private_forward_msg" => Ok(MsgSendFromKoviType::SendPrivateForwardMsg), 65 | "send_group_forward_msg" => Ok(MsgSendFromKoviType::SendGroupForwardMsg), 66 | _ => Err(format!("Invalid MsgSendFromKoviType: {value}")), 67 | } 68 | } 69 | } 70 | impl TryFrom<&String> for MsgSendFromKoviType { 71 | type Error = String; 72 | 73 | fn try_from(value: &String) -> Result { 74 | match value.as_str() { 75 | "send_msg" => Ok(MsgSendFromKoviType::SendMsg), 76 | "send_private_msg" => Ok(MsgSendFromKoviType::SendPrivateMsg), 77 | "send_group_msg" => Ok(MsgSendFromKoviType::SendGroupMsg), 78 | "send_forward_msg" => Ok(MsgSendFromKoviType::SendForwardMsg), 79 | "send_private_forward_msg" => Ok(MsgSendFromKoviType::SendPrivateForwardMsg), 80 | "send_group_forward_msg" => Ok(MsgSendFromKoviType::SendGroupForwardMsg), 81 | _ => Err(format!("Invalid MsgSendFromKoviType: {value}")), 82 | } 83 | } 84 | } 85 | 86 | impl Event for MsgSendFromKoviEvent { 87 | fn de( 88 | event: &InternalEvent, 89 | _: &BotInformation, 90 | api_tx: &mpsc::Sender, 91 | ) -> Option { 92 | let InternalEvent::OneBotApiEvent((send_api, res)) = event else { 93 | return None; 94 | }; 95 | 96 | let Ok(event_type) = MsgSendFromKoviType::try_from(&send_api.action) else { 97 | return None; 98 | }; 99 | 100 | Some(Self::new( 101 | event_type, 102 | send_api.clone(), 103 | res.clone(), 104 | api_tx.clone(), 105 | )) 106 | } 107 | } 108 | 109 | impl MsgSendFromKoviEvent { 110 | fn new( 111 | event_type: MsgSendFromKoviType, 112 | send_api: SendApi, 113 | res: Result, 114 | api_tx: mpsc::Sender, 115 | ) -> MsgSendFromKoviEvent { 116 | MsgSendFromKoviEvent { 117 | event_type, 118 | send_api, 119 | res, 120 | api_tx, 121 | } 122 | } 123 | } 124 | 125 | impl CanSendApi for MsgSendFromKoviEvent { 126 | fn __get_api_tx(&self) -> &tokio::sync::mpsc::Sender { 127 | &self.api_tx 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/plugin.rs: -------------------------------------------------------------------------------- 1 | pub mod plugin_builder; 2 | 3 | use crate::PluginBuilder; 4 | use crate::bot::plugin_builder::Listen; 5 | #[cfg(feature = "plugin-access-control")] 6 | use crate::bot::runtimebot::kovi_api::AccessList; 7 | use crate::types::KoviAsyncFn; 8 | use serde::{Deserialize, Serialize}; 9 | use std::sync::Arc; 10 | use tokio::sync::watch; 11 | use tokio::task::JoinHandle; 12 | 13 | #[cfg(feature = "plugin-access-control")] 14 | pub use crate::bot::runtimebot::kovi_api::AccessControlMode; 15 | 16 | use crate::task::TASK_MANAGER; 17 | 18 | tokio::task_local! { 19 | pub static PLUGIN_BUILDER: crate::PluginBuilder; 20 | } 21 | 22 | tokio::task_local! { 23 | pub(crate) static PLUGIN_NAME: Arc; 24 | } 25 | 26 | #[derive(Clone)] 27 | pub struct Plugin { 28 | pub(crate) enable_on_startup: bool, 29 | pub(crate) enabled: watch::Sender, 30 | 31 | pub name: String, 32 | pub version: String, 33 | pub(crate) main: Arc, 34 | pub(crate) listen: Listen, 35 | 36 | #[cfg(feature = "plugin-access-control")] 37 | pub(crate) access_control: bool, 38 | #[cfg(feature = "plugin-access-control")] 39 | pub(crate) list_mode: AccessControlMode, 40 | #[cfg(feature = "plugin-access-control")] 41 | pub(crate) access_list: AccessList, 42 | } 43 | 44 | impl Plugin { 45 | pub fn new(name: S, version: S, main: Arc) -> Self 46 | where 47 | S: Into, 48 | { 49 | Self { 50 | enable_on_startup: true, 51 | enabled: watch::channel(true).0, 52 | name: name.into(), 53 | version: version.into(), 54 | main, 55 | listen: Listen::default(), 56 | #[cfg(feature = "plugin-access-control")] 57 | access_control: false, 58 | #[cfg(feature = "plugin-access-control")] 59 | list_mode: AccessControlMode::WhiteList, 60 | #[cfg(feature = "plugin-access-control")] 61 | access_list: AccessList::default(), 62 | } 63 | } 64 | 65 | /// 运行单个插件的main() 66 | pub(crate) fn run(&self, plugin_builder: PluginBuilder) { 67 | let plugin_name = plugin_builder.runtime_bot.plugin_name.clone(); 68 | 69 | let mut enabled = self.enabled.subscribe(); 70 | let main = self.main.clone(); 71 | 72 | tokio::spawn(async move { 73 | tokio::select! { 74 | _ = PLUGIN_NAME.scope( 75 | Arc::new(plugin_name), 76 | PLUGIN_BUILDER.scope(plugin_builder, main()), 77 | ) =>{} 78 | _ = async { 79 | loop { 80 | enabled.changed().await.expect("Failed to change enabled status"); 81 | if !*enabled.borrow_and_update() { 82 | break; 83 | } 84 | } 85 | } => {} 86 | } 87 | }); 88 | } 89 | 90 | pub(crate) fn shutdown(&mut self) -> JoinHandle<()> { 91 | log::debug!("Plugin '{}' is dropping.", self.name,); 92 | 93 | let plugin_name_ = Arc::new(self.name.clone()); 94 | 95 | let mut task_vec = Vec::new(); 96 | 97 | for listen in &self.listen.drop { 98 | let listen_clone = listen.clone(); 99 | let plugin_name_ = plugin_name_.clone(); 100 | let task = tokio::spawn(async move { 101 | PLUGIN_NAME.scope(plugin_name_, listen_clone()).await; 102 | }); 103 | task_vec.push(task); 104 | } 105 | 106 | TASK_MANAGER.disable_plugin(&self.name); 107 | 108 | self.enabled.send_modify(|v| { 109 | *v = false; 110 | }); 111 | self.listen.clear(); 112 | tokio::spawn(async move { 113 | for task in task_vec { 114 | let _ = task.await; 115 | } 116 | }) 117 | } 118 | } 119 | 120 | #[derive(Debug, Clone, Deserialize, Serialize)] 121 | pub(crate) struct PluginStatus { 122 | pub(crate) enable_on_startup: bool, 123 | #[cfg(feature = "plugin-access-control")] 124 | pub(crate) access_control: bool, 125 | #[cfg(feature = "plugin-access-control")] 126 | pub(crate) list_mode: AccessControlMode, 127 | #[cfg(feature = "plugin-access-control")] 128 | pub(crate) access_list: AccessList, 129 | } 130 | 131 | #[derive(Clone, Debug, Deserialize, Serialize)] 132 | pub struct PluginInfo { 133 | pub name: String, 134 | pub version: String, 135 | /// 插件是否启用 136 | pub enabled: bool, 137 | /// 插件是否在Bot启动时启用 138 | pub enable_on_startup: bool, 139 | /// 插件是否启用框架级访问控制 140 | #[cfg(feature = "plugin-access-control")] 141 | pub access_control: bool, 142 | /// 插件的访问控制模式 143 | #[cfg(feature = "plugin-access-control")] 144 | pub list_mode: AccessControlMode, 145 | /// 插件的访问控制列表 146 | #[cfg(feature = "plugin-access-control")] 147 | pub access_list: AccessList, 148 | } 149 | -------------------------------------------------------------------------------- /src/bot/event.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | bot::BotInformation, 3 | types::{ApiAndOneshot, ApiAndRuturn}, 4 | }; 5 | use serde::{Deserialize, Serialize}; 6 | use std::any::Any; 7 | 8 | pub use admin_msg_event::AdminMsgEvent; 9 | pub use group_msg_event::GroupMsgEvent; 10 | pub use msg_event::MsgEvent; 11 | pub use msg_send_from_kovi_event::MsgSendFromKoviEvent; 12 | pub use msg_send_from_server_event::MsgSendFromServerEvent; 13 | pub use notice_event::NoticeEvent; 14 | pub use private_msg_event::PrivateMsgEvent; 15 | pub use request_event::RequestEvent; 16 | 17 | pub mod admin_msg_event; 18 | pub mod group_msg_event; 19 | pub mod lifecycle_event; 20 | pub mod msg_event; 21 | pub mod msg_send_from_kovi_event; 22 | pub mod msg_send_from_server_event; 23 | pub mod notice_event; 24 | pub mod private_msg_event; 25 | pub mod request_event; 26 | 27 | #[deprecated(since = "0.11.0", note = "请使用 `MsgEvent` 代替")] 28 | pub type AllMsgEvent = MsgEvent; 29 | #[deprecated(since = "0.11.0", note = "请使用 `NoticeEvent` 代替")] 30 | pub type AllNoticeEvent = NoticeEvent; 31 | #[deprecated(since = "0.11.0", note = "请使用 `RequestEvent` 代替")] 32 | pub type AllRequestEvent = RequestEvent; 33 | 34 | #[derive(Debug, Copy, Clone)] 35 | pub enum Sex { 36 | Male, 37 | Female, 38 | } 39 | 40 | #[derive(Debug, Clone)] 41 | pub struct Sender { 42 | pub user_id: i64, 43 | pub nickname: Option, 44 | pub card: Option, 45 | pub sex: Option, 46 | pub age: Option, 47 | pub area: Option, 48 | pub level: Option, 49 | pub role: Option, 50 | pub title: Option, 51 | } 52 | #[derive(Debug, Deserialize, Serialize, Clone)] 53 | pub struct Anonymous { 54 | pub id: i64, 55 | pub name: String, 56 | pub flag: String, 57 | } 58 | 59 | #[derive(Debug, Clone, PartialEq, Eq)] 60 | pub enum PostType { 61 | Message, 62 | Notice, 63 | Request, 64 | MetaEvent, 65 | MessageSent, 66 | 67 | Other(String), 68 | } 69 | 70 | impl<'de> Deserialize<'de> for PostType { 71 | fn deserialize(deserializer: D) -> Result 72 | where 73 | D: serde::Deserializer<'de>, 74 | { 75 | let s = String::deserialize(deserializer)?; 76 | let post_type = match s.as_str() { 77 | "message" => PostType::Message, 78 | "notice" => PostType::Notice, 79 | "request" => PostType::Request, 80 | "meta_event" => PostType::MetaEvent, 81 | "message_sent" => PostType::MessageSent, 82 | _ => PostType::Other(s), 83 | }; 84 | Ok(post_type) 85 | } 86 | } 87 | 88 | /// 满足此 trait 即可在Kovi运行时中监听并处理 89 | /// 90 | /// # Warning 91 | /// 92 | /// 最好不要阻塞解析事件,如果目标信息需要阻塞获取,请通知用户由用户处理,而非由事件解析器阻塞 93 | /// 94 | /// 在 Kovi 0.12.4 之后,事件是并发解析的,所以阻塞解析事件并不会阻塞其他事件的解析,虽然如此,仍然不建议阻塞解析事件 95 | pub trait Event: Any + Send + Sync { 96 | /// 解析事件 97 | /// 98 | /// 传入三个东西,按需所取。 99 | /// - InternalEvent 内部消息,包含OneBot消息与由框架发出去的Api消息 100 | /// - 借用的bot信息,可以通过 `BotInformation` 获取 `Bot` 相关的信息,例如管理员是谁。 101 | /// - 借用的api发送通道,可以通过 `api_tx.clone()` 来让事件可以发送 api 102 | /// 103 | /// 如果认为此 json 不符合事件要求,请返回 `None`。 104 | /// 105 | /// 在一个消息周期内,Kovi 运行时会缓存此事件。 106 | /// 107 | /// 不需要的信息用 `_` 忽略,例如: 108 | /// 109 | /// ```ignore 110 | /// 111 | /// impl Event for LifecycleEvent { 112 | /// fn de( 113 | /// event: &InternalEvent, 114 | /// _: &BotInformation, 115 | /// _: &tokio::sync::mpsc::Sender, 116 | /// ) -> Option 117 | /// where 118 | /// Self: Sized, 119 | /// { 120 | /// let InternalEvent::OneBotEvent(json_str) = event else { 121 | /// return None; 122 | /// }; 123 | /// let event: LifecycleEvent = serde_json::from_str(json_str).ok()?; 124 | /// if event.meta_event_type == "lifecycle" { 125 | /// Some(event) 126 | /// } else { 127 | /// None 128 | /// } 129 | /// } 130 | /// } 131 | /// ``` 132 | /// 133 | /// # Warning 134 | /// 135 | /// 最好不要阻塞解析事件,如果目标信息需要阻塞获取,请通知用户由用户处理,而非由事件解析器阻塞 136 | /// 137 | /// 在 Kovi 0.12.4 之后,事件是并发解析的,所以阻塞解析事件并不会阻塞其他事件的解析,虽然如此,仍然不建议阻塞解析事件 138 | /// 139 | /// 可以使用类似于 `MsgSendFromKoviEvent` 的实现,将所需的交给用户就行。 140 | /// 141 | /// ```ignore 142 | /// 143 | /// pub struct MsgSendFromKoviEvent { 144 | /// pub event_type: MsgSendFromKoviType, 145 | /// pub send_api: SendApi, 146 | /// pub res: Result, 147 | /// } 148 | /// ``` 149 | fn de( 150 | event: &InternalEvent, 151 | bot_info: &BotInformation, 152 | api_tx: &tokio::sync::mpsc::Sender, 153 | ) -> Option 154 | where 155 | Self: Sized; 156 | } 157 | 158 | /// 事件 159 | pub enum InternalEvent { 160 | /// 来自OneBot的事件 161 | OneBotEvent(String), 162 | /// 来自Kovi发送给服务端并包含了返回结果 163 | OneBotApiEvent(ApiAndRuturn), 164 | } 165 | 166 | #[test] 167 | fn post_type_is_ok() { 168 | use serde_json::json; 169 | 170 | assert_eq!( 171 | PostType::Message, 172 | serde_json::from_value::(json!("message")).unwrap() 173 | ); 174 | assert_eq!( 175 | PostType::Notice, 176 | serde_json::from_value::(json!("notice")).unwrap() 177 | ); 178 | assert_eq!( 179 | PostType::Request, 180 | serde_json::from_value::(json!("request")).unwrap() 181 | ); 182 | assert_eq!( 183 | PostType::MetaEvent, 184 | serde_json::from_value::(json!("meta_event")).unwrap() 185 | ); 186 | } 187 | -------------------------------------------------------------------------------- /src/bot/message/add.rs: -------------------------------------------------------------------------------- 1 | use serde::Serialize; 2 | use serde_json::{json, Value}; 3 | use std::fmt::Display; 4 | 5 | use super::{Message, Segment}; 6 | 7 | #[cfg(feature = "cqstring")] 8 | use super::CQMessage; 9 | 10 | impl Message { 11 | /// 在消息加上文字 12 | pub fn add_text(mut self, text: T) -> Self 13 | where 14 | String: From, 15 | T: Serialize + Display, 16 | { 17 | self.push(Segment { 18 | type_: "text".to_string(), 19 | data: json!({ "text": text }), 20 | }); 21 | self 22 | } 23 | 24 | /// 消息加上at 25 | pub fn add_at(mut self, id: &str) -> Self { 26 | self.0.push(Segment { 27 | type_: "at".to_string(), 28 | data: json!({ "qq": id }), 29 | }); 30 | self 31 | } 32 | 33 | /// 消息加上引用 34 | pub fn add_reply(mut self, message_id: i32) -> Self { 35 | self.0.insert(0, Segment { 36 | type_: "reply".to_string(), 37 | data: json!({ "id": message_id.to_string() }), 38 | }); 39 | self 40 | } 41 | 42 | /// 消息加上表情, 具体 id 请看服务端文档, 本框架不提供 43 | pub fn add_face(mut self, id: i64) -> Self { 44 | self.0.push(Segment { 45 | type_: "face".to_string(), 46 | data: json!({ "id": id.to_string() }), 47 | }); 48 | self 49 | } 50 | 51 | /// 消息加上图片 52 | pub fn add_image(mut self, file: &str) -> Self { 53 | self.0.push(Segment { 54 | type_: "image".to_string(), 55 | data: json!({ "file": file }), 56 | }); 57 | self 58 | } 59 | 60 | /// 消息加上 segment 61 | pub fn add_segment(mut self, segment: T) -> Self 62 | where 63 | Value: From, 64 | T: Serialize, 65 | { 66 | let value = Value::from(segment); 67 | if let Ok(segment) = serde_json::from_value(value) { 68 | self.0.push(segment); 69 | } 70 | self 71 | } 72 | } 73 | 74 | impl Message { 75 | /// 在消息加上文字 76 | pub fn push_text(&mut self, text: T) 77 | where 78 | String: From, 79 | T: Serialize + Display, 80 | { 81 | self.push(Segment { 82 | type_: "text".to_string(), 83 | data: json!({ "text": text }), 84 | }); 85 | } 86 | 87 | /// 消息加上at 88 | pub fn push_at(&mut self, id: &str) { 89 | self.0.push(Segment { 90 | type_: "at".to_string(), 91 | data: json!({ "qq": id }), 92 | }); 93 | } 94 | 95 | /// 消息加上引用 96 | pub fn push_reply(&mut self, message_id: i32) { 97 | self.0.insert(0, Segment { 98 | type_: "reply".to_string(), 99 | data: json!({ "id": message_id.to_string() }), 100 | }); 101 | } 102 | 103 | /// 消息加上表情, 具体 id 请看服务端文档, 本框架不提供 104 | pub fn push_face(&mut self, id: i64) { 105 | self.0.push(Segment { 106 | type_: "face".to_string(), 107 | data: json!({ "id": id.to_string() }), 108 | }); 109 | } 110 | 111 | /// 消息加上图片 112 | pub fn push_image(&mut self, file: &str) { 113 | self.0.push(Segment { 114 | type_: "image".to_string(), 115 | data: json!({ "file": file }), 116 | }); 117 | } 118 | 119 | pub fn push(&mut self, s: Segment) { 120 | self.0.push(s); 121 | } 122 | } 123 | 124 | #[cfg(feature = "cqstring")] 125 | impl CQMessage { 126 | /// 在消息加上文字 127 | pub fn add_text(mut self, text: T) -> Self 128 | where 129 | String: From, 130 | T: Serialize + Display, 131 | { 132 | self.0.push_str(&format!("[CQ:text,text={text}]")); 133 | self 134 | } 135 | 136 | /// 消息加上at 137 | pub fn add_at(mut self, id: &str) -> Self { 138 | self.0.push_str(&format!("[CQ:at,qq={id}]")); 139 | self 140 | } 141 | 142 | /// 消息加上引用 143 | pub fn add_reply(mut self, message_id: i32) -> Self { 144 | self.0 145 | .insert_str(0, &format!("[CQ:reply,id={message_id}]")); 146 | self 147 | } 148 | 149 | /// 消息加上表情 150 | pub fn add_face(mut self, id: i64) -> Self { 151 | self.0.push_str(&format!("[CQ:face,id={id}]")); 152 | self 153 | } 154 | 155 | /// 消息加上图片 156 | pub fn add_image(mut self, file: &str) -> Self { 157 | self.0.push_str(&format!("[CQ:image,file={file}]")); 158 | self 159 | } 160 | 161 | /// 消息加上 segment 162 | pub fn add_segment(mut self, segment: T) -> Self 163 | where 164 | Value: From, 165 | T: Serialize, 166 | { 167 | let value = Value::from(segment); 168 | if let Ok(segment) = serde_json::from_value::(value) { 169 | self.0.push_str(&super::parse_cq_code(&segment)); 170 | } 171 | self 172 | } 173 | } 174 | 175 | #[cfg(feature = "cqstring")] 176 | impl CQMessage { 177 | /// 在消息加上文字 178 | pub fn push_text(&mut self, text: T) 179 | where 180 | String: From, 181 | T: Serialize + Display, 182 | { 183 | self.0.push_str(&format!("[CQ:text,text={text}]")); 184 | } 185 | 186 | /// 消息加上at 187 | pub fn push_at(&mut self, id: &str) { 188 | self.0.push_str(&format!("[CQ:at,qq={id}]")); 189 | } 190 | 191 | /// 消息加上引用 192 | pub fn push_reply(&mut self, message_id: i32) { 193 | self.0 194 | .insert_str(0, &format!("[CQ:reply,id={message_id}]")); 195 | } 196 | 197 | /// 消息加上表情 198 | pub fn push_face(&mut self, id: i64) { 199 | self.0.push_str(&format!("[CQ:face,id={id}]")); 200 | } 201 | 202 | /// 消息加上图片 203 | pub fn push_image(&mut self, file: &str) { 204 | self.0.push_str(&format!("[CQ:image,file={file}]")); 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /src/bot/run.rs: -------------------------------------------------------------------------------- 1 | use super::{Bot, handler::KoviEvent}; 2 | use crate::{ 3 | PluginBuilder, bot::handler::InternalInternalEvent, 4 | event::lifecycle_event::handler_lifecycle_log_bot_enable, types::ApiAndOneshot, 5 | }; 6 | use log::error; 7 | use parking_lot::RwLock; 8 | use std::{ 9 | borrow::Borrow, 10 | future::Future, 11 | process::exit, 12 | sync::{Arc, LazyLock}, 13 | }; 14 | use tokio::{ 15 | runtime::Runtime as TokioRuntime, 16 | sync::{ 17 | mpsc::{self, Sender}, 18 | watch, 19 | }, 20 | task::JoinHandle, 21 | }; 22 | 23 | pub(crate) static RUNTIME: LazyLock = 24 | LazyLock::new(|| TokioRuntime::new().expect("unreachable! tokio runtime fail to start")); 25 | pub(crate) use RUNTIME as RT; 26 | 27 | impl Bot { 28 | pub fn spawn(&mut self, future: F) -> JoinHandle 29 | where 30 | F: Future + Send + 'static, 31 | F::Output: Send + 'static, 32 | { 33 | let join = RT.spawn(future); 34 | self.run_abort.push(join.abort_handle()); 35 | join 36 | } 37 | 38 | /// 运行bot 39 | /// 40 | /// **注意此函数会阻塞, 直到Bot连接失效,或者有退出信号传入程序** 41 | pub fn run(self) { 42 | let server = self.information.read().server.clone(); 43 | 44 | let bot = Arc::new(RwLock::new(self)); 45 | 46 | let async_task = async { 47 | // let (tx, rx): ( 48 | // tokio::sync::broadcast::Sender>, 49 | // tokio::sync::broadcast::Receiver>, 50 | // ) = tokio::sync::broadcast::channel(32); 51 | 52 | //处理连接,从msg_tx返回消息 53 | let (event_tx, mut event_rx): ( 54 | mpsc::Sender, 55 | mpsc::Receiver, 56 | ) = mpsc::channel(32); 57 | 58 | // 接收插件的api 59 | let (api_tx, api_rx): (mpsc::Sender, mpsc::Receiver) = 60 | mpsc::channel(32); 61 | 62 | // 连接 63 | let connect_task = RT.spawn({ 64 | let event_tx = event_tx.clone(); 65 | Self::ws_connect(server, api_rx, event_tx, bot.clone()) 66 | }); 67 | 68 | let connect_res = connect_task.await.expect("unreachable"); 69 | 70 | if let Err(e) = connect_res { 71 | error!( 72 | "{e}\nBot connection failed, please check the configuration and restart the bot" 73 | ); 74 | return; 75 | } 76 | 77 | { 78 | let mut bot_write = bot.write(); 79 | 80 | // drop检测 81 | bot_write.spawn({ 82 | let event_tx = event_tx; 83 | exit_signal_check(event_tx) 84 | }); 85 | 86 | // 运行所有的main 87 | bot_write.spawn({ 88 | let bot = bot.clone(); 89 | let api_tx = api_tx.clone(); 90 | async move { Self::run_mains(bot, api_tx) } 91 | }); 92 | } 93 | 94 | tokio::spawn(handler_lifecycle_log_bot_enable(api_tx.clone())); 95 | 96 | let mut drop_task = None; 97 | //处理事件,每个事件都会来到这里 98 | while let Some(event) = event_rx.recv().await { 99 | let api_tx = api_tx.clone(); 100 | let bot = bot.clone(); 101 | 102 | // Drop为关闭事件,所以要等待,其他的不等待 103 | if let InternalInternalEvent::KoviEvent(KoviEvent::Drop) = event { 104 | drop_task = Some(RT.spawn(Self::handler_event(bot, event, api_tx))); 105 | break; 106 | } else { 107 | RT.spawn(Self::handler_event(bot, event, api_tx)); 108 | } 109 | } 110 | if let Some(drop_task) = drop_task { 111 | match drop_task.await { 112 | Ok(_) => {} 113 | Err(e) => { 114 | error!("{e}") 115 | } 116 | }; 117 | } 118 | }; 119 | 120 | RT.block_on(async_task); 121 | } 122 | 123 | // 运行所有main() 124 | fn run_mains(bot: Arc>, api_tx: mpsc::Sender) { 125 | let bot_ = bot.read(); 126 | let main_job_map = bot_.plugins.borrow(); 127 | 128 | let (host, port) = { 129 | let info = bot_.information.read(); 130 | (info.server.host.clone(), info.server.port) 131 | }; 132 | 133 | for (name, plugin) in main_job_map.iter() { 134 | if !plugin.enable_on_startup { 135 | continue; 136 | } 137 | let plugin_builder = PluginBuilder::new( 138 | name.clone(), 139 | bot.clone(), 140 | host.clone(), 141 | port, 142 | api_tx.clone(), 143 | ); 144 | plugin.run(plugin_builder); 145 | } 146 | } 147 | } 148 | 149 | pub(crate) static DROP_CHECK: LazyLock = LazyLock::new(ExitCheck::init); 150 | 151 | pub struct ExitCheck { 152 | watch_rx: watch::Receiver, 153 | join_handle: tokio::task::JoinHandle<()>, 154 | } 155 | 156 | impl Drop for ExitCheck { 157 | fn drop(&mut self) { 158 | self.join_handle.abort(); 159 | } 160 | } 161 | 162 | impl ExitCheck { 163 | fn init() -> ExitCheck { 164 | let (tx, watch_rx) = watch::channel(false); 165 | 166 | // 启动 drop check 任务 167 | let join_handle = RT.spawn(async move { 168 | Self::await_exit_signal().await; 169 | 170 | let _ = tx.send(true); 171 | 172 | Self::await_exit_signal().await; 173 | 174 | handler_second_time_exit_signal().await; 175 | }); 176 | 177 | ExitCheck { 178 | watch_rx, 179 | join_handle, 180 | } 181 | } 182 | 183 | async fn await_exit_signal() { 184 | #[cfg(unix)] 185 | use tokio::signal::unix::{SignalKind, signal}; 186 | #[cfg(windows)] 187 | use tokio::signal::windows; 188 | 189 | #[cfg(windows)] 190 | { 191 | let mut sig_ctrl_break = windows::ctrl_break().expect("unreachable"); 192 | let mut sig_ctrl_c = windows::ctrl_c().expect("unreachable"); 193 | let mut sig_ctrl_close = windows::ctrl_close().expect("unreachable"); 194 | let mut sig_ctrl_logoff = windows::ctrl_logoff().expect("unreachable"); 195 | let mut sig_ctrl_shutdown = windows::ctrl_shutdown().expect("unreachable"); 196 | 197 | tokio::select! { 198 | _ = sig_ctrl_break.recv() => {} 199 | _ = sig_ctrl_c.recv() => {} 200 | _ = sig_ctrl_close.recv() => {} 201 | _ = sig_ctrl_logoff.recv() => {} 202 | _ = sig_ctrl_shutdown.recv() => {} 203 | } 204 | } 205 | 206 | #[cfg(unix)] 207 | { 208 | let mut sig_hangup = signal(SignalKind::hangup()).expect("unreachable"); 209 | let mut sig_alarm = signal(SignalKind::alarm()).expect("unreachable"); 210 | let mut sig_interrupt = signal(SignalKind::interrupt()).expect("unreachable"); 211 | let mut sig_quit = signal(SignalKind::quit()).expect("unreachable"); 212 | let mut sig_terminate = signal(SignalKind::terminate()).expect("unreachable"); 213 | 214 | tokio::select! { 215 | _ = sig_hangup.recv() => {} 216 | _ = sig_alarm.recv() => {} 217 | _ = sig_interrupt.recv() => {} 218 | _ = sig_quit.recv() => {} 219 | _ = sig_terminate.recv() => {} 220 | } 221 | } 222 | } 223 | 224 | pub async fn await_exit_signal_change(&self) { 225 | let mut rx = self.watch_rx.clone(); 226 | rx.changed().await.expect("The exit signal wait failed"); 227 | } 228 | } 229 | 230 | pub(crate) async fn exit_signal_check(tx: Sender) { 231 | DROP_CHECK.await_exit_signal_change().await; 232 | 233 | tx.send(InternalInternalEvent::KoviEvent(KoviEvent::Drop)) 234 | .await 235 | .expect("The exit signal send failed"); 236 | } 237 | 238 | async fn handler_second_time_exit_signal() { 239 | exit(1) 240 | } 241 | -------------------------------------------------------------------------------- /src/bot/event/private_msg_event.rs: -------------------------------------------------------------------------------- 1 | use super::{Anonymous, Sender}; 2 | use crate::MsgEvent; 3 | use crate::bot::BotInformation; 4 | use crate::bot::event::InternalEvent; 5 | use crate::bot::plugin_builder::event::{Event, PostType}; 6 | use crate::bot::runtimebot::send_api_request_with_forget; 7 | use crate::error::EventBuildError; 8 | use crate::types::ApiAndOneshot; 9 | use crate::{Message, bot::SendApi}; 10 | use log::info; 11 | use serde::Serialize; 12 | use serde_json::value::Index; 13 | use serde_json::{self, Value, json}; 14 | use tokio::sync::mpsc; 15 | 16 | #[cfg(feature = "cqstring")] 17 | use crate::bot::message::CQMessage; 18 | 19 | #[derive(Debug, Clone)] 20 | pub struct PrivateMsgEvent { 21 | /// 事件发生的时间戳 22 | pub time: i64, 23 | /// 收到事件的机器人 登陆号 24 | pub self_id: i64, 25 | /// 上报类型 26 | pub post_type: PostType, 27 | /// 消息类型 28 | pub message_type: String, 29 | /// 消息子类型,如果是好友则是 friend,如果是群临时会话则是 group 30 | pub sub_type: String, 31 | /// 消息内容 32 | pub message: Message, 33 | /// 消息 ID 34 | pub message_id: i32, 35 | /// 发送者号 36 | pub user_id: i64, 37 | /// 匿名信息,如果不是匿名消息则为 null 38 | pub anonymous: Option, 39 | /// 原始消息内容 40 | pub raw_message: String, 41 | /// 字体 42 | pub font: i32, 43 | /// 发送人信息 44 | pub sender: Sender, 45 | 46 | /// 处理过的纯文本,如果是纯图片或无文本,此处为None 47 | pub text: Option, 48 | /// 处理过的文本,会解析成人类易读形式,里面会包含\[image\]\[face\]等解析后字符串 49 | pub human_text: String, 50 | /// 原始的onebot消息,已处理成json格式 51 | pub original_json: Value, 52 | 53 | /// 不推荐的消息发送方式 54 | pub api_tx: mpsc::Sender, 55 | } 56 | 57 | impl Event for PrivateMsgEvent { 58 | fn de( 59 | event: &InternalEvent, 60 | _: &BotInformation, 61 | api_tx: &mpsc::Sender, 62 | ) -> Option { 63 | let InternalEvent::OneBotEvent(json_str) = event else { 64 | return None; 65 | }; 66 | 67 | let json: Value = serde_json::from_str(json_str).ok()?; 68 | let event = Self::new(api_tx.clone(), json).ok()?; 69 | 70 | Some(event) 71 | } 72 | } 73 | 74 | impl PrivateMsgEvent { 75 | fn new( 76 | api_tx: mpsc::Sender, 77 | json: Value, 78 | ) -> Result { 79 | let msg_event = MsgEvent::new(api_tx, json)?; 80 | 81 | if msg_event.is_group() { 82 | return Err(EventBuildError::ParseError( 83 | "PrivateMsgEvent Not Group".to_string(), 84 | )); 85 | } 86 | 87 | Ok(PrivateMsgEvent { 88 | time: msg_event.time, 89 | self_id: msg_event.self_id, 90 | post_type: msg_event.post_type, 91 | message_type: msg_event.message_type, 92 | sub_type: msg_event.sub_type, 93 | message: msg_event.message, 94 | message_id: msg_event.message_id, 95 | user_id: msg_event.user_id, 96 | anonymous: msg_event.anonymous, 97 | raw_message: msg_event.raw_message, 98 | font: msg_event.font, 99 | sender: msg_event.sender, 100 | text: msg_event.text, 101 | human_text: msg_event.human_text, 102 | original_json: msg_event.original_json, 103 | api_tx: msg_event.api_tx, 104 | }) 105 | } 106 | } 107 | 108 | impl PrivateMsgEvent { 109 | /// 直接从原始的 Json Value 获取某值 110 | /// 111 | /// # example 112 | /// 113 | /// ```ignore 114 | /// use kovi::PluginBuilder; 115 | /// 116 | /// PluginBuilder::on_msg(|event| async move { 117 | /// let time = event.get("time").and_then(|v| v.as_i64()).unwrap(); 118 | /// 119 | /// assert_eq!(time, event.time); 120 | /// }); 121 | /// ``` 122 | pub fn get(&self, index: I) -> Option<&Value> { 123 | self.original_json.get(index) 124 | } 125 | } 126 | 127 | impl std::ops::Index for PrivateMsgEvent 128 | where 129 | I: Index, 130 | { 131 | type Output = Value; 132 | 133 | fn index(&self, index: I) -> &Self::Output { 134 | &self.original_json[index] 135 | } 136 | } 137 | 138 | impl PrivateMsgEvent { 139 | fn reply_builder(&self, msg: T, auto_escape: bool) -> SendApi 140 | where 141 | T: Serialize, 142 | { 143 | SendApi::new( 144 | "send_msg", 145 | json!({ 146 | "message_type":"private", 147 | "user_id":self.user_id, 148 | "message":msg, 149 | "auto_escape":auto_escape, 150 | }), 151 | ) 152 | } 153 | 154 | #[cfg(not(feature = "cqstring"))] 155 | /// 快速回复消息 156 | pub fn reply(&self, msg: T) 157 | where 158 | Message: From, 159 | T: Serialize, 160 | { 161 | let msg = Message::from(msg); 162 | let send_msg = self.reply_builder(&msg, false); 163 | let nickname = self.get_sender_nickname(); 164 | let id = &self.sender.user_id; 165 | let message_type = &self.message_type; 166 | let human_msg = msg.to_human_string(); 167 | info!("[reply] [to {message_type} {nickname} {id}]: {human_msg}"); 168 | 169 | send_api_request_with_forget(&self.api_tx, send_msg) 170 | } 171 | 172 | #[cfg(feature = "cqstring")] 173 | /// 快速回复消息 174 | pub fn reply(&self, msg: T) 175 | where 176 | CQMessage: From, 177 | T: Serialize, 178 | { 179 | let msg = CQMessage::from(msg); 180 | let send_msg = self.reply_builder(&msg, false); 181 | let nickname = self.get_sender_nickname(); 182 | let id = &self.sender.user_id; 183 | let message_type = &self.message_type; 184 | let human_msg = Message::from(msg).to_human_string(); 185 | info!("[reply] [to {message_type} {nickname} {id}]: {human_msg}"); 186 | send_api_request_with_forget(&self.api_tx, send_msg); 187 | } 188 | 189 | #[cfg(not(feature = "cqstring"))] 190 | /// 快速回复消息并且**引用** 191 | pub fn reply_and_quote(&self, msg: T) 192 | where 193 | Message: From, 194 | T: Serialize, 195 | { 196 | let msg = Message::from(msg).add_reply(self.message_id); 197 | let send_msg = self.reply_builder(&msg, false); 198 | 199 | let nickname = self.get_sender_nickname(); 200 | let id = &self.sender.user_id; 201 | let message_type = &self.message_type; 202 | let human_msg = msg.to_human_string(); 203 | info!("[reply] [to {message_type} {nickname} {id}]: {human_msg}"); 204 | 205 | send_api_request_with_forget(&self.api_tx, send_msg); 206 | } 207 | 208 | #[cfg(feature = "cqstring")] 209 | /// 快速回复消息并且**引用** 210 | pub fn reply_and_quote(&self, msg: T) 211 | where 212 | CQMessage: From, 213 | T: Serialize, 214 | { 215 | let msg = CQMessage::from(msg).add_reply(self.message_id); 216 | let send_msg = self.reply_builder(&msg, false); 217 | 218 | let nickname = self.get_sender_nickname(); 219 | let id = &self.sender.user_id; 220 | let message_type = &self.message_type; 221 | let human_msg = Message::from(msg).to_human_string(); 222 | info!("[reply] [to {message_type} {nickname} {id}]: {human_msg}"); 223 | send_api_request_with_forget(&self.api_tx, send_msg); 224 | } 225 | 226 | #[cfg(feature = "cqstring")] 227 | /// 快速回复消息,并且**kovi不进行解析,直接发送此字符串** 228 | pub fn reply_text(&self, msg: T) 229 | where 230 | String: From, 231 | T: Serialize, 232 | { 233 | let send_msg = self.reply_builder(&msg, true); 234 | let nickname = self.get_sender_nickname(); 235 | let id = &self.sender.user_id; 236 | let message_type = &self.message_type; 237 | let msg = String::from(msg); 238 | info!("[reply] [to {message_type} {nickname} {id}]: {msg}"); 239 | send_api_request_with_forget(&self.api_tx, send_msg); 240 | } 241 | 242 | /// 便捷获取文本,如果没有文本则会返回空字符串,如果只需要借用,请使用 `borrow_text()` 243 | pub fn get_text(&self) -> String { 244 | match self.text.clone() { 245 | Some(v) => v, 246 | None => "".to_string(), 247 | } 248 | } 249 | 250 | /// 便捷获取发送者昵称,如果无名字,此处为空字符串 251 | pub fn get_sender_nickname(&self) -> String { 252 | if let Some(v) = &self.sender.nickname { 253 | v.clone() 254 | } else { 255 | "".to_string() 256 | } 257 | } 258 | 259 | /// 借用 event 的 text,只是做了一下self.text.as_deref()的包装 260 | pub fn borrow_text(&self) -> Option<&str> { 261 | self.text.as_deref() 262 | } 263 | } 264 | -------------------------------------------------------------------------------- /src/bot/event/group_msg_event.rs: -------------------------------------------------------------------------------- 1 | use super::{Anonymous, Sender}; 2 | use crate::MsgEvent; 3 | use crate::bot::BotInformation; 4 | use crate::bot::event::InternalEvent; 5 | use crate::bot::plugin_builder::event::{Event, PostType}; 6 | use crate::bot::runtimebot::{CanSendApi, send_api_request_with_forget}; 7 | use crate::error::EventBuildError; 8 | use crate::types::ApiAndOneshot; 9 | use crate::{Message, bot::SendApi}; 10 | use log::info; 11 | use serde::Serialize; 12 | use serde_json::value::Index; 13 | use serde_json::{self, Value, json}; 14 | use tokio::sync::mpsc; 15 | 16 | #[cfg(feature = "cqstring")] 17 | use crate::bot::message::CQMessage; 18 | 19 | #[derive(Debug, Clone)] 20 | pub struct GroupMsgEvent { 21 | /// 事件发生的时间戳 22 | pub time: i64, 23 | /// 收到事件的机器人 登陆号 24 | pub self_id: i64, 25 | /// 上报类型 26 | pub post_type: PostType, 27 | /// 消息类型 28 | pub message_type: String, 29 | /// 消息子类型,如果是好友则是 friend,如果是群临时会话则是 group 30 | pub sub_type: String, 31 | /// 消息内容 32 | pub message: Message, 33 | /// 消息 ID 34 | pub message_id: i32, 35 | /// 群号 36 | pub group_id: i64, 37 | /// 发送者号 38 | pub user_id: i64, 39 | /// 匿名信息,如果不是匿名消息则为 null 40 | pub anonymous: Option, 41 | /// 原始消息内容 42 | pub raw_message: String, 43 | /// 字体 44 | pub font: i32, 45 | /// 发送人信息 46 | pub sender: Sender, 47 | 48 | /// 处理过的纯文本,如果是纯图片或无文本,此处为None 49 | pub text: Option, 50 | /// 处理过的文本,会解析成人类易读形式,里面会包含\[image\]\[face\]等解析后字符串 51 | pub human_text: String, 52 | /// 原始的onebot消息,已处理成json格式 53 | pub original_json: Value, 54 | 55 | /// 不推荐的消息发送方式 56 | pub api_tx: mpsc::Sender, 57 | } 58 | 59 | impl Event for GroupMsgEvent { 60 | fn de( 61 | event: &InternalEvent, 62 | _: &BotInformation, 63 | api_tx: &mpsc::Sender, 64 | ) -> Option { 65 | let InternalEvent::OneBotEvent(json_str) = event else { 66 | return None; 67 | }; 68 | let json: Value = serde_json::from_str(json_str).ok()?; 69 | let event = Self::new(api_tx.clone(), json).ok()?; 70 | 71 | Some(event) 72 | } 73 | } 74 | 75 | impl GroupMsgEvent { 76 | fn new( 77 | api_tx: mpsc::Sender, 78 | json: Value, 79 | ) -> Result { 80 | let msg_event = MsgEvent::new(api_tx, json)?; 81 | 82 | Ok(GroupMsgEvent { 83 | time: msg_event.time, 84 | self_id: msg_event.self_id, 85 | post_type: msg_event.post_type, 86 | message_type: msg_event.message_type, 87 | sub_type: msg_event.sub_type, 88 | message: msg_event.message, 89 | message_id: msg_event.message_id, 90 | group_id: match msg_event.group_id { 91 | Some(id) => id, 92 | None => { 93 | return Err(EventBuildError::ParseError( 94 | "group_id unreachable".to_string(), 95 | )); 96 | } 97 | }, 98 | user_id: msg_event.user_id, 99 | anonymous: msg_event.anonymous, 100 | raw_message: msg_event.raw_message, 101 | font: msg_event.font, 102 | sender: msg_event.sender, 103 | text: msg_event.text, 104 | human_text: msg_event.human_text, 105 | original_json: msg_event.original_json, 106 | api_tx: msg_event.api_tx, 107 | }) 108 | } 109 | } 110 | 111 | impl GroupMsgEvent { 112 | /// 直接从原始的 Json Value 获取某值 113 | /// 114 | /// # example 115 | /// 116 | /// ```ignore 117 | /// use kovi::PluginBuilder; 118 | /// 119 | /// PluginBuilder::on_msg(|event| async move { 120 | /// let time = event.get("time").and_then(|v| v.as_i64()).unwrap(); 121 | /// 122 | /// assert_eq!(time, event.time); 123 | /// }); 124 | /// ``` 125 | pub fn get(&self, index: I) -> Option<&Value> { 126 | self.original_json.get(index) 127 | } 128 | } 129 | 130 | impl std::ops::Index for GroupMsgEvent 131 | where 132 | I: Index, 133 | { 134 | type Output = Value; 135 | 136 | fn index(&self, index: I) -> &Self::Output { 137 | &self.original_json[index] 138 | } 139 | } 140 | 141 | impl GroupMsgEvent { 142 | fn reply_builder(&self, msg: T, auto_escape: bool) -> SendApi 143 | where 144 | T: Serialize, 145 | { 146 | SendApi::new( 147 | "send_msg", 148 | json!({ 149 | "message_type":"group", 150 | "group_id":self.group_id, 151 | "message":msg, 152 | "auto_escape":auto_escape, 153 | }), 154 | ) 155 | } 156 | 157 | #[cfg(not(feature = "cqstring"))] 158 | /// 快速回复消息 159 | pub fn reply(&self, msg: T) 160 | where 161 | Message: From, 162 | T: Serialize, 163 | { 164 | let msg = Message::from(msg); 165 | let send_msg = self.reply_builder(&msg, false); 166 | let nickname = self.get_sender_nickname(); 167 | let id = &self.sender.user_id; 168 | let message_type = &self.message_type; 169 | let group_id = &self.group_id; 170 | let human_msg = msg.to_human_string(); 171 | info!("[reply] [to {message_type} {group_id} {nickname} {id}]: {human_msg}"); 172 | 173 | send_api_request_with_forget(&self.api_tx, send_msg) 174 | } 175 | 176 | #[cfg(feature = "cqstring")] 177 | /// 快速回复消息 178 | pub fn reply(&self, msg: T) 179 | where 180 | CQMessage: From, 181 | T: Serialize, 182 | { 183 | let msg = CQMessage::from(msg); 184 | let send_msg = self.reply_builder(&msg, false); 185 | let nickname = self.get_sender_nickname(); 186 | let id = &self.sender.user_id; 187 | let message_type = &self.message_type; 188 | let group_id = &self.group_id; 189 | let human_msg = Message::from(msg).to_human_string(); 190 | info!("[reply] [to {message_type} {group_id} {nickname} {id}]: {human_msg}"); 191 | send_api_request_with_forget(&self.api_tx, send_msg); 192 | } 193 | 194 | #[cfg(not(feature = "cqstring"))] 195 | /// 快速回复消息并且**引用** 196 | pub fn reply_and_quote(&self, msg: T) 197 | where 198 | Message: From, 199 | T: Serialize, 200 | { 201 | let msg = Message::from(msg).add_reply(self.message_id); 202 | let send_msg = self.reply_builder(&msg, false); 203 | let nickname = self.get_sender_nickname(); 204 | let id = &self.sender.user_id; 205 | let message_type = &self.message_type; 206 | let group_id = &self.group_id; 207 | let human_msg = msg.to_human_string(); 208 | info!("[reply] [to {message_type} {group_id} {nickname} {id}]: {human_msg}"); 209 | 210 | send_api_request_with_forget(&self.api_tx, send_msg); 211 | } 212 | 213 | #[cfg(feature = "cqstring")] 214 | /// 快速回复消息并且**引用** 215 | pub fn reply_and_quote(&self, msg: T) 216 | where 217 | CQMessage: From, 218 | T: Serialize, 219 | { 220 | let msg = CQMessage::from(msg).add_reply(self.message_id); 221 | let send_msg = self.reply_builder(&msg, false); 222 | let nickname = self.get_sender_nickname(); 223 | let id = &self.sender.user_id; 224 | let message_type = &self.message_type; 225 | let group_id = &self.group_id; 226 | let human_msg = Message::from(msg).to_human_string(); 227 | info!("[reply] [to {message_type} {group_id} {nickname} {id}]: {human_msg}"); 228 | send_api_request_with_forget(&self.api_tx, send_msg); 229 | } 230 | 231 | #[cfg(feature = "cqstring")] 232 | /// 快速回复消息,并且**kovi不进行解析,直接发送此字符串** 233 | pub fn reply_text(&self, msg: T) 234 | where 235 | String: From, 236 | T: Serialize, 237 | { 238 | let send_msg = self.reply_builder(&msg, true); 239 | let nickname = self.get_sender_nickname(); 240 | let id = &self.sender.user_id; 241 | let message_type = &self.message_type; 242 | let group_id = &self.group_id; 243 | let msg = String::from(msg); 244 | info!("[reply] [to {message_type} {group_id} {nickname} {id}]: {msg}"); 245 | send_api_request_with_forget(&self.api_tx, send_msg); 246 | } 247 | 248 | /// 便捷获取文本,如果没有文本则会返回空字符串,如果只需要借用,请使用 `borrow_text()` 249 | pub fn get_text(&self) -> String { 250 | match self.text.clone() { 251 | Some(v) => v, 252 | None => "".to_string(), 253 | } 254 | } 255 | 256 | /// 便捷获取发送者昵称,如果无名字,此处为空字符串 257 | pub fn get_sender_nickname(&self) -> String { 258 | if let Some(v) = &self.sender.nickname { 259 | v.clone() 260 | } else { 261 | "".to_string() 262 | } 263 | } 264 | 265 | /// 借用 event 的 text,只是做了一下self.text.as_deref()的包装 266 | pub fn borrow_text(&self) -> Option<&str> { 267 | self.text.as_deref() 268 | } 269 | } 270 | 271 | impl CanSendApi for GroupMsgEvent { 272 | fn __get_api_tx(&self) -> &tokio::sync::mpsc::Sender { 273 | &self.api_tx 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /src/bot/event/admin_msg_event.rs: -------------------------------------------------------------------------------- 1 | use super::{Anonymous, Sender}; 2 | use crate::MsgEvent; 3 | use crate::bot::BotInformation; 4 | use crate::bot::event::InternalEvent; 5 | use crate::bot::plugin_builder::event::{Event, PostType}; 6 | use crate::bot::runtimebot::{CanSendApi, send_api_request_with_forget}; 7 | use crate::error::EventBuildError; 8 | use crate::types::ApiAndOneshot; 9 | use crate::{Message, bot::SendApi}; 10 | use log::info; 11 | use serde::Serialize; 12 | use serde_json::value::Index; 13 | use serde_json::{self, Value, json}; 14 | use tokio::sync::mpsc; 15 | 16 | #[cfg(feature = "cqstring")] 17 | use crate::bot::message::CQMessage; 18 | 19 | #[derive(Debug, Clone)] 20 | pub struct AdminMsgEvent { 21 | /// 事件发生的时间戳 22 | pub time: i64, 23 | /// 收到事件的机器人 登陆号 24 | pub self_id: i64, 25 | /// 上报类型 26 | pub post_type: PostType, 27 | /// 消息类型 28 | pub message_type: String, 29 | /// 消息子类型,如果是好友则是 friend,如果是群临时会话则是 group 30 | pub sub_type: String, 31 | /// 消息内容 32 | pub message: Message, 33 | /// 消息 ID 34 | pub message_id: i32, 35 | /// 群号 36 | pub group_id: Option, 37 | /// 发送者号 38 | pub user_id: i64, 39 | /// 匿名信息,如果不是匿名消息则为 null 40 | pub anonymous: Option, 41 | /// 原始消息内容 42 | pub raw_message: String, 43 | /// 字体 44 | pub font: i32, 45 | /// 发送人信息 46 | pub sender: Sender, 47 | 48 | /// 处理过的纯文本,如果是纯图片或无文本,此处为None 49 | pub text: Option, 50 | /// 处理过的文本,会解析成人类易读形式,里面会包含\[image\]\[face\]等解析后字符串 51 | pub human_text: String, 52 | /// 原始的onebot消息,已处理成json格式 53 | pub original_json: Value, 54 | 55 | /// 不推荐的消息发送方式 56 | pub api_tx: mpsc::Sender, 57 | } 58 | 59 | impl Event for AdminMsgEvent { 60 | fn de( 61 | event: &InternalEvent, 62 | bot_info: &BotInformation, 63 | api_tx: &mpsc::Sender, 64 | ) -> Option { 65 | let InternalEvent::OneBotEvent(json_str) = event else { 66 | return None; 67 | }; 68 | let json: Value = serde_json::from_str(json_str).ok()?; 69 | let event = Self::new(api_tx.clone(), json).ok()?; 70 | 71 | let mut admins = bot_info.deputy_admins.clone(); 72 | admins.insert(bot_info.main_admin); 73 | 74 | if !admins.contains(&event.sender.user_id) { 75 | return None; 76 | } 77 | 78 | Some(event) 79 | } 80 | } 81 | 82 | impl AdminMsgEvent { 83 | fn new( 84 | api_tx: mpsc::Sender, 85 | json: Value, 86 | ) -> Result { 87 | let msg_event = MsgEvent::new(api_tx, json)?; 88 | 89 | Ok(AdminMsgEvent { 90 | time: msg_event.time, 91 | self_id: msg_event.self_id, 92 | post_type: msg_event.post_type, 93 | message_type: msg_event.message_type, 94 | sub_type: msg_event.sub_type, 95 | message: msg_event.message, 96 | message_id: msg_event.message_id, 97 | group_id: msg_event.group_id, 98 | user_id: msg_event.user_id, 99 | anonymous: msg_event.anonymous, 100 | raw_message: msg_event.raw_message, 101 | font: msg_event.font, 102 | sender: msg_event.sender, 103 | text: msg_event.text, 104 | human_text: msg_event.human_text, 105 | original_json: msg_event.original_json, 106 | api_tx: msg_event.api_tx, 107 | }) 108 | } 109 | } 110 | 111 | impl AdminMsgEvent { 112 | /// 直接从原始的 Json Value 获取某值 113 | /// 114 | /// # example 115 | /// 116 | /// ```ignore 117 | /// use kovi::PluginBuilder; 118 | /// 119 | /// PluginBuilder::on_msg(|event| async move { 120 | /// let time = event.get("time").and_then(|v| v.as_i64()).unwrap(); 121 | /// 122 | /// assert_eq!(time, event.time); 123 | /// }); 124 | /// ``` 125 | pub fn get(&self, index: I) -> Option<&Value> { 126 | self.original_json.get(index) 127 | } 128 | } 129 | 130 | impl std::ops::Index for AdminMsgEvent 131 | where 132 | I: Index, 133 | { 134 | type Output = Value; 135 | 136 | fn index(&self, index: I) -> &Self::Output { 137 | &self.original_json[index] 138 | } 139 | } 140 | 141 | impl AdminMsgEvent { 142 | fn reply_builder(&self, msg: T, auto_escape: bool) -> SendApi 143 | where 144 | T: Serialize, 145 | { 146 | if self.is_private() { 147 | SendApi::new( 148 | "send_msg", 149 | json!({ 150 | "message_type":"private", 151 | "user_id":self.user_id, 152 | "message":msg, 153 | "auto_escape":auto_escape, 154 | }), 155 | ) 156 | } else { 157 | SendApi::new( 158 | "send_msg", 159 | json!({ 160 | "message_type":"group", 161 | "group_id":self.group_id.expect("unreachable"), 162 | "message":msg, 163 | "auto_escape":auto_escape, 164 | }), 165 | ) 166 | } 167 | } 168 | 169 | #[cfg(not(feature = "cqstring"))] 170 | /// 快速回复消息 171 | pub fn reply(&self, msg: T) 172 | where 173 | Message: From, 174 | T: Serialize, 175 | { 176 | let msg = Message::from(msg); 177 | let send_msg = self.reply_builder(&msg, false); 178 | let mut nickname = self.get_sender_nickname(); 179 | nickname.insert(0, ' '); 180 | let id = &self.sender.user_id; 181 | let message_type = &self.message_type; 182 | let group_id = match &self.group_id { 183 | Some(v) => format!(" {v}"), 184 | None => "".to_string(), 185 | }; 186 | let human_msg = msg.to_human_string(); 187 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 188 | 189 | send_api_request_with_forget(&self.api_tx, send_msg) 190 | } 191 | 192 | #[cfg(feature = "cqstring")] 193 | /// 快速回复消息 194 | pub fn reply(&self, msg: T) 195 | where 196 | CQMessage: From, 197 | T: Serialize, 198 | { 199 | let msg = CQMessage::from(msg); 200 | let send_msg = self.reply_builder(&msg, false); 201 | let mut nickname = self.get_sender_nickname(); 202 | nickname.insert(0, ' '); 203 | let id = &self.sender.user_id; 204 | let message_type = &self.message_type; 205 | let group_id = match &self.group_id { 206 | Some(v) => format!(" {v}"), 207 | None => "".to_string(), 208 | }; 209 | let human_msg = Message::from(msg).to_human_string(); 210 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 211 | send_api_request_with_forget(&self.api_tx, send_msg); 212 | } 213 | 214 | #[cfg(not(feature = "cqstring"))] 215 | /// 快速回复消息并且**引用** 216 | pub fn reply_and_quote(&self, msg: T) 217 | where 218 | Message: From, 219 | T: Serialize, 220 | { 221 | let msg = Message::from(msg).add_reply(self.message_id); 222 | let send_msg = self.reply_builder(&msg, false); 223 | 224 | let mut nickname = self.get_sender_nickname(); 225 | nickname.insert(0, ' '); 226 | let id = &self.sender.user_id; 227 | let message_type = &self.message_type; 228 | let group_id = match &self.group_id { 229 | Some(v) => format!(" {v}"), 230 | None => "".to_string(), 231 | }; 232 | let human_msg = msg.to_human_string(); 233 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 234 | 235 | send_api_request_with_forget(&self.api_tx, send_msg); 236 | } 237 | 238 | #[cfg(feature = "cqstring")] 239 | /// 快速回复消息并且**引用** 240 | pub fn reply_and_quote(&self, msg: T) 241 | where 242 | CQMessage: From, 243 | T: Serialize, 244 | { 245 | let msg = CQMessage::from(msg).add_reply(self.message_id); 246 | let send_msg = self.reply_builder(&msg, false); 247 | 248 | let mut nickname = self.get_sender_nickname(); 249 | nickname.insert(0, ' '); 250 | let id = &self.sender.user_id; 251 | let message_type = &self.message_type; 252 | let group_id = match &self.group_id { 253 | Some(v) => format!(" {v}"), 254 | None => "".to_string(), 255 | }; 256 | let human_msg = Message::from(msg).to_human_string(); 257 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 258 | send_api_request_with_forget(&self.api_tx, send_msg); 259 | } 260 | 261 | #[cfg(feature = "cqstring")] 262 | /// 快速回复消息,并且**kovi不进行解析,直接发送此字符串** 263 | pub fn reply_text(&self, msg: T) 264 | where 265 | String: From, 266 | T: Serialize, 267 | { 268 | let send_msg = self.reply_builder(&msg, true); 269 | let mut nickname = self.get_sender_nickname(); 270 | nickname.insert(0, ' '); 271 | let id = &self.sender.user_id; 272 | let message_type = &self.message_type; 273 | let group_id = match &self.group_id { 274 | Some(v) => format!(" {v}"), 275 | None => "".to_string(), 276 | }; 277 | let msg = String::from(msg); 278 | info!("[reply] [to {message_type}{group_id} {nickname} {id}]: {msg}"); 279 | send_api_request_with_forget(&self.api_tx, send_msg); 280 | } 281 | 282 | /// 便捷获取文本,如果没有文本则会返回空字符串,如果只需要借用,请使用 `borrow_text()` 283 | pub fn get_text(&self) -> String { 284 | match self.text.clone() { 285 | Some(v) => v, 286 | None => "".to_string(), 287 | } 288 | } 289 | 290 | /// 便捷获取发送者昵称,如果无名字,此处为空字符串 291 | pub fn get_sender_nickname(&self) -> String { 292 | if let Some(v) = &self.sender.nickname { 293 | v.clone() 294 | } else { 295 | "".to_string() 296 | } 297 | } 298 | 299 | /// 借用 event 的 text,只是做了一下self.text.as_deref()的包装 300 | pub fn borrow_text(&self) -> Option<&str> { 301 | self.text.as_deref() 302 | } 303 | 304 | pub fn is_group(&self) -> bool { 305 | self.group_id.is_some() 306 | } 307 | 308 | pub fn is_private(&self) -> bool { 309 | self.group_id.is_none() 310 | } 311 | } 312 | 313 | impl CanSendApi for AdminMsgEvent { 314 | fn __get_api_tx(&self) -> &tokio::sync::mpsc::Sender { 315 | &self.api_tx 316 | } 317 | } 318 | -------------------------------------------------------------------------------- /src/bot/event/msg_send_from_server_event.rs: -------------------------------------------------------------------------------- 1 | use super::{Anonymous, Sender}; 2 | use crate::MsgEvent; 3 | use crate::bot::BotInformation; 4 | use crate::bot::event::InternalEvent; 5 | use crate::bot::plugin_builder::event::{Event, PostType}; 6 | use crate::bot::runtimebot::{CanSendApi, send_api_request_with_forget}; 7 | use crate::error::EventBuildError; 8 | use crate::types::ApiAndOneshot; 9 | use crate::{Message, bot::SendApi}; 10 | use log::info; 11 | use serde::Serialize; 12 | use serde_json::value::Index; 13 | use serde_json::{self, Value, json}; 14 | use tokio::sync::mpsc; 15 | 16 | #[cfg(feature = "cqstring")] 17 | use crate::bot::message::CQMessage; 18 | 19 | #[derive(Debug, Clone)] 20 | pub struct MsgSendFromServerEvent { 21 | /// 事件发生的时间戳 22 | pub time: i64, 23 | /// 收到事件的机器人 登陆号 24 | pub self_id: i64, 25 | /// 上报类型 26 | pub post_type: PostType, 27 | /// 消息类型 28 | pub message_type: String, 29 | /// 消息子类型,如果是好友则是 friend,如果是群临时会话则是 group 30 | pub sub_type: String, 31 | /// 消息内容 32 | pub message: Message, 33 | /// 消息 ID 34 | pub message_id: i32, 35 | /// 群号 36 | pub group_id: Option, 37 | /// 发送者号 38 | pub user_id: i64, 39 | /// 匿名信息,如果不是匿名消息则为 null 40 | pub anonymous: Option, 41 | /// 原始消息内容 42 | pub raw_message: String, 43 | /// 字体 44 | pub font: i32, 45 | /// 发送人信息 46 | pub sender: Sender, 47 | 48 | /// 处理过的纯文本,如果是纯图片或无文本,此处为None 49 | pub text: Option, 50 | /// 处理过的文本,会解析成人类易读形式,里面会包含\[image\]\[face\]等解析后字符串 51 | pub human_text: String, 52 | /// 原始的onebot消息,已处理成json格式 53 | pub original_json: Value, 54 | 55 | /// 不推荐的消息发送方式 56 | pub api_tx: mpsc::Sender, 57 | } 58 | 59 | impl Event for MsgSendFromServerEvent { 60 | fn de( 61 | event: &InternalEvent, 62 | _: &BotInformation, 63 | api_tx: &mpsc::Sender, 64 | ) -> Option { 65 | let InternalEvent::OneBotEvent(json_str) = event else { 66 | return None; 67 | }; 68 | if !json_str.contains("message_sent") { 69 | return None; 70 | } 71 | 72 | let json = serde_json::from_str(json_str).ok()?; 73 | let event = Self::new(api_tx.clone(), json).ok()?; 74 | 75 | Some(event) 76 | } 77 | } 78 | 79 | impl MsgSendFromServerEvent { 80 | fn new( 81 | api_tx: mpsc::Sender, 82 | json: Value, 83 | ) -> Result { 84 | let msg_event = MsgEvent::new(api_tx, json)?; 85 | 86 | if msg_event.post_type != PostType::MessageSent { 87 | return Err(EventBuildError::ParseError( 88 | "MsgSendFromServerEvent Not message_sent".to_string(), 89 | )); 90 | } 91 | 92 | Ok(MsgSendFromServerEvent { 93 | time: msg_event.time, 94 | self_id: msg_event.self_id, 95 | post_type: msg_event.post_type, 96 | message_type: msg_event.message_type, 97 | sub_type: msg_event.sub_type, 98 | message: msg_event.message, 99 | message_id: msg_event.message_id, 100 | group_id: msg_event.group_id, 101 | user_id: msg_event.user_id, 102 | anonymous: msg_event.anonymous, 103 | raw_message: msg_event.raw_message, 104 | font: msg_event.font, 105 | sender: msg_event.sender, 106 | text: msg_event.text, 107 | human_text: msg_event.human_text, 108 | original_json: msg_event.original_json, 109 | api_tx: msg_event.api_tx, 110 | }) 111 | } 112 | } 113 | 114 | impl MsgSendFromServerEvent { 115 | /// 直接从原始的 Json Value 获取某值 116 | /// 117 | /// # example 118 | /// 119 | /// ```ignore 120 | /// use kovi::PluginBuilder; 121 | /// 122 | /// PluginBuilder::on_msg(|event| async move { 123 | /// let time = event.get("time").and_then(|v| v.as_i64()).unwrap(); 124 | /// 125 | /// assert_eq!(time, event.time); 126 | /// }); 127 | /// ``` 128 | pub fn get(&self, index: I) -> Option<&Value> { 129 | self.original_json.get(index) 130 | } 131 | } 132 | 133 | impl std::ops::Index for MsgSendFromServerEvent 134 | where 135 | I: Index, 136 | { 137 | type Output = Value; 138 | 139 | fn index(&self, index: I) -> &Self::Output { 140 | &self.original_json[index] 141 | } 142 | } 143 | 144 | impl MsgSendFromServerEvent { 145 | fn reply_builder(&self, msg: T, auto_escape: bool) -> SendApi 146 | where 147 | T: Serialize, 148 | { 149 | if self.is_private() { 150 | SendApi::new( 151 | "send_msg", 152 | json!({ 153 | "message_type":"private", 154 | "user_id":self.user_id, 155 | "message":msg, 156 | "auto_escape":auto_escape, 157 | }), 158 | ) 159 | } else { 160 | SendApi::new( 161 | "send_msg", 162 | json!({ 163 | "message_type":"group", 164 | "group_id":self.group_id.expect("unreachable"), 165 | "message":msg, 166 | "auto_escape":auto_escape, 167 | }), 168 | ) 169 | } 170 | } 171 | 172 | #[cfg(not(feature = "cqstring"))] 173 | /// 快速回复消息 174 | pub fn reply(&self, msg: T) 175 | where 176 | Message: From, 177 | T: Serialize, 178 | { 179 | let msg = Message::from(msg); 180 | let send_msg = self.reply_builder(&msg, false); 181 | let mut nickname = self.get_sender_nickname(); 182 | nickname.insert(0, ' '); 183 | let id = &self.sender.user_id; 184 | let message_type = &self.message_type; 185 | let group_id = match &self.group_id { 186 | Some(v) => format!(" {v}"), 187 | None => "".to_string(), 188 | }; 189 | let human_msg = msg.to_human_string(); 190 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 191 | 192 | send_api_request_with_forget(&self.api_tx, send_msg) 193 | } 194 | 195 | #[cfg(feature = "cqstring")] 196 | /// 快速回复消息 197 | pub fn reply(&self, msg: T) 198 | where 199 | CQMessage: From, 200 | T: Serialize, 201 | { 202 | let msg = CQMessage::from(msg); 203 | let send_msg = self.reply_builder(&msg, false); 204 | let mut nickname = self.get_sender_nickname(); 205 | nickname.insert(0, ' '); 206 | let id = &self.sender.user_id; 207 | let message_type = &self.message_type; 208 | let group_id = match &self.group_id { 209 | Some(v) => format!(" {v}"), 210 | None => "".to_string(), 211 | }; 212 | let human_msg = Message::from(msg).to_human_string(); 213 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 214 | send_api_request_with_forget(&self.api_tx, send_msg); 215 | } 216 | 217 | #[cfg(not(feature = "cqstring"))] 218 | /// 快速回复消息并且**引用** 219 | pub fn reply_and_quote(&self, msg: T) 220 | where 221 | Message: From, 222 | T: Serialize, 223 | { 224 | let msg = Message::from(msg).add_reply(self.message_id); 225 | let send_msg = self.reply_builder(&msg, false); 226 | 227 | let mut nickname = self.get_sender_nickname(); 228 | nickname.insert(0, ' '); 229 | let id = &self.sender.user_id; 230 | let message_type = &self.message_type; 231 | let group_id = match &self.group_id { 232 | Some(v) => format!(" {v}"), 233 | None => "".to_string(), 234 | }; 235 | let human_msg = msg.to_human_string(); 236 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 237 | 238 | send_api_request_with_forget(&self.api_tx, send_msg); 239 | } 240 | 241 | #[cfg(feature = "cqstring")] 242 | /// 快速回复消息并且**引用** 243 | pub fn reply_and_quote(&self, msg: T) 244 | where 245 | CQMessage: From, 246 | T: Serialize, 247 | { 248 | let msg = CQMessage::from(msg).add_reply(self.message_id); 249 | let send_msg = self.reply_builder(&msg, false); 250 | 251 | let mut nickname = self.get_sender_nickname(); 252 | nickname.insert(0, ' '); 253 | let id = &self.sender.user_id; 254 | let message_type = &self.message_type; 255 | let group_id = match &self.group_id { 256 | Some(v) => format!(" {v}"), 257 | None => "".to_string(), 258 | }; 259 | let human_msg = Message::from(msg).to_human_string(); 260 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 261 | send_api_request_with_forget(&self.api_tx, send_msg); 262 | } 263 | 264 | #[cfg(feature = "cqstring")] 265 | /// 快速回复消息,并且**kovi不进行解析,直接发送此字符串** 266 | pub fn reply_text(&self, msg: T) 267 | where 268 | String: From, 269 | T: Serialize, 270 | { 271 | let send_msg = self.reply_builder(&msg, true); 272 | let mut nickname = self.get_sender_nickname(); 273 | nickname.insert(0, ' '); 274 | let id = &self.sender.user_id; 275 | let message_type = &self.message_type; 276 | let group_id = match &self.group_id { 277 | Some(v) => format!(" {v}"), 278 | None => "".to_string(), 279 | }; 280 | let msg = String::from(msg); 281 | info!("[reply] [to {message_type}{group_id} {nickname} {id}]: {msg}"); 282 | send_api_request_with_forget(&self.api_tx, send_msg); 283 | } 284 | 285 | /// 便捷获取文本,如果没有文本则会返回空字符串,如果只需要借用,请使用 `borrow_text()` 286 | pub fn get_text(&self) -> String { 287 | match self.text.clone() { 288 | Some(v) => v, 289 | None => "".to_string(), 290 | } 291 | } 292 | 293 | /// 便捷获取发送者昵称,如果无名字,此处为空字符串 294 | pub fn get_sender_nickname(&self) -> String { 295 | if let Some(v) = &self.sender.nickname { 296 | v.clone() 297 | } else { 298 | "".to_string() 299 | } 300 | } 301 | 302 | /// 借用 event 的 text,只是做了一下self.text.as_deref()的包装 303 | pub fn borrow_text(&self) -> Option<&str> { 304 | self.text.as_deref() 305 | } 306 | 307 | pub fn is_group(&self) -> bool { 308 | self.group_id.is_some() 309 | } 310 | 311 | pub fn is_private(&self) -> bool { 312 | self.group_id.is_none() 313 | } 314 | } 315 | 316 | impl CanSendApi for MsgSendFromServerEvent { 317 | fn __get_api_tx(&self) -> &tokio::sync::mpsc::Sender { 318 | &self.api_tx 319 | } 320 | } 321 | -------------------------------------------------------------------------------- /src/bot/connect.rs: -------------------------------------------------------------------------------- 1 | use super::Server; 2 | use super::{ApiReturn, Bot, Host}; 3 | use crate::bot::handler::InternalInternalEvent; 4 | use crate::event::InternalEvent; 5 | use crate::types::ApiAndOneshot; 6 | use futures_util::stream::{SplitSink, SplitStream}; 7 | use futures_util::{SinkExt, StreamExt}; 8 | use http::HeaderValue; 9 | use log::{debug, error, warn}; 10 | use parking_lot::{Mutex, RwLock}; 11 | use std::error::Error; 12 | use std::fmt::Display; 13 | use std::{net::IpAddr, sync::Arc}; 14 | use tokio::net::TcpStream; 15 | use tokio::sync::mpsc::Sender; 16 | use tokio::sync::{mpsc, oneshot}; 17 | use tokio_tungstenite::tungstenite::Message; 18 | use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; 19 | use tokio_tungstenite::{connect_async, tungstenite::client::IntoClientRequest}; 20 | 21 | type ApiTxMap = Arc>>; 22 | 23 | impl Bot { 24 | pub(crate) async fn ws_connect( 25 | server: Server, 26 | api_rx: mpsc::Receiver, 27 | event_tx: mpsc::Sender, 28 | bot: Arc>, 29 | ) -> Result<(), Box> { 30 | #[allow(clippy::type_complexity)] 31 | let (event_connected_tx, event_connected_rx): ( 32 | oneshot::Sender>>, 33 | oneshot::Receiver>>, 34 | ) = oneshot::channel(); 35 | 36 | #[allow(clippy::type_complexity)] 37 | let (api_connected_tx, api_connected_rx): ( 38 | oneshot::Sender>>, 39 | oneshot::Receiver>>, 40 | ) = oneshot::channel(); 41 | 42 | { 43 | let mut bot_write = bot.write(); 44 | bot_write.spawn(Self::ws_event_connect( 45 | server.clone(), 46 | event_tx.clone(), 47 | event_connected_tx, 48 | bot.clone(), 49 | )); 50 | bot_write.spawn(Self::ws_send_api( 51 | server, 52 | api_rx, 53 | event_tx, 54 | api_connected_tx, 55 | bot.clone(), 56 | )); 57 | } 58 | 59 | let (res1, res2) = tokio::join!(event_connected_rx, api_connected_rx); 60 | let (res1, res2) = (res1.expect("unreachable"), res2.expect("unreachable")); 61 | match (res1, res2) { 62 | (Ok(_), Ok(_)) => Ok(()), 63 | (Err(e), _) | (_, Err(e)) => Err(e), 64 | } 65 | } 66 | 67 | pub(crate) async fn ws_event_connect( 68 | server: Server, 69 | event_tx: mpsc::Sender, 70 | connected_tx: oneshot::Sender>>, 71 | bot: Arc>, 72 | ) { 73 | let (host, port, access_token, secure) = 74 | (server.host, server.port, server.access_token, server.secure); 75 | 76 | let protocol = if secure { "wss" } else { "ws" }; 77 | let mut request = match host { 78 | Host::IpAddr(ip) => match ip { 79 | IpAddr::V4(ip) => format!("{protocol}://{ip}:{port}/event") 80 | .into_client_request() 81 | .expect("The domain name is invalid"), 82 | IpAddr::V6(ip) => format!("{protocol}://[{ip}]:{port}/event") 83 | .into_client_request() 84 | .expect("The domain name is invalid"), 85 | }, 86 | Host::Domain(domain) => format!("{protocol}://{domain}:{port}/event") 87 | .into_client_request() 88 | .expect("The domain name is invalid"), 89 | }; 90 | 91 | //增加Authorization头 92 | if !access_token.is_empty() { 93 | request.headers_mut().insert( 94 | "Authorization", 95 | HeaderValue::from_str(&format!("Bearer {access_token}")).expect("unreachable"), 96 | ); 97 | } 98 | 99 | let (ws_stream, _) = match connect_async(request).await { 100 | Ok(v) => v, 101 | Err(e) => { 102 | connected_tx 103 | .send(Err(e.into())) 104 | .expect("The OneBot connect channel has been established"); 105 | return; 106 | } 107 | }; 108 | 109 | connected_tx 110 | .send(Ok(())) 111 | .expect("The OneBot connect channel has been established"); 112 | 113 | let (_, read) = ws_stream.split(); 114 | 115 | let mut bot_write = bot.write(); 116 | bot_write.spawn(ws_event_connect_read(read, event_tx)); 117 | } 118 | 119 | pub(crate) async fn ws_send_api( 120 | server: Server, 121 | api_rx: mpsc::Receiver, 122 | event_tx: mpsc::Sender, 123 | connected_tx: oneshot::Sender>>, 124 | bot: Arc>, 125 | ) { 126 | let (host, port, access_token, secure) = 127 | (server.host, server.port, server.access_token, server.secure); 128 | 129 | let protocol = if secure { "wss" } else { "ws" }; 130 | let mut request = match host { 131 | Host::IpAddr(ip) => match ip { 132 | IpAddr::V4(ip) => format!("{protocol}://{ip}:{port}/api") 133 | .into_client_request() 134 | .expect("The domain name is invalid"), 135 | IpAddr::V6(ip) => format!("{protocol}://[{ip}]:{port}/api") 136 | .into_client_request() 137 | .expect("The domain name is invalid"), 138 | }, 139 | Host::Domain(domain) => format!("{protocol}://{domain}:{port}/api") 140 | .into_client_request() 141 | .expect("The domain name is invalid"), 142 | }; 143 | 144 | //增加Authorization头 145 | if !access_token.is_empty() { 146 | request.headers_mut().insert( 147 | "Authorization", 148 | HeaderValue::from_str(&format!("Bearer {access_token}")).expect("unreachable"), 149 | ); 150 | } 151 | 152 | let (ws_stream, _) = match connect_async(request).await { 153 | Ok(v) => v, 154 | Err(e) => { 155 | connected_tx 156 | .send(Err(e.into())) 157 | .expect("The OneBot connect channel has been established"); 158 | return; 159 | } 160 | }; 161 | 162 | connected_tx 163 | .send(Ok(())) 164 | .expect("The OneBot connect channel has been established"); 165 | 166 | let (write, read) = ws_stream.split(); 167 | let api_tx_map: ApiTxMap = Arc::new(Mutex::new(ahash::HashMap::<_, _>::default())); 168 | 169 | let mut bot_write = bot.write(); 170 | 171 | //读 172 | bot_write.spawn(ws_send_api_read( 173 | read, 174 | event_tx.clone(), 175 | Arc::clone(&api_tx_map), 176 | )); 177 | 178 | //写 179 | bot_write.spawn(ws_send_api_write( 180 | write, 181 | api_rx, 182 | event_tx, 183 | api_tx_map.clone(), 184 | )); 185 | } 186 | } 187 | 188 | async fn ws_event_connect_read( 189 | read: SplitStream>>, 190 | event_tx: Sender, 191 | ) { 192 | read.for_each(|msg| { 193 | let event_tx = event_tx.clone(); 194 | async { 195 | match msg { 196 | Ok(msg) => handle_msg(msg, event_tx).await, 197 | Err(e) => connection_failed_eprintln(e, event_tx).await, 198 | } 199 | } 200 | }) 201 | .await; 202 | 203 | async fn handle_msg( 204 | msg: tokio_tungstenite::tungstenite::Message, 205 | event_tx: Sender, 206 | ) { 207 | if !msg.is_text() { 208 | return; 209 | } 210 | 211 | let text = msg.to_text().expect("unreachable"); 212 | if let Err(e) = event_tx 213 | .send(InternalInternalEvent::OneBotEvent( 214 | InternalEvent::OneBotEvent(text.to_string()), 215 | )) 216 | .await 217 | { 218 | debug!("通道关闭:{e}") 219 | } 220 | } 221 | } 222 | 223 | async fn ws_send_api_read( 224 | read: SplitStream>>, 225 | event_tx: Sender, 226 | api_tx_map: ApiTxMap, 227 | ) { 228 | read.for_each(|msg| { 229 | let event_tx = event_tx.clone(); 230 | async { 231 | match msg { 232 | Ok(msg) => handle_msg(msg, event_tx, api_tx_map.clone()).await, 233 | Err(e) => connection_failed_eprintln(e, event_tx).await, 234 | } 235 | } 236 | }) 237 | .await; 238 | 239 | async fn handle_msg( 240 | msg: tokio_tungstenite::tungstenite::Message, 241 | event_tx: Sender, 242 | api_tx_map: ApiTxMap, 243 | ) { 244 | if msg.is_close() { 245 | connection_failed_eprintln(format!("{msg}\nBot api connection failed"), event_tx).await; 246 | return; 247 | } 248 | if !msg.is_text() { 249 | return; 250 | } 251 | 252 | let text = msg.to_text().expect("unreachable"); 253 | 254 | debug!("{text}"); 255 | 256 | let return_value: ApiReturn = match serde_json::from_str(text) { 257 | Ok(v) => v, 258 | Err(_) => { 259 | debug!("Unknow api return: {text}"); 260 | return; 261 | } 262 | }; 263 | 264 | if return_value.status != "ok" { 265 | warn!("Api return error: {text}") 266 | } 267 | 268 | let api_tx_cache = { 269 | let mut api_tx_map = api_tx_map.lock(); 270 | match api_tx_map.remove(&return_value.echo) { 271 | Some(v) => v, 272 | None => { 273 | log::error!("Api return echo not found from api_tx_map: {text}"); 274 | return; 275 | } 276 | } 277 | }; 278 | 279 | let return_value = if return_value.status.to_lowercase() == "ok" { 280 | Ok(return_value) 281 | } else { 282 | Err(return_value) 283 | }; 284 | 285 | if let Some(tx) = api_tx_cache.1 286 | && tx.send(return_value.clone()).is_err() { 287 | log::debug!("Return Api to plugin failed, the receiver has been closed") 288 | }; 289 | 290 | event_tx 291 | .send(InternalInternalEvent::OneBotEvent( 292 | InternalEvent::OneBotApiEvent((api_tx_cache.0, return_value)), 293 | )) 294 | .await 295 | .expect("The event_tx is closed"); 296 | } 297 | } 298 | 299 | async fn ws_send_api_write( 300 | mut write: SplitSink>, Message>, 301 | mut api_rx: mpsc::Receiver, 302 | event_tx: Sender, 303 | api_tx_map: ApiTxMap, 304 | ) { 305 | while let Some((api_msg, return_api_tx)) = api_rx.recv().await { 306 | let event_tx = event_tx.clone(); 307 | debug!("{api_msg}"); 308 | 309 | api_tx_map 310 | .lock() 311 | .insert(api_msg.echo.clone(), (api_msg.clone(), return_api_tx)); 312 | 313 | let msg = tokio_tungstenite::tungstenite::Message::text(api_msg.to_string()); 314 | 315 | if let Err(e) = write.send(msg).await { 316 | connection_failed_eprintln(e, event_tx).await; 317 | } 318 | } 319 | } 320 | 321 | async fn connection_failed_eprintln(e: E, event_tx: Sender) 322 | where 323 | E: Display, 324 | { 325 | log::error!("{e}\nBot connection failed, please check the configuration and restart."); 326 | if let Err(e) = event_tx 327 | .send(InternalInternalEvent::KoviEvent( 328 | crate::bot::handler::KoviEvent::Drop, 329 | )) 330 | .await 331 | { 332 | error!("通道关闭,{e}") 333 | }; 334 | } 335 | -------------------------------------------------------------------------------- /src/plugin/plugin_builder.rs: -------------------------------------------------------------------------------- 1 | use crate::RT; 2 | use crate::bot::BotInformation; 3 | use crate::bot::Host; 4 | use crate::bot::plugin_builder::event::Event; 5 | use crate::bot::{Bot, runtimebot::RuntimeBot}; 6 | use crate::event::InternalEvent; 7 | use crate::event::MsgSendFromServerEvent; 8 | use crate::event::{AdminMsgEvent, GroupMsgEvent, PrivateMsgEvent}; 9 | use crate::plugin::{PLUGIN_BUILDER, PLUGIN_NAME}; 10 | use crate::types::{ApiAndOneshot, NoArgsFn, PinFut}; 11 | use croner::Cron; 12 | use croner::errors::CronError; 13 | use event::{MsgEvent, NoticeEvent, RequestEvent}; 14 | use log::error; 15 | use parking_lot::RwLock; 16 | use std::any::Any; 17 | use std::future::Future; 18 | use std::sync::Arc; 19 | use tokio::sync::mpsc; 20 | 21 | // 兼容旧版本 22 | pub use crate::bot::event; 23 | 24 | macro_rules! assert_right_place { 25 | ($expr:expr) => { 26 | match $expr { 27 | Ok(val) => val, 28 | Err(_) => panic!("Using PluginBuilder in wrong place"), 29 | } 30 | }; 31 | } 32 | 33 | pub(crate) trait DowncastArc: Any { 34 | fn downcast_arc(self: Arc) -> Result, Arc>; 35 | } 36 | impl DowncastArc for T { 37 | fn downcast_arc(self: Arc) -> Result, Arc> { 38 | if (*self).type_id() == std::any::TypeId::of::() { 39 | let raw: *const Self = Arc::into_raw(self); 40 | Ok(unsafe { Arc::from_raw(raw as *const U) }) 41 | } else { 42 | Err(self) 43 | } 44 | } 45 | } 46 | 47 | #[derive(Clone, Default)] 48 | pub(crate) struct Listen { 49 | pub(crate) list: Vec>, 50 | pub(crate) drop: Vec, 51 | } 52 | impl Listen { 53 | pub(crate) fn clear(&mut self) { 54 | self.list.clear(); 55 | self.drop.clear(); 56 | self.list.shrink_to_fit(); 57 | self.drop.shrink_to_fit(); 58 | } 59 | } 60 | type ArcTypeDeFn = Arc< 61 | dyn Fn(&InternalEvent, &BotInformation, &mpsc::Sender) -> Option> 62 | + Send 63 | + Sync, 64 | >; 65 | 66 | #[derive(Clone)] 67 | pub(crate) struct ListenInner { 68 | pub(crate) type_id: std::any::TypeId, 69 | pub(crate) type_de: ArcTypeDeFn, 70 | pub(crate) handler: Arc) -> PinFut + Send + Sync>, 71 | } 72 | 73 | impl Listen { 74 | pub(crate) fn on(&mut self, handler: F) 75 | where 76 | T: Event, 77 | F: Fn(Arc) -> Fut + Send + Sync + 'static, 78 | Fut: Future + Send, 79 | Fut::Output: Send, 80 | { 81 | let handler = Arc::new(handler); 82 | 83 | self.list.push(Arc::new(ListenInner { 84 | type_id: std::any::TypeId::of::(), 85 | type_de: Arc::new(|value, bot_info, sender| { 86 | Some(Arc::new(T::de(value, bot_info, sender)?)) 87 | }), 88 | handler: Arc::new(move |evt: Arc| { 89 | let downcasted = evt.downcast_arc::(); 90 | 91 | match downcasted { 92 | Ok(downcasted) => Box::pin({ 93 | let handler = handler.clone(); 94 | async move { 95 | handler(downcasted).await; 96 | } 97 | }), 98 | Err(_) => panic!("Type downcasted error!"), 99 | } 100 | }), 101 | })); 102 | } 103 | } 104 | 105 | #[derive(Clone)] 106 | pub struct PluginBuilder { 107 | pub(crate) bot: Arc>, 108 | pub(crate) runtime_bot: Arc, 109 | } 110 | 111 | impl PluginBuilder { 112 | pub(crate) fn new( 113 | name: String, 114 | bot: Arc>, 115 | host: Host, 116 | port: u16, 117 | api_tx: mpsc::Sender, 118 | ) -> Self { 119 | let bot_weak = Arc::downgrade(&bot); 120 | 121 | let runtime_bot = Arc::new(RuntimeBot { 122 | host, 123 | port, 124 | 125 | bot: bot_weak, 126 | plugin_name: name, 127 | api_tx, 128 | }); 129 | 130 | PluginBuilder { bot, runtime_bot } 131 | } 132 | 133 | pub fn get_runtime_bot() -> Arc { 134 | assert_right_place!(PLUGIN_BUILDER.try_with(|p| p.runtime_bot.clone())) 135 | } 136 | 137 | pub fn get_plugin_name() -> String { 138 | assert_right_place!(PLUGIN_BUILDER.try_with(|p| p.runtime_bot.plugin_name.to_string())) 139 | } 140 | 141 | pub fn get_plugin_host() -> (Host, u16) { 142 | assert_right_place!( 143 | PLUGIN_BUILDER.try_with(|p| (p.runtime_bot.host.clone(), p.runtime_bot.port)) 144 | ) 145 | } 146 | } 147 | 148 | impl PluginBuilder { 149 | pub fn on(handler: impl Fn(Arc) -> Fut + Send + Sync + 'static) 150 | where 151 | Fut: Future + Send, 152 | Fut::Output: Send, 153 | { 154 | assert_right_place!(PLUGIN_BUILDER.try_with(|p| { 155 | let mut bot = p.bot.write(); 156 | let bot_plugin = bot.plugins.get_mut(&p.runtime_bot.plugin_name).expect(""); 157 | 158 | bot_plugin.listen.on(handler); 159 | })); 160 | } 161 | 162 | /// 注册事件处理函数。 163 | pub fn on_msg(handler: F) 164 | where 165 | F: Fn(Arc) -> Fut + Send + Sync + 'static, 166 | Fut: Future + Send, 167 | Fut::Output: Send, 168 | { 169 | PluginBuilder::on::(handler) 170 | } 171 | 172 | /// 注册事件处理函数。 173 | pub fn on_admin_msg(handler: F) 174 | where 175 | F: Fn(Arc) -> Fut + Send + Sync + 'static, 176 | Fut: Future + Send, 177 | Fut::Output: Send, 178 | { 179 | PluginBuilder::on::(handler) 180 | } 181 | 182 | /// 注册事件处理函数。 183 | pub fn on_private_msg(handler: F) 184 | where 185 | F: Fn(Arc) -> Fut + Send + Sync + 'static, 186 | Fut: Future + Send, 187 | Fut::Output: Send, 188 | { 189 | PluginBuilder::on::(handler) 190 | } 191 | 192 | /// 注册事件处理函数。 193 | pub fn on_group_msg(handler: F) 194 | where 195 | F: Fn(Arc) -> Fut + Send + Sync + 'static, 196 | Fut: Future + Send, 197 | Fut::Output: Send, 198 | { 199 | PluginBuilder::on::(handler) 200 | } 201 | 202 | #[deprecated( 203 | note = "请使用 `PluginBuilder::on::(|event: Arc| fn())` 代替" 204 | )] 205 | /// 注册事件处理函数。 206 | pub fn on_msg_send(handler: F) 207 | where 208 | F: Fn(Arc) -> Fut + Send + Sync + 'static, 209 | Fut: Future + Send, 210 | Fut::Output: Send, 211 | { 212 | PluginBuilder::on::(handler) 213 | } 214 | 215 | /// 注册事件处理函数。 216 | pub fn on_notice(handler: F) 217 | where 218 | F: Fn(Arc) -> Fut + Send + Sync + 'static, 219 | Fut: Future + Send, 220 | Fut::Output: Send, 221 | { 222 | PluginBuilder::on::(handler) 223 | } 224 | 225 | /// 注册事件处理函数。 226 | pub fn on_request(handler: F) 227 | where 228 | F: Fn(Arc) -> Fut + Send + Sync + 'static, 229 | Fut: Future + Send, 230 | Fut::Output: Send, 231 | { 232 | PluginBuilder::on::(handler) 233 | } 234 | 235 | #[deprecated(note = "请使用 `on_notice` 代替")] 236 | /// 注册事件处理函数。 237 | pub fn on_all_notice(handler: F) 238 | where 239 | F: Fn(Arc) -> Fut + Send + Sync + 'static, 240 | Fut: Future + Send, 241 | Fut::Output: Send, 242 | { 243 | Self::on_notice(handler) 244 | } 245 | 246 | #[deprecated(note = "请使用 `on_request` 代替")] 247 | /// 注册事件处理函数。 248 | pub fn on_all_request(handler: F) 249 | where 250 | F: Fn(Arc) -> Fut + Send + Sync + 'static, 251 | Fut: Future + Send, 252 | Fut::Output: Send, 253 | { 254 | Self::on_request(handler) 255 | } 256 | 257 | /// 注册程序结束事件处理函数。 258 | /// 259 | /// 注册处理程序,用于处理接收到的程序结束事件。 260 | pub fn drop(handler: F) 261 | where 262 | F: Fn() -> Fut + Send + Sync + 'static, 263 | Fut: Future + Send, 264 | Fut::Output: Send, 265 | { 266 | assert_right_place!(PLUGIN_BUILDER.try_with(|p| { 267 | let mut bot = p.bot.write(); 268 | let bot_plugin = bot 269 | .plugins 270 | .get_mut(&p.runtime_bot.plugin_name) 271 | .expect("unreachable"); 272 | 273 | bot_plugin.listen.drop.push(Arc::new({ 274 | let handler = Arc::new(handler); 275 | move || { 276 | Box::pin({ 277 | let handler = handler.clone(); 278 | async move { 279 | handler().await; 280 | } 281 | }) 282 | } 283 | })); 284 | })); 285 | } 286 | 287 | /// 注册定时任务。 288 | /// 289 | /// 传入 Cron 。 290 | pub fn cron(cron: &str, handler: F) -> Result<(), CronError> 291 | where 292 | F: Fn() -> Fut + Send + Sync + 'static, 293 | Fut: Future + Send, 294 | Fut::Output: Send, 295 | { 296 | assert_right_place!(PLUGIN_BUILDER.try_with(|p| { 297 | let cron = match Cron::new(cron).with_seconds_optional().parse() { 298 | Ok(v) => v, 299 | Err(e) => return Err(e), 300 | }; 301 | Self::run_cron_task(p, cron, handler); 302 | Ok(()) 303 | })) 304 | } 305 | 306 | /// 注册定时任务。 307 | /// 308 | /// 传入 Cron 。 309 | pub fn cron_use_croner(cron: Cron, handler: F) 310 | where 311 | F: Fn() -> Fut + Send + Sync + 'static, 312 | Fut: Future + Send, 313 | Fut::Output: Send, 314 | { 315 | assert_right_place!(PLUGIN_BUILDER.try_with(|p| { 316 | Self::run_cron_task(p, cron, handler); 317 | })); 318 | } 319 | 320 | fn run_cron_task(p: &PluginBuilder, cron: Cron, handler: F) 321 | where 322 | F: Fn() -> Fut + Send + Sync + 'static, 323 | Fut: Future + Send, 324 | Fut::Output: Send, 325 | { 326 | let name = Arc::new(p.runtime_bot.plugin_name.clone()); 327 | let mut enabled = { 328 | let bot = p.bot.read(); 329 | let plugin = bot.plugins.get(&*name).expect("unreachable"); 330 | plugin.enabled.subscribe() 331 | }; 332 | RT.spawn(PLUGIN_NAME.scope(name.clone(), async move { 333 | 334 | tokio::select! { 335 | _ = async { 336 | loop { 337 | let now = chrono::Local::now(); 338 | let next = match cron.find_next_occurrence(&now, false) { 339 | Ok(v) => v, 340 | Err(e) => { 341 | error!("{name} cron task error: {e}"); 342 | break; 343 | } 344 | }; 345 | let time = next - now; 346 | let duration = std::time::Duration::from_millis(time.num_milliseconds() as u64); 347 | tokio::time::sleep(duration).await; 348 | handler().await; 349 | } 350 | } => {} 351 | _ = async { 352 | loop { 353 | enabled.changed().await.expect("The enabled channel closed"); 354 | if !*enabled.borrow_and_update() { 355 | break; 356 | } 357 | } 358 | } => {} 359 | } 360 | })); 361 | } 362 | } 363 | 364 | #[macro_export] 365 | macro_rules! async_move { 366 | // 匹配没有事件参数的情况 367 | (;$($var:ident),*; $($body:tt)*) => { 368 | { 369 | $(let $var = $var.clone();)* 370 | move || { 371 | $(let $var = $var.clone();)* 372 | async move 373 | $($body)* 374 | } 375 | } 376 | }; 377 | 378 | // 匹配有事件参数的情况 379 | ($event:ident; $($var:ident),*; $($body:tt)*) => { 380 | { 381 | $(let $var = $var.clone();)* 382 | move |$event| { 383 | $(let $var = $var.clone();)* 384 | async move 385 | $($body)* 386 | } 387 | } 388 | }; 389 | 390 | // 匹配只要一次clone的情况(自己tokio::spawn一个新线程) 391 | ($($var:ident),*;$($body:tt)*) => { 392 | { 393 | $(let $var = $var.clone();)* 394 | async move 395 | $($body)* 396 | } 397 | }; 398 | } 399 | -------------------------------------------------------------------------------- /src/bot/handler.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | bot::{ 3 | plugin_builder::{ListenInner, event::Event}, 4 | *, 5 | }, 6 | event::InternalEvent, 7 | plugin::PLUGIN_NAME, 8 | types::ApiAndOneshot, 9 | }; 10 | use log::info; 11 | use parking_lot::RwLock; 12 | use plugin_builder::event::MsgEvent; 13 | use std::{any::TypeId, sync::Arc}; 14 | 15 | /// Kovi内部事件 16 | pub(crate) enum InternalInternalEvent { 17 | KoviEvent(KoviEvent), 18 | OneBotEvent(InternalEvent), 19 | } 20 | 21 | pub(crate) enum KoviEvent { 22 | Drop, 23 | } 24 | 25 | impl Bot { 26 | pub(crate) async fn handler_event( 27 | bot: Arc>, 28 | event: InternalInternalEvent, 29 | api_tx: mpsc::Sender, 30 | ) { 31 | match event { 32 | InternalInternalEvent::KoviEvent(event) => Self::handle_kovi_event(bot, event).await, 33 | InternalInternalEvent::OneBotEvent(msg) => { 34 | Self::handler_internal_event(bot, msg, api_tx).await 35 | } 36 | } 37 | } 38 | 39 | pub(crate) async fn handle_kovi_event(bot: Arc>, event: KoviEvent) { 40 | let drop_task = { 41 | let mut bot_write = bot.write(); 42 | match event { 43 | KoviEvent::Drop => { 44 | #[cfg(any(feature = "save_plugin_status", feature = "save_bot_admin"))] 45 | bot_write.save_bot_status(); 46 | let mut task_vec = Vec::new(); 47 | for plugin in bot_write.plugins.values_mut() { 48 | task_vec.push(plugin.shutdown()); 49 | } 50 | Some(task_vec) 51 | } 52 | } 53 | }; 54 | if let Some(drop_task) = drop_task { 55 | for task in drop_task { 56 | let _ = task.await; 57 | } 58 | } 59 | } 60 | 61 | async fn handler_internal_event( 62 | bot: Arc>, 63 | msg: InternalEvent, 64 | api_tx: mpsc::Sender, 65 | ) { 66 | let bot_read = bot.read(); 67 | 68 | let info = bot_read.information.clone(); 69 | 70 | let plugin_iter = bot_read.plugins.iter(); 71 | 72 | let plugin_cache = plugin_iter 73 | .clone() 74 | .map(|(name, plugin)| { 75 | let name = Arc::new(name.to_owned()); 76 | (name.clone(), PluginCache { 77 | name, 78 | #[cfg(feature = "plugin-access-control")] 79 | acc: AccCache::new( 80 | plugin.access_control, 81 | plugin.list_mode, 82 | plugin.access_list.clone(), 83 | ), 84 | bot_info: info.clone(), 85 | enabled: plugin.enabled.subscribe(), 86 | }) 87 | }) 88 | .collect::, PluginCache>>(); 89 | 90 | let type_plugin_map = { 91 | let mut type_plugin_map: PluginMap = Default::default(); 92 | for (name, plugin) in plugin_iter { 93 | for listen in &plugin.listen.list { 94 | let plugin_map = type_plugin_map.entry(listen.type_id).or_default(); 95 | 96 | let plugin_vec = plugin_map 97 | .plugins 98 | .entry(plugin_cache[name].name.clone()) 99 | .or_default(); 100 | 101 | plugin_vec.push(listen.clone()); 102 | } 103 | } 104 | type_plugin_map 105 | }; 106 | 107 | drop(bot_read); 108 | 109 | let msg_event = MsgEvent::de(&msg, &info.read(), &api_tx).map(|e| { 110 | log_msg_event(&e); 111 | Arc::new(e) 112 | }); 113 | 114 | struct SharedData { 115 | msg: InternalEvent, 116 | api_tx: mpsc::Sender, 117 | plugin_cache: ahash::HashMap, PluginCache>, 118 | } 119 | 120 | let shared_data = Arc::new(SharedData { 121 | msg, 122 | api_tx, 123 | plugin_cache, 124 | }); 125 | 126 | for (type_id, plugin_map) in type_plugin_map { 127 | tokio::spawn(type_handler( 128 | type_id, 129 | plugin_map, 130 | msg_event.clone(), 131 | shared_data.clone(), 132 | )); 133 | } 134 | 135 | async fn type_handler( 136 | type_id: TypeId, 137 | plugin_map: EventHandler, 138 | msg_event: Option>, 139 | shared_data: Arc, 140 | ) { 141 | let mut event_cache = if type_id == TypeId::of::() { 142 | msg_event.clone().map(|arc| arc as Arc) 143 | } else { 144 | None 145 | }; 146 | 147 | for (name, plugin_vec) in plugin_map.plugins.into_iter() { 148 | let plugin_cache = &shared_data.plugin_cache[&name]; 149 | 150 | #[cfg(feature = "plugin-access-control")] 151 | if let Some(event) = &msg_event { 152 | // 判断是否黑白名单 153 | if !is_access(&plugin_cache.acc, event) { 154 | continue; 155 | } 156 | } 157 | 158 | for listen in plugin_vec { 159 | let event = match &event_cache { 160 | Some(v) => v.clone(), 161 | None => { 162 | let event_opt = (listen.type_de)( 163 | &shared_data.msg, 164 | &plugin_cache.bot_info.read(), 165 | &shared_data.api_tx, 166 | ); 167 | 168 | match event_opt { 169 | Some(event) => { 170 | event_cache = Some(event.clone()); 171 | event 172 | } 173 | None => return, 174 | } 175 | } 176 | }; 177 | 178 | let name = name.clone(); 179 | let enabled = plugin_cache.enabled.clone(); 180 | 181 | RT.spawn(async move { 182 | tokio::select! { 183 | _ = PLUGIN_NAME.scope(name, handle_listen(listen, event)) => {} 184 | _ = monitor_enabled_state(enabled) => {} 185 | } 186 | }); 187 | } 188 | } 189 | } 190 | 191 | async fn monitor_enabled_state(mut enabled: watch::Receiver) { 192 | loop { 193 | enabled 194 | .changed() 195 | .await 196 | .expect("The enabled signal was dropped"); 197 | if !*enabled.borrow_and_update() { 198 | break; 199 | } 200 | } 201 | } 202 | 203 | fn log_msg_event(event: &MsgEvent) { 204 | info!( 205 | "[{message_type}{group_id}{nickname} {id}]: {text}", 206 | message_type = event.message_type, 207 | group_id = match event.group_id { 208 | Some(id) => id.to_string(), 209 | None => "".to_string(), 210 | }, 211 | nickname = match &event.sender.nickname { 212 | Some(nickname) => nickname, 213 | None => "", 214 | }, 215 | id = event.sender.user_id, 216 | text = event.message.to_human_string() 217 | ); 218 | } 219 | 220 | async fn handle_listen(listen: Arc, cache_event: Arc) { 221 | (*listen.handler)(cache_event).await; 222 | } 223 | } 224 | } 225 | 226 | struct PluginCache { 227 | name: Arc, 228 | #[cfg(feature = "plugin-access-control")] 229 | acc: AccCache, 230 | bot_info: Arc>, 231 | enabled: watch::Receiver, 232 | } 233 | 234 | #[cfg(feature = "plugin-access-control")] 235 | struct AccCache { 236 | pub(crate) access_control: bool, 237 | pub(crate) list_mode: AccessControlMode, 238 | pub(crate) access_list: AccessList, 239 | } 240 | 241 | #[cfg(feature = "plugin-access-control")] 242 | impl AccCache { 243 | pub fn new( 244 | access_control: bool, 245 | list_mode: AccessControlMode, 246 | access_list: AccessList, 247 | ) -> Self { 248 | Self { 249 | access_control, 250 | list_mode, 251 | access_list, 252 | } 253 | } 254 | } 255 | 256 | #[cfg(feature = "plugin-access-control")] 257 | fn is_access(plugin: &AccCache, event: &MsgEvent) -> bool { 258 | if !plugin.access_control { 259 | return true; 260 | } 261 | 262 | let access_list = &plugin.access_list; 263 | let in_group = event.is_group(); 264 | 265 | match (plugin.list_mode, in_group) { 266 | (AccessControlMode::WhiteList, true) => access_list 267 | .groups 268 | .contains(event.group_id.as_ref().expect("unreachable")), 269 | (AccessControlMode::WhiteList, false) => { 270 | access_list.friends.contains(&event.sender.user_id) 271 | } 272 | (AccessControlMode::BlackList, true) => !access_list 273 | .groups 274 | .contains(event.group_id.as_ref().expect("unreachable")), 275 | (AccessControlMode::BlackList, false) => { 276 | !access_list.friends.contains(&event.sender.user_id) 277 | } 278 | } 279 | } 280 | 281 | #[allow(dead_code)] 282 | #[derive(Default)] 283 | struct EventHandler { 284 | plugins: ahash::HashMap, Vec>>, 285 | } 286 | 287 | #[allow(warnings)] 288 | type PluginMap<'a> = 289 | HashMap>; 290 | 291 | #[allow(warnings)] 292 | type TypeEventCacheMap = 293 | HashMap>, std::hash::BuildHasherDefault>; 294 | 295 | /// With TypeIds as keys, there's no need to hash them. They are already hashes 296 | /// themselves, coming from the compiler. The IdHasher holds the u64 of 297 | /// the TypeId, and then returns it, instead of doing any bit fiddling. 298 | #[derive(Default, Debug)] 299 | struct IdHasher(u64); 300 | 301 | impl std::hash::Hasher for IdHasher { 302 | fn write(&mut self, _: &[u8]) { 303 | unreachable!("TypeId calls write_u64"); 304 | } 305 | 306 | #[inline] 307 | fn write_u64(&mut self, id: u64) { 308 | self.0 = id; 309 | } 310 | 311 | #[inline] 312 | fn finish(&self) -> u64 { 313 | self.0 314 | } 315 | } 316 | 317 | // if let Some(lifecycle_event) = LifecycleEvent::de(&msg, &bot_read.information, &api_tx) { 318 | // tokio::spawn(lifecycle_event::handler_lifecycle_log_bot_enable( 319 | // api_tx.clone(), 320 | // )); 321 | // cache.insert( 322 | // std::any::TypeId::of::(), 323 | // Some(Arc::new(lifecycle_event)), 324 | // ); 325 | // }; 326 | 327 | // // 这里在 没有 plugin-access-control 会警告所以用 _ 328 | // let _msg_sevent_opt = match msg_event { 329 | // Some(event) => { 330 | // let event = Arc::new(event); 331 | // log_msg_event(&event); 332 | // cache.insert(std::any::TypeId::of::(), Some(event.clone())); 333 | // Some(event) 334 | // } 335 | // None => None, 336 | // }; 337 | 338 | // for (name, plugin) in bot_read.plugins.iter() { 339 | // let name_ = Arc::new(name.clone()); 340 | 341 | // for listen in &plugin.listen.list { 342 | // let name = name_.clone(); 343 | // let api_tx = api_tx.clone(); 344 | 345 | // let cache_event = match cache.get(&listen.type_id) { 346 | // Some(event) => match event { 347 | // None => { 348 | // continue; 349 | // } 350 | // Some(event) => event.clone(), 351 | // }, 352 | // None => { 353 | // let event_opt = (listen.type_de)(&msg, &bot_read.information, &api_tx); 354 | // cache.insert(listen.type_id, event_opt.clone()); 355 | // match event_opt { 356 | // Some(event) => event, 357 | // None => continue, 358 | // } 359 | // } 360 | // }; 361 | 362 | // let listen = listen.clone(); 363 | // let enabled = plugin.enabled.subscribe(); 364 | 365 | // RT.spawn(async move { 366 | // tokio::select! { 367 | // _ = PLUGIN_NAME.scope(name, Self::handle_listen(listen, cache_event)) => {} 368 | // _ = monitor_enabled_state(enabled) => {} 369 | // } 370 | // }); 371 | // } 372 | // } 373 | -------------------------------------------------------------------------------- /src/bot/runtimebot/kovi_api.rs: -------------------------------------------------------------------------------- 1 | use super::RuntimeBot; 2 | use crate::error::BotError; 3 | use crate::plugin::PluginInfo; 4 | use crate::types::ApiAndOneshot; 5 | use crate::{Bot, PluginBuilder, RT}; 6 | use parking_lot::RwLock; 7 | use std::path::PathBuf; 8 | use std::sync::Arc; 9 | use tokio::sync::mpsc; 10 | 11 | #[cfg(feature = "plugin-access-control")] 12 | use ahash::HashSet; 13 | #[cfg(feature = "plugin-access-control")] 14 | use serde::{Deserialize, Serialize}; 15 | 16 | #[deprecated(since = "0.11.0", note = "弃用,直接删掉就好了")] 17 | pub trait KoviApi {} 18 | 19 | #[derive(Debug, Clone)] 20 | pub enum SetAdmin { 21 | /// 增加一个管理员 22 | Add(i64), 23 | /// 增加多个管理员 24 | Adds(Vec), 25 | /// 移除一个管理员 26 | Remove(i64), 27 | /// 移除多个管理员 28 | Removes(Vec), 29 | /// 替换管理员成此管理员 30 | Changes(Vec), 31 | } 32 | 33 | #[cfg(feature = "plugin-access-control")] 34 | #[derive(Debug, Clone)] 35 | pub enum SetAccessControlList { 36 | /// 增加一个名单 37 | Add(i64), 38 | /// 增加多个名单 39 | Adds(Vec), 40 | /// 移除一个名单 41 | Remove(i64), 42 | /// 移除多个名单 43 | Removes(Vec), 44 | /// 替换名单成此名单 45 | Changes(Vec), 46 | } 47 | 48 | #[cfg(feature = "plugin-access-control")] 49 | #[derive(Clone, Debug, Default, Deserialize, Serialize)] 50 | pub struct AccessList { 51 | pub friends: HashSet, 52 | pub groups: HashSet, 53 | } 54 | 55 | #[cfg(feature = "plugin-access-control")] 56 | #[derive(Debug, Clone, Copy, Deserialize, Serialize)] 57 | pub enum AccessControlMode { 58 | BlackList, 59 | WhiteList, 60 | } 61 | 62 | /// 黑白名单 63 | #[cfg(feature = "plugin-access-control")] 64 | impl RuntimeBot { 65 | /// 为某一插件启动名单 66 | /// 67 | /// # error 68 | /// 69 | /// 如果寻找不到插件,会返回Err `BotError::PluginNotFound` 70 | /// 71 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回Err `BotError::RefExpired` 。 72 | /// 这通常出现在 `Bot` 已经关闭,可有个不受 Kovi 管理的线程仍然拥有此 `RuntimeBot`。 73 | pub fn set_plugin_access_control>( 74 | &self, 75 | plugin_name: T, 76 | enable: bool, 77 | ) -> Result<(), BotError> { 78 | let bot = match self.bot.upgrade() { 79 | Some(b) => b, 80 | None => return Err(BotError::RefExpired), 81 | }; 82 | 83 | let mut bot = bot.write(); 84 | 85 | let plugin_name = plugin_name.as_ref(); 86 | 87 | let plugin = match bot.plugins.get_mut(plugin_name) { 88 | Some(v) => v, 89 | None => return Err(BotError::PluginNotFound(plugin_name.to_string())), 90 | }; 91 | 92 | plugin.access_control = enable; 93 | 94 | Ok(()) 95 | } 96 | 97 | /// 更改名单为其他模式,插件默认为白名单模式 98 | /// 99 | /// # error 100 | /// 101 | /// 如果寻找不到插件,会返回Err `BotError::PluginNotFound` 102 | /// 103 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回Err `BotError::RefExpired` 。 104 | /// 这通常出现在 `Bot` 已经关闭,可有个不受 Kovi 管理的线程仍然拥有此 `RuntimeBot`。 105 | pub fn set_plugin_access_control_mode>( 106 | &self, 107 | plugin_name: T, 108 | access_control_mode: AccessControlMode, 109 | ) -> Result<(), BotError> { 110 | let bot = match self.bot.upgrade() { 111 | Some(b) => b, 112 | None => return Err(BotError::RefExpired), 113 | }; 114 | 115 | let mut bot = bot.write(); 116 | 117 | let plugin_name = plugin_name.as_ref(); 118 | 119 | let plugin = match bot.plugins.get_mut(plugin_name) { 120 | Some(v) => v, 121 | None => return Err(BotError::PluginNotFound(plugin_name.to_string())), 122 | }; 123 | 124 | plugin.list_mode = access_control_mode; 125 | 126 | Ok(()) 127 | } 128 | 129 | /// 为某一插件添加名单 130 | /// 131 | /// is_group为true时,为群组名单,为false时为好友名单 132 | /// 133 | /// # error 134 | /// 135 | /// 如果寻找不到插件,会返回Err `BotError::PluginNotFound` 136 | /// 137 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回Err `BotError::RefExpired` 。 138 | /// 这通常出现在 `Bot` 已经关闭,可有个不受 Kovi 管理的线程仍然拥有此 `RuntimeBot`。 139 | pub fn set_plugin_access_control_list>( 140 | &self, 141 | plugin_name: T, 142 | is_group: bool, 143 | change: SetAccessControlList, 144 | ) -> Result<(), BotError> { 145 | let bot = match self.bot.upgrade() { 146 | Some(b) => b, 147 | None => return Err(BotError::RefExpired), 148 | }; 149 | 150 | let mut bot = bot.write(); 151 | 152 | let plugin_name = plugin_name.as_ref(); 153 | 154 | let plugin = match bot.plugins.get_mut(plugin_name) { 155 | Some(v) => v, 156 | None => return Err(BotError::PluginNotFound(plugin_name.to_string())), 157 | }; 158 | 159 | match (change, is_group) { 160 | // 添加一个群组到名单 161 | (SetAccessControlList::Add(id), true) => { 162 | plugin.access_list.groups.insert(id); 163 | } 164 | // 添加多个群组到名单 165 | (SetAccessControlList::Adds(ids), true) => { 166 | for id in ids { 167 | plugin.access_list.groups.insert(id); 168 | } 169 | } 170 | // 从名单中移除一个群组 171 | (SetAccessControlList::Remove(id), true) => { 172 | plugin.access_list.groups.remove(&id); 173 | } 174 | // 从名单中移除多个群组 175 | (SetAccessControlList::Removes(ids), true) => { 176 | for id in ids { 177 | plugin.access_list.groups.remove(&id); 178 | } 179 | } 180 | // 替换名单为新的群组列表 181 | (SetAccessControlList::Changes(ids), true) => { 182 | plugin.access_list.groups = ids.into_iter().collect(); 183 | } 184 | // 添加一个用户到名单 185 | (SetAccessControlList::Add(id), false) => { 186 | plugin.access_list.friends.insert(id); 187 | } 188 | // 添加多个用户到名单 189 | (SetAccessControlList::Adds(ids), false) => { 190 | plugin.access_list.friends.extend(ids); 191 | } 192 | // 从名单中移除一个用户 193 | (SetAccessControlList::Remove(id), false) => { 194 | plugin.access_list.friends.remove(&id); 195 | } 196 | // 从名单中移除多个用户 197 | (SetAccessControlList::Removes(ids), false) => { 198 | plugin.access_list.friends.retain(|&x| !ids.contains(&x)); 199 | } 200 | // 替换名单为新的用户列表 201 | (SetAccessControlList::Changes(ids), false) => { 202 | plugin.access_list.friends = ids.into_iter().collect(); 203 | } 204 | } 205 | 206 | Ok(()) 207 | } 208 | } 209 | 210 | /// 管理员控制 211 | impl RuntimeBot { 212 | /// 修改Bot的管理员 213 | /// 214 | /// # Error 215 | /// 216 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回 `BotError::RefExpired` 错误。 217 | /// 这通常出现在Bot已经关闭,可有个不受Kovi管理的线程仍然拥有此 RuntimeBot。 218 | pub fn set_deputy_admins(&self, change: SetAdmin) -> Result<(), BotError> { 219 | let bot = match self.bot.upgrade() { 220 | Some(b) => b, 221 | None => return Err(BotError::RefExpired), 222 | }; 223 | 224 | let bot = bot.read(); 225 | match change { 226 | SetAdmin::Add(id) => { 227 | bot.information.write().deputy_admins.insert(id); 228 | } 229 | SetAdmin::Adds(ids) => { 230 | bot.information.write().deputy_admins.extend(ids); 231 | } 232 | SetAdmin::Remove(id) => { 233 | bot.information.write().deputy_admins.remove(&id); 234 | } 235 | SetAdmin::Removes(ids) => { 236 | bot.information 237 | .write() 238 | .deputy_admins 239 | .retain(|&x| !ids.contains(&x)); 240 | } 241 | SetAdmin::Changes(ids) => { 242 | bot.information.write().deputy_admins = ids.into_iter().collect(); 243 | } 244 | } 245 | 246 | Ok(()) 247 | } 248 | 249 | /// 获取Bot的主管理员 250 | /// 251 | /// # Error 252 | /// 253 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回 `BotError::RefExpired` 错误。 254 | /// 这通常出现在Bot已经关闭,可有个不受Kovi管理的线程仍然拥有此 RuntimeBot。 255 | pub fn get_main_admin(&self) -> Result { 256 | let bot = match self.bot.upgrade() { 257 | Some(b) => b, 258 | None => return Err(BotError::RefExpired), 259 | }; 260 | 261 | let id = bot.read().information.read().main_admin; 262 | Ok(id) 263 | } 264 | 265 | /// 获取Bot的副管理员 266 | /// 267 | /// # Error 268 | /// 269 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回 `BotError::RefExpired` 错误。 270 | /// 这通常出现在Bot已经关闭,可有个不受Kovi管理的线程仍然拥有此 RuntimeBot。 271 | pub fn get_deputy_admins(&self) -> Result, BotError> { 272 | let bot = match self.bot.upgrade() { 273 | Some(b) => b, 274 | None => return Err(BotError::RefExpired), 275 | }; 276 | 277 | let ids = bot.read().information.read().deputy_admins.clone(); 278 | Ok(ids.into_iter().collect()) 279 | } 280 | 281 | /// 获取Bot的所有管理员 282 | /// 283 | /// # Error 284 | /// 285 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回 `BotError::RefExpired` 错误。 286 | /// 这通常出现在Bot已经关闭,可有个不受Kovi管理的线程仍然拥有此 RuntimeBot。 287 | pub fn get_all_admin(&self) -> Result, BotError> { 288 | let bot = match self.bot.upgrade() { 289 | Some(b) => b, 290 | None => return Err(BotError::RefExpired), 291 | }; 292 | 293 | let mut admins = Vec::with_capacity(1); 294 | 295 | let bot = bot.read(); 296 | 297 | admins.push(bot.information.read().main_admin); 298 | 299 | admins.extend(bot.information.read().deputy_admins.clone()); 300 | 301 | Ok(admins) 302 | } 303 | } 304 | 305 | /// 工具 306 | impl RuntimeBot { 307 | /// 获取插件自己的路径 308 | /// 309 | /// # panic 310 | /// 311 | /// 可能会 panic 的情况: 312 | /// - 当前运行目录不存在,这种情况很少见。 313 | /// - 权限不足,无法访问当前目录,这样肯定不能运行插件。 314 | pub fn get_data_path(&self) -> PathBuf { 315 | let mut current_dir = std::env::current_dir().expect("Get current directory failed"); 316 | 317 | current_dir.push(format!("data/{}", self.plugin_name)); 318 | current_dir 319 | } 320 | } 321 | 322 | /// 插件控制 323 | impl RuntimeBot { 324 | /// 获取Bot的插件信息。 325 | /// 326 | /// # Error 327 | /// 328 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回 `BotError::RefExpired` 错误。 329 | /// 这通常出现在Bot已经关闭,可有个不受Kovi管理的线程仍然拥有此 RuntimeBot。 330 | pub fn get_plugin_info(&self) -> Result, BotError> { 331 | let bot = match self.bot.upgrade() { 332 | Some(b) => b, 333 | None => return Err(BotError::RefExpired), 334 | }; 335 | 336 | let bot = bot.read(); 337 | 338 | let plugins_info: Vec = bot 339 | .plugins 340 | .iter() 341 | .map(|(name, plugin)| PluginInfo { 342 | name: name.clone(), 343 | version: plugin.version.clone(), 344 | enabled: *plugin.enabled.borrow(), 345 | enable_on_startup: plugin.enable_on_startup, 346 | #[cfg(feature = "plugin-access-control")] 347 | access_control: plugin.access_control, 348 | #[cfg(feature = "plugin-access-control")] 349 | list_mode: plugin.list_mode, 350 | #[cfg(feature = "plugin-access-control")] 351 | access_list: plugin.access_list.clone(), 352 | }) 353 | .collect(); 354 | 355 | Ok(plugins_info) 356 | } 357 | 358 | /// 重载传入的插件 359 | /// 360 | /// # error 361 | /// 362 | /// 如果寻找不到插件,会返回Err `BotError::PluginNotFound` 363 | /// 364 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回Err `BotError::RefExpired` 。 365 | /// 这通常出现在 `Bot` 已经关闭,可有个不受 Kovi 管理的线程仍然拥有此 `RuntimeBot`。 366 | /// 367 | /// # panic 368 | /// 369 | /// 如果插件的 Drop 闭包发生 panic ,此函数也会 panic 370 | pub async fn restart_plugin>(&self, plugin_name: T) -> Result<(), BotError> { 371 | if self.is_plugin_enable(&plugin_name)? { 372 | let join = self.disable_plugin(&plugin_name)?; 373 | 374 | if let Some(join) = join { 375 | join.await.expect("Internal thread panic") 376 | } 377 | } 378 | 379 | self.enable_plugin(plugin_name) 380 | } 381 | 382 | /// 卸载传入的插件 383 | /// 384 | /// # error 385 | /// 386 | /// 如果寻找不到插件,会返回Err `BotError::PluginNotFound` 387 | /// 388 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回Err `BotError::RefExpired` 。 389 | /// 这通常出现在 `Bot` 已经关闭,可有个不受 Kovi 管理的线程仍然拥有此 `RuntimeBot`。 390 | pub fn disable_plugin>( 391 | &self, 392 | plugin_name: T, 393 | ) -> Result>, BotError> { 394 | if !self.is_plugin_enable(&plugin_name)? { 395 | return Ok(None); 396 | } 397 | 398 | let bot = match self.bot.upgrade() { 399 | Some(b) => b, 400 | None => return Err(BotError::RefExpired), 401 | }; 402 | 403 | Ok(Some(disable_plugin(bot, plugin_name)?)) 404 | } 405 | 406 | /// 启用传入的插件 407 | /// 408 | /// # error 409 | /// 410 | /// 如果寻找不到插件,会返回Err `BotError::PluginNotFound` 411 | /// 412 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回Err `BotError::RefExpired` 。 413 | /// 这通常出现在 `Bot` 已经关闭,可有个不受 Kovi 管理的线程仍然拥有此 `RuntimeBot`。 414 | pub fn enable_plugin>(&self, plugin_name: T) -> Result<(), BotError> { 415 | if self.is_plugin_enable(&plugin_name)? { 416 | return Ok(()); 417 | } 418 | 419 | let bot = match self.bot.upgrade() { 420 | Some(b) => b, 421 | None => return Err(BotError::RefExpired), 422 | }; 423 | 424 | enable_plugin(bot, plugin_name, self.api_tx.clone()) 425 | } 426 | 427 | /// 插件是否开启 428 | /// 429 | /// # error 430 | /// 431 | /// 如果寻找不到插件,会返回Err `BotError::PluginNotFound` 432 | /// 433 | /// 如果此 `RuntimeBot` 实例内部的 `Bot` 中已经不存在,将会返回Err `BotError::RefExpired` 。 434 | /// 这通常出现在 `Bot` 已经关闭,可有个不受 Kovi 管理的线程仍然拥有此 `RuntimeBot`。 435 | pub fn is_plugin_enable>(&self, plugin_name: T) -> Result { 436 | let bot = match self.bot.upgrade() { 437 | Some(b) => b, 438 | None => return Err(BotError::RefExpired), 439 | }; 440 | 441 | let bot = bot.read(); 442 | let plugin_name = plugin_name.as_ref(); 443 | 444 | let bot_plugin = match bot.plugins.get(plugin_name) { 445 | Some(v) => v, 446 | None => return Err(BotError::PluginNotFound(plugin_name.to_string())), 447 | }; 448 | let bool_ = *bot_plugin.enabled.borrow(); 449 | Ok(bool_) 450 | } 451 | } 452 | 453 | pub(crate) fn disable_plugin>( 454 | bot: Arc>, 455 | plugin_name: T, 456 | ) -> Result, BotError> { 457 | let join; 458 | { 459 | let mut bot = bot.write(); 460 | 461 | let plugin_name = plugin_name.as_ref(); 462 | 463 | let bot_plugin = match bot.plugins.get_mut(plugin_name) { 464 | Some(v) => v, 465 | None => return Err(BotError::PluginNotFound(plugin_name.to_string())), 466 | }; 467 | join = bot_plugin.shutdown(); 468 | } 469 | 470 | Ok(join) 471 | } 472 | 473 | fn enable_plugin>( 474 | bot: Arc>, 475 | plugin_name: T, 476 | api_tx: mpsc::Sender, 477 | ) -> Result<(), BotError> { 478 | let bot_read = bot.read(); 479 | let plugin_name = plugin_name.as_ref(); 480 | 481 | let (host, port) = { 482 | let info = bot_read.information.read(); 483 | (info.server.host.clone(), info.server.port) 484 | }; 485 | 486 | let Some(bot_plugin) = bot_read.plugins.get(plugin_name) else { 487 | return Err(BotError::PluginNotFound(plugin_name.to_string())); 488 | }; 489 | 490 | bot_plugin.enabled.send_modify(|v| { 491 | *v = true; 492 | }); 493 | 494 | let plugin_ = bot_plugin.clone(); 495 | 496 | let plugin_builder = 497 | PluginBuilder::new(plugin_name.to_string(), bot.clone(), host, port, api_tx); 498 | 499 | RT.spawn(async move { plugin_.run(plugin_builder) }); 500 | 501 | Ok(()) 502 | } 503 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /src/bot/event/msg_event.rs: -------------------------------------------------------------------------------- 1 | use super::{Anonymous, Sender}; 2 | use crate::Message; 3 | use crate::bot::event::InternalEvent; 4 | use crate::bot::message::cq_to_arr_inner; 5 | use crate::bot::plugin_builder::event::{Event, PostType, Sex}; 6 | use crate::bot::runtimebot::{CanSendApi, send_api_request_with_forget}; 7 | use crate::bot::{BotInformation, SendApi}; 8 | use crate::error::EventBuildError; 9 | use crate::types::ApiAndOneshot; 10 | use log::{debug, info}; 11 | use serde::Serialize; 12 | use serde_json::value::Index; 13 | use serde_json::{self, Value, json}; 14 | use tokio::sync::mpsc; 15 | 16 | #[cfg(feature = "cqstring")] 17 | use crate::bot::message::CQMessage; 18 | 19 | #[deprecated(since = "0.11.0", note = "请使用 `MsgEvent` 代替")] 20 | pub type AllMsgEvent = MsgEvent; 21 | 22 | #[derive(Debug, Clone)] 23 | pub struct MsgEvent { 24 | /// 事件发生的时间戳 25 | pub time: i64, 26 | /// 收到事件的机器人 登陆号 27 | pub self_id: i64, 28 | /// 上报类型 29 | pub post_type: PostType, 30 | /// 消息类型 31 | pub message_type: String, 32 | /// 消息子类型,如果是好友则是 friend,如果是群临时会话则是 group 33 | pub sub_type: String, 34 | /// 消息内容 35 | pub message: Message, 36 | /// 消息 ID 37 | pub message_id: i32, 38 | /// 群号 39 | pub group_id: Option, 40 | /// 发送者号 41 | pub user_id: i64, 42 | /// 匿名信息,如果不是匿名消息则为 null 43 | pub anonymous: Option, 44 | /// 原始消息内容 45 | pub raw_message: String, 46 | /// 字体 47 | pub font: i32, 48 | /// 发送人信息 49 | pub sender: Sender, 50 | 51 | /// 处理过的纯文本,如果是纯图片或无文本,此处为None 52 | pub text: Option, 53 | /// 处理过的文本,会解析成人类易读形式,里面会包含\[image\]\[face\]等解析后字符串 54 | pub human_text: String, 55 | /// 原始的onebot消息,已处理成json格式 56 | pub original_json: Value, 57 | 58 | /// 不推荐的消息发送方式 59 | pub api_tx: mpsc::Sender, 60 | } 61 | 62 | impl Event for MsgEvent { 63 | fn de( 64 | event: &InternalEvent, 65 | _: &BotInformation, 66 | api_tx: &mpsc::Sender, 67 | ) -> Option { 68 | let InternalEvent::OneBotEvent(json_str) = event else { 69 | return None; 70 | }; 71 | let json = serde_json::from_str(json_str).ok()?; 72 | Self::new(api_tx.clone(), json).ok() 73 | } 74 | } 75 | 76 | impl MsgEvent { 77 | pub(crate) fn new( 78 | api_tx: mpsc::Sender, 79 | temp: Value, 80 | ) -> Result { 81 | let temp_object = temp.as_object().ok_or(EventBuildError::ParseError( 82 | "Invalid JSON object".to_string(), 83 | ))?; 84 | 85 | let temp_sender = temp_object 86 | .get("sender") 87 | .and_then(|v| v.as_object()) 88 | .ok_or(EventBuildError::ParseError( 89 | "Invalid sender object".to_string(), 90 | ))?; 91 | 92 | let sender = { 93 | Sender { 94 | user_id: temp_sender 95 | .get("user_id") 96 | .and_then(|v| v.as_i64()) 97 | .ok_or(EventBuildError::ParseError("Invalid user_id".to_string()))?, 98 | nickname: temp_sender.get("nickname").and_then(|v| { 99 | if let Value::String(str) = v.clone() { 100 | Some(str) 101 | } else { 102 | None 103 | } 104 | }), 105 | card: temp_sender.get("card").and_then(|v| { 106 | if let Value::String(str) = v.clone() { 107 | Some(str) 108 | } else { 109 | None 110 | } 111 | }), 112 | sex: if let Some(v) = temp_sender.get("sex").and_then(|v| v.as_str()) { 113 | match v { 114 | "male" => Some(Sex::Male), 115 | "female" => Some(Sex::Female), 116 | _ => None, 117 | } 118 | } else { 119 | None 120 | }, 121 | age: temp_sender 122 | .get("age") 123 | .and_then(|v| v.as_i64()) 124 | .map(|v| v as i32), 125 | area: temp_sender.get("area").and_then(|v| { 126 | if let Value::String(str) = v.clone() { 127 | Some(str) 128 | } else { 129 | None 130 | } 131 | }), 132 | level: temp_sender.get("level").and_then(|v| { 133 | if let Value::String(str) = v.clone() { 134 | Some(str) 135 | } else { 136 | None 137 | } 138 | }), 139 | role: temp_sender.get("role").and_then(|v| { 140 | if let Value::String(str) = v.clone() { 141 | Some(str) 142 | } else { 143 | None 144 | } 145 | }), 146 | title: temp_sender.get("title").and_then(|v| { 147 | if let Value::String(str) = v.clone() { 148 | Some(str) 149 | } else { 150 | None 151 | } 152 | }), 153 | } 154 | }; 155 | 156 | let group_id = temp_object.get("group_id").and_then(|v| v.as_i64()); 157 | 158 | let message = if temp_object 159 | .get("message") 160 | .and_then(|v| v.as_array()) 161 | .is_some() 162 | { 163 | let v = temp_object 164 | .get("message") 165 | .ok_or(EventBuildError::ParseError( 166 | "Missing 'message' field".to_string(), 167 | ))? 168 | .as_array() 169 | .ok_or(EventBuildError::ParseError( 170 | "Invalid 'message' array".to_string(), 171 | ))? 172 | .to_vec(); 173 | Message::from_vec_segment_value(v) 174 | .map_err(|e| EventBuildError::ParseError(format!("Parse error: {e}")))? 175 | } else { 176 | let str_v = temp_object["message"] 177 | .as_str() 178 | .ok_or(format!( 179 | "message is not string:{:?}", 180 | temp_object["message"] 181 | )) 182 | .map_err(|e| EventBuildError::ParseError(format!("Parse error: {e}")))?; 183 | let arr_v = cq_to_arr_inner(str_v); 184 | Message::from_vec_segment_value(arr_v) 185 | .map_err(|e| EventBuildError::ParseError(format!("Parse error: {e}")))? 186 | }; 187 | 188 | let anonymous: Option = 189 | if temp_object.get("anonymous").is_none_or(|v| v.is_null()) { 190 | None 191 | } else { 192 | let anonymous = temp_object 193 | .get("anonymous") 194 | .ok_or(EventBuildError::ParseError( 195 | "Invalid anonymous field".to_string(), 196 | ))? 197 | .clone(); 198 | Some( 199 | serde_json::from_value(anonymous) 200 | .map_err(|e| EventBuildError::ParseError(e.to_string()))?, 201 | ) 202 | }; 203 | 204 | let text = { 205 | let mut text_vec = Vec::new(); 206 | for msg in message.iter() { 207 | if msg.type_ == "text" 208 | && let Some(text_value) = msg.data.get("text").and_then(|v| v.as_str()) 209 | { 210 | text_vec.push(text_value); 211 | }; 212 | } 213 | if !text_vec.is_empty() { 214 | Some(text_vec.join("\n").trim().to_string()) 215 | } else { 216 | None 217 | } 218 | }; 219 | 220 | let event = MsgEvent { 221 | human_text: message.to_human_string(), 222 | time: temp_object 223 | .get("time") 224 | .and_then(|v| v.as_i64()) 225 | .ok_or(EventBuildError::ParseError("Invalid time".to_string()))?, 226 | self_id: temp_object 227 | .get("self_id") 228 | .and_then(|v| v.as_i64()) 229 | .ok_or(EventBuildError::ParseError("Invalid self_id".to_string()))?, 230 | post_type: temp_object 231 | .get("post_type") 232 | .and_then(|v| serde_json::from_value::(v.clone()).ok()) 233 | .ok_or(EventBuildError::ParseError("Invalid post_type".to_string()))?, 234 | message_type: temp_object 235 | .get("message_type") 236 | .and_then(|v| { 237 | if let Value::String(str) = v.clone() { 238 | Some(str) 239 | } else { 240 | None 241 | } 242 | }) 243 | .ok_or(EventBuildError::ParseError( 244 | "Invalid message_type".to_string(), 245 | ))?, 246 | sub_type: temp_object 247 | .get("sub_type") 248 | .and_then(|v| { 249 | if let Value::String(str) = v.clone() { 250 | Some(str) 251 | } else { 252 | None 253 | } 254 | }) 255 | .ok_or(EventBuildError::ParseError("Invalid sub_type".to_string()))?, 256 | message, 257 | message_id: temp_object 258 | .get("message_id") 259 | .and_then(|v| v.as_i64()) 260 | .ok_or(EventBuildError::ParseError( 261 | "Invalid message_id".to_string(), 262 | ))? as i32, 263 | group_id, 264 | user_id: temp_object 265 | .get("user_id") 266 | .and_then(|v| v.as_i64()) 267 | .ok_or(EventBuildError::ParseError("Invalid user_id".to_string()))?, 268 | anonymous, 269 | raw_message: temp_object 270 | .get("raw_message") 271 | .and_then(|v| { 272 | if let Value::String(str) = v.clone() { 273 | Some(str) 274 | } else { 275 | None 276 | } 277 | }) 278 | .ok_or(EventBuildError::ParseError( 279 | "Invalid raw_message".to_string(), 280 | ))?, 281 | font: temp_object 282 | .get("font") 283 | .and_then(|v| v.as_i64()) 284 | .ok_or(EventBuildError::ParseError("Invalid font".to_string()))? 285 | as i32, 286 | sender, 287 | api_tx, 288 | text, 289 | original_json: temp, 290 | }; 291 | debug!("{event:?}"); 292 | Ok(event) 293 | } 294 | } 295 | 296 | impl MsgEvent { 297 | /// 直接从原始的 Json Value 获取某值 298 | /// 299 | /// # example 300 | /// 301 | /// ```ignore 302 | /// use kovi::PluginBuilder; 303 | /// 304 | /// PluginBuilder::on_msg(|event| async move { 305 | /// let time = event.get("time").and_then(|v| v.as_i64()).unwrap(); 306 | /// 307 | /// assert_eq!(time, event.time); 308 | /// }); 309 | /// ``` 310 | pub fn get(&self, index: I) -> Option<&Value> { 311 | self.original_json.get(index) 312 | } 313 | } 314 | 315 | impl std::ops::Index for MsgEvent 316 | where 317 | I: Index, 318 | { 319 | type Output = Value; 320 | 321 | fn index(&self, index: I) -> &Self::Output { 322 | &self.original_json[index] 323 | } 324 | } 325 | 326 | impl MsgEvent { 327 | fn reply_builder(&self, msg: T, auto_escape: bool) -> SendApi 328 | where 329 | T: Serialize, 330 | { 331 | if self.is_private() { 332 | SendApi::new( 333 | "send_msg", 334 | json!({ 335 | "message_type":"private", 336 | "user_id":self.user_id, 337 | "message":msg, 338 | "auto_escape":auto_escape, 339 | }), 340 | ) 341 | } else { 342 | SendApi::new( 343 | "send_msg", 344 | json!({ 345 | "message_type":"group", 346 | "group_id":self.group_id.expect("unreachable"), 347 | "message":msg, 348 | "auto_escape":auto_escape, 349 | }), 350 | ) 351 | } 352 | } 353 | 354 | #[cfg(not(feature = "cqstring"))] 355 | /// 快速回复消息 356 | pub fn reply(&self, msg: T) 357 | where 358 | Message: From, 359 | T: Serialize, 360 | { 361 | let msg = Message::from(msg); 362 | let send_msg = self.reply_builder(&msg, false); 363 | let mut nickname = self.get_sender_nickname(); 364 | nickname.insert(0, ' '); 365 | let id = &self.sender.user_id; 366 | let message_type = &self.message_type; 367 | let group_id = match &self.group_id { 368 | Some(v) => format!(" {v}"), 369 | None => "".to_string(), 370 | }; 371 | let human_msg = msg.to_human_string(); 372 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 373 | 374 | send_api_request_with_forget(&self.api_tx, send_msg) 375 | } 376 | 377 | #[cfg(feature = "cqstring")] 378 | /// 快速回复消息 379 | pub fn reply(&self, msg: T) 380 | where 381 | CQMessage: From, 382 | T: Serialize, 383 | { 384 | let msg = CQMessage::from(msg); 385 | let send_msg = self.reply_builder(&msg, false); 386 | let mut nickname = self.get_sender_nickname(); 387 | nickname.insert(0, ' '); 388 | let id = &self.sender.user_id; 389 | let message_type = &self.message_type; 390 | let group_id = match &self.group_id { 391 | Some(v) => format!(" {v}"), 392 | None => "".to_string(), 393 | }; 394 | let human_msg = Message::from(msg).to_human_string(); 395 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 396 | send_api_request_with_forget(&self.api_tx, send_msg); 397 | } 398 | 399 | #[cfg(not(feature = "cqstring"))] 400 | /// 快速回复消息并且**引用** 401 | pub fn reply_and_quote(&self, msg: T) 402 | where 403 | Message: From, 404 | T: Serialize, 405 | { 406 | let msg = Message::from(msg).add_reply(self.message_id); 407 | let send_msg = self.reply_builder(&msg, false); 408 | 409 | let mut nickname = self.get_sender_nickname(); 410 | nickname.insert(0, ' '); 411 | let id = &self.sender.user_id; 412 | let message_type = &self.message_type; 413 | let group_id = match &self.group_id { 414 | Some(v) => format!(" {v}"), 415 | None => "".to_string(), 416 | }; 417 | let human_msg = msg.to_human_string(); 418 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 419 | 420 | send_api_request_with_forget(&self.api_tx, send_msg); 421 | } 422 | 423 | #[cfg(feature = "cqstring")] 424 | /// 快速回复消息并且**引用** 425 | pub fn reply_and_quote(&self, msg: T) 426 | where 427 | CQMessage: From, 428 | T: Serialize, 429 | { 430 | let msg = CQMessage::from(msg).add_reply(self.message_id); 431 | let send_msg = self.reply_builder(&msg, false); 432 | 433 | let mut nickname = self.get_sender_nickname(); 434 | nickname.insert(0, ' '); 435 | let id = &self.sender.user_id; 436 | let message_type = &self.message_type; 437 | let group_id = match &self.group_id { 438 | Some(v) => format!(" {v}"), 439 | None => "".to_string(), 440 | }; 441 | let human_msg = Message::from(msg).to_human_string(); 442 | info!("[reply] [to {message_type}{group_id}{nickname} {id}]: {human_msg}"); 443 | send_api_request_with_forget(&self.api_tx, send_msg); 444 | } 445 | 446 | #[cfg(feature = "cqstring")] 447 | /// 快速回复消息,并且**kovi不进行解析,直接发送此字符串** 448 | pub fn reply_text(&self, msg: T) 449 | where 450 | String: From, 451 | T: Serialize, 452 | { 453 | let send_msg = self.reply_builder(&msg, true); 454 | let mut nickname = self.get_sender_nickname(); 455 | nickname.insert(0, ' '); 456 | let id = &self.sender.user_id; 457 | let message_type = &self.message_type; 458 | let group_id = match &self.group_id { 459 | Some(v) => format!(" {v}"), 460 | None => "".to_string(), 461 | }; 462 | let msg = String::from(msg); 463 | info!("[reply] [to {message_type}{group_id} {nickname} {id}]: {msg}"); 464 | send_api_request_with_forget(&self.api_tx, send_msg); 465 | } 466 | 467 | /// 便捷获取文本,如果没有文本则会返回空字符串,如果只需要借用,请使用 `borrow_text()` 468 | pub fn get_text(&self) -> String { 469 | match self.text.clone() { 470 | Some(v) => v, 471 | None => "".to_string(), 472 | } 473 | } 474 | 475 | /// 便捷获取发送者昵称,如果无名字,此处为空字符串 476 | pub fn get_sender_nickname(&self) -> String { 477 | if let Some(v) = &self.sender.nickname { 478 | v.clone() 479 | } else { 480 | "".to_string() 481 | } 482 | } 483 | 484 | /// 借用 event 的 text,只是做了一下self.text.as_deref()的包装 485 | pub fn borrow_text(&self) -> Option<&str> { 486 | self.text.as_deref() 487 | } 488 | 489 | pub fn is_group(&self) -> bool { 490 | self.group_id.is_some() 491 | } 492 | 493 | pub fn is_private(&self) -> bool { 494 | self.group_id.is_none() 495 | } 496 | } 497 | 498 | impl CanSendApi for MsgEvent { 499 | fn __get_api_tx(&self) -> &tokio::sync::mpsc::Sender { 500 | &self.api_tx 501 | } 502 | } 503 | -------------------------------------------------------------------------------- /src/bot/message.rs: -------------------------------------------------------------------------------- 1 | use std::ops::Add; 2 | 3 | use ahash::HashMap; 4 | use serde::{Deserialize, Serialize}; 5 | use serde_json::{Value, json}; 6 | 7 | use crate::error::MessageError; 8 | 9 | pub mod add; 10 | 11 | #[derive(Debug, Clone, Serialize, Deserialize)] 12 | pub struct Segment { 13 | #[serde(rename = "type")] 14 | pub type_: String, 15 | pub data: Value, 16 | } 17 | 18 | impl Segment { 19 | pub fn new(type_: &str, data: Value) -> Self { 20 | Segment { 21 | type_: type_.to_string(), 22 | data, 23 | } 24 | } 25 | } 26 | 27 | impl PartialEq for Segment { 28 | fn eq(&self, other: &Self) -> bool { 29 | self.type_ == other.type_ && self.data == other.data 30 | } 31 | } 32 | 33 | /// 消息 34 | /// 35 | /// **不保证 data 里的 Value 格式是否正确,需要自行检查** 36 | /// 37 | /// # Examples 38 | /// ``` 39 | /// use kovi::bot::message::Message; 40 | /// use serde_json::json; 41 | /// 42 | /// let msg: Message = Message::from("Hi"); 43 | /// let msg: Message = Message::from_value(json!( 44 | /// [ 45 | /// { 46 | /// "type":"text", 47 | /// "data":{ 48 | /// "text":"Some msg" 49 | /// } 50 | /// } 51 | /// ] 52 | /// )).unwrap(); 53 | /// ``` 54 | #[derive(Debug, Clone, Serialize, Deserialize, Default)] 55 | pub struct Message(Vec); 56 | 57 | impl From> for Message { 58 | fn from(v: Vec) -> Self { 59 | Message(v) 60 | } 61 | } 62 | 63 | impl From for Vec { 64 | fn from(v: Message) -> Self { 65 | v.0 66 | } 67 | } 68 | 69 | impl From<&str> for Message { 70 | fn from(v: &str) -> Self { 71 | Message(vec![Segment { 72 | type_: "text".to_string(), 73 | data: json!({ 74 | "text":v, 75 | }), 76 | }]) 77 | } 78 | } 79 | 80 | impl From for Message { 81 | fn from(v: String) -> Self { 82 | Message(vec![Segment { 83 | type_: "text".to_string(), 84 | data: json!({ 85 | "text":v, 86 | }), 87 | }]) 88 | } 89 | } 90 | 91 | impl From<&String> for Message { 92 | fn from(v: &String) -> Self { 93 | Message(vec![Segment { 94 | type_: "text".to_string(), 95 | data: json!({ 96 | "text":v, 97 | }), 98 | }]) 99 | } 100 | } 101 | 102 | #[cfg(feature = "cqstring")] 103 | impl From for Message { 104 | fn from(v: CQMessage) -> Self { 105 | cq_to_arr(v) 106 | } 107 | } 108 | 109 | impl PartialEq for Message { 110 | fn eq(&self, other: &Self) -> bool { 111 | self.0 == other.0 112 | } 113 | } 114 | 115 | impl Add for Message { 116 | type Output = Message; 117 | 118 | fn add(mut self, rhs: Self) -> Self::Output { 119 | for seg in rhs.into_iter() { 120 | self.push(seg); 121 | } 122 | self 123 | } 124 | } 125 | 126 | impl Message { 127 | pub fn iter(&self) -> std::slice::Iter<'_, Segment> { 128 | self.0.iter() 129 | } 130 | 131 | pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Segment> { 132 | self.0.iter_mut() 133 | } 134 | } 135 | 136 | impl IntoIterator for Message { 137 | type Item = Segment; 138 | type IntoIter = std::vec::IntoIter; 139 | 140 | fn into_iter(self) -> Self::IntoIter { 141 | self.0.into_iter() 142 | } 143 | } 144 | 145 | impl std::ops::Index for Message { 146 | type Output = Segment; 147 | 148 | fn index(&self, index: usize) -> &Self::Output { 149 | &self.0[index] 150 | } 151 | } 152 | 153 | impl std::ops::IndexMut for Message { 154 | fn index_mut(&mut self, index: usize) -> &mut Self::Output { 155 | &mut self.0[index] 156 | } 157 | } 158 | 159 | impl Message { 160 | pub fn from_value(v: Value) -> Result { 161 | if let Some(v) = v.as_array() { 162 | match Message::from_vec_segment_value(v.clone()) { 163 | Ok(msg) => return Ok(msg), 164 | Err(err) => return Err(MessageError::ParseError(err.to_string())), 165 | }; 166 | } 167 | if let Some(v) = v.as_str() { 168 | return Ok(Message::from(v)); 169 | } 170 | 171 | Err(MessageError::ParseError( 172 | "Message::from_value only accept array".to_string(), 173 | )) 174 | } 175 | 176 | pub fn from_vec_segment_value(v: Vec) -> Result { 177 | let segments: Result, serde_json::Error> = v 178 | .into_iter() 179 | .map(|value| { 180 | let segment: Segment = serde_json::from_value(value)?; 181 | Ok(segment) 182 | }) 183 | .collect(); 184 | 185 | match segments { 186 | Ok(segments) => Ok(Message(segments)), 187 | Err(err) => Err(err), 188 | } 189 | } 190 | 191 | /// Message 解析成人类可读字符串, 会将里面的 segment 转换成 `[type]` 字符串,如: image segment 会转换成 `[image]` 字符串。不要靠此函数做判断,可能不同版本会改变内容。 192 | pub fn to_human_string(&self) -> String { 193 | let mut result = String::new(); 194 | 195 | for item in self.iter() { 196 | match item.type_.as_str() { 197 | "text" => { 198 | if let Some(text_data) = item.data.get("text") 199 | && let Some(text_str) = text_data.as_str() { 200 | result.push_str(text_str); 201 | } 202 | } 203 | _ => { 204 | result.push_str(&format!("[{}]", item.type_)); 205 | } 206 | } 207 | } 208 | result 209 | } 210 | 211 | pub fn get_from_index(&self, index: usize) -> Option<&Segment> { 212 | self.0.get(index) 213 | } 214 | 215 | pub fn get_mut_from_index(&mut self, index: usize) -> Option<&mut Segment> { 216 | self.0.get_mut(index) 217 | } 218 | } 219 | 220 | impl Message { 221 | /// 返回空的 Message 222 | pub fn new() -> Message { 223 | Default::default() 224 | } 225 | 226 | /// 检查 Message 是否包含任意一项 segment 。返回 bool。 227 | /// 228 | /// # Examples 229 | /// ``` 230 | /// use kovi::bot::message::Message; 231 | /// use serde_json::json; 232 | /// 233 | /// let msg1: Message = Message::from("Hi"); 234 | /// let msg2: Message = Message::from_value(json!( 235 | /// [ 236 | /// { 237 | /// "type":"text", 238 | /// "data":{ 239 | /// "text":"Some msg" 240 | /// } 241 | /// } 242 | /// ] 243 | /// )).unwrap(); 244 | /// 245 | /// assert!(msg1.contains("text")); 246 | /// assert!(msg2.contains("text")); 247 | pub fn contains(&self, s: &str) -> bool { 248 | self.iter().any(|item| item.type_ == s) 249 | } 250 | 251 | /// 获取 Message 任意一种 segment 。返回 `Vec`,有多少项,就会返回多少项。 252 | /// 253 | /// # Examples 254 | /// ``` 255 | /// use kovi::bot::message::Segment; 256 | /// use kovi::bot::message::Message; 257 | /// use serde_json::{json, Value}; 258 | /// 259 | /// let msg: Message = Message::from_value(json!( 260 | /// [ 261 | /// { 262 | /// "type":"text", 263 | /// "data":{ 264 | /// "text":"Some msg" 265 | /// } 266 | /// }, 267 | /// { 268 | /// "type":"face", 269 | /// "data":{ 270 | /// "id":"0" 271 | /// } 272 | /// }, 273 | /// ] 274 | /// )).unwrap(); 275 | /// 276 | /// let text_value: Segment = Segment::new("text", json!({"text": "Some msg"})); 277 | /// let face_value: Segment = Segment::new("face", json!({"id": "0"})); 278 | /// assert_eq!(msg.get("text")[0], text_value); 279 | /// assert_eq!(msg.get("face")[0], face_value); 280 | pub fn get(&self, s: &str) -> Vec { 281 | self.iter() 282 | .filter(|item| item.type_ == s) 283 | .cloned() 284 | .collect() 285 | } 286 | } 287 | 288 | #[cfg(feature = "cqstring")] 289 | #[derive(Debug, Clone, Serialize)] 290 | pub struct CQMessage(String); 291 | 292 | #[cfg(feature = "cqstring")] 293 | impl From for CQMessage { 294 | fn from(str: String) -> Self { 295 | CQMessage(str) 296 | } 297 | } 298 | 299 | #[cfg(feature = "cqstring")] 300 | impl From<&String> for CQMessage { 301 | fn from(str: &String) -> Self { 302 | CQMessage(str.clone()) 303 | } 304 | } 305 | 306 | #[cfg(feature = "cqstring")] 307 | impl From<&str> for CQMessage { 308 | fn from(str: &str) -> Self { 309 | CQMessage(str.to_string()) 310 | } 311 | } 312 | 313 | #[cfg(feature = "cqstring")] 314 | impl From for String { 315 | fn from(cq: CQMessage) -> Self { 316 | cq.0 317 | } 318 | } 319 | 320 | #[cfg(feature = "cqstring")] 321 | impl From for CQMessage { 322 | fn from(v: Message) -> Self { 323 | arr_to_cq(v) 324 | } 325 | } 326 | 327 | pub(crate) fn cq_to_arr_inner(message: &str) -> Vec { 328 | let cqstr = message.chars().collect::>(); 329 | let mut text = "".to_owned(); 330 | let mut type_ = "".to_owned(); 331 | let mut val = "".to_owned(); 332 | let mut key = "".to_owned(); 333 | let mut jsonarr: Vec = vec![]; 334 | let mut cqcode: HashMap = ahash::HashMap::default(); 335 | let mut stat = 0; //0:text 1:cqcode_type 2:cqcode_key 3:cqcode_val 336 | let mut i = 0usize; 337 | while i < cqstr.len() { 338 | let cur_ch = cqstr[i]; 339 | if stat == 0 { 340 | if cur_ch == '[' { 341 | if i + 4 <= cqstr.len() { 342 | let t = &cqstr[i..i + 4]; 343 | if t.starts_with(&['[', 'C', 'Q', ':']) { 344 | if !text.is_empty() { 345 | let mut node: HashMap = 346 | ahash::HashMap::default(); 347 | node.insert("type".to_string(), serde_json::json!("text")); 348 | node.insert("data".to_string(), serde_json::json!({"text": text})); 349 | jsonarr.push(serde_json::json!(node)); 350 | text.clear(); 351 | } 352 | stat = 1; 353 | i += 3; 354 | } else { 355 | text.push(cqstr[i]); 356 | } 357 | } else { 358 | text.push(cqstr[i]); 359 | } 360 | } else if cur_ch == '&' { 361 | if i + 5 <= cqstr.len() { 362 | let t = &cqstr[i..i + 5]; 363 | if t.starts_with(&['&', '#', '9', '1', ';']) { 364 | text.push('['); 365 | i += 4; 366 | } else if t.starts_with(&['&', '#', '9', '3', ';']) { 367 | text.push(']'); 368 | i += 4; 369 | } else if t.starts_with(&['&', 'a', 'm', 'p', ';']) { 370 | text.push('&'); 371 | i += 4; 372 | } else { 373 | text.push(cqstr[i]); 374 | } 375 | } else { 376 | text.push(cqstr[i]); 377 | } 378 | } else { 379 | text.push(cqstr[i]); 380 | } 381 | } else if stat == 1 { 382 | if cur_ch == ',' { 383 | stat = 2; 384 | } else if cur_ch == '&' { 385 | if i + 5 <= cqstr.len() { 386 | let t = &cqstr[i..i + 5]; 387 | if t.starts_with(&['&', '#', '9', '1', ';']) { 388 | type_.push('['); 389 | i += 4; 390 | } else if t.starts_with(&['&', '#', '9', '3', ';']) { 391 | type_.push(']'); 392 | i += 4; 393 | } else if t.starts_with(&['&', 'a', 'm', 'p', ';']) { 394 | type_.push('&'); 395 | i += 4; 396 | } else if t.starts_with(&['&', '#', '4', '4', ';']) { 397 | type_.push(','); 398 | i += 4; 399 | } else { 400 | type_.push(cqstr[i]); 401 | } 402 | } else { 403 | type_.push(cqstr[i]); 404 | } 405 | } else { 406 | type_.push(cqstr[i]); 407 | } 408 | } else if stat == 2 { 409 | if cur_ch == '=' { 410 | stat = 3; 411 | } else if cur_ch == '&' { 412 | if i + 5 <= cqstr.len() { 413 | let t = &cqstr[i..i + 5]; 414 | if t.starts_with(&['&', '#', '9', '1', ';']) { 415 | key.push('['); 416 | i += 4; 417 | } else if t.starts_with(&['&', '#', '9', '3', ';']) { 418 | key.push(']'); 419 | i += 4; 420 | } else if t.starts_with(&['&', 'a', 'm', 'p', ';']) { 421 | key.push('&'); 422 | i += 4; 423 | } else if t.starts_with(&['&', '#', '4', '4', ';']) { 424 | key.push(','); 425 | i += 4; 426 | } else { 427 | key.push(cqstr[i]); 428 | } 429 | } else { 430 | key.push(cqstr[i]); 431 | } 432 | } else { 433 | key.push(cqstr[i]); 434 | } 435 | } else if stat == 3 { 436 | if cur_ch == ']' { 437 | let mut node: HashMap = ahash::HashMap::default(); 438 | cqcode.insert(key.clone(), serde_json::json!(val)); 439 | node.insert("type".to_string(), serde_json::json!(type_)); 440 | node.insert("data".to_string(), serde_json::json!(cqcode)); 441 | jsonarr.push(serde_json::json!(node)); 442 | key.clear(); 443 | val.clear(); 444 | text.clear(); 445 | type_.clear(); 446 | cqcode.clear(); 447 | stat = 0; 448 | } else if cur_ch == ',' { 449 | cqcode.insert(key.clone(), serde_json::json!(val)); 450 | key.clear(); 451 | val.clear(); 452 | stat = 2; 453 | } else if cur_ch == '&' { 454 | if i + 5 <= cqstr.len() { 455 | let t = &cqstr[i..i + 5]; 456 | if t.starts_with(&['&', '#', '9', '1', ';']) { 457 | val.push('['); 458 | i += 4; 459 | } else if t.starts_with(&['&', '#', '9', '3', ';']) { 460 | val.push(']'); 461 | i += 4; 462 | } else if t.starts_with(&['&', 'a', 'm', 'p', ';']) { 463 | val.push('&'); 464 | i += 4; 465 | } else if t.starts_with(&['&', '#', '4', '4', ';']) { 466 | val.push(','); 467 | i += 4; 468 | } else { 469 | val.push(cqstr[i]); 470 | } 471 | } else { 472 | val.push(cqstr[i]); 473 | } 474 | } else { 475 | val.push(cqstr[i]); 476 | } 477 | } 478 | i += 1; 479 | } 480 | if !text.is_empty() { 481 | let mut node: HashMap = ahash::HashMap::default(); 482 | node.insert("type".to_string(), serde_json::json!("text")); 483 | node.insert("data".to_string(), serde_json::json!({"text": text})); 484 | jsonarr.push(serde_json::json!(node)); 485 | } 486 | jsonarr 487 | } 488 | 489 | #[cfg(feature = "cqstring")] 490 | pub fn cq_to_arr(message: CQMessage) -> Message { 491 | let json_arr = cq_to_arr_inner(&message.0); 492 | Message::from_vec_segment_value(json_arr).expect("I don't want to maintain cqstring, So this has something panic, The reason for this error is that there is an issue with the cqstring you passed in") 493 | } 494 | 495 | #[cfg(feature = "cqstring")] 496 | fn parse_cq_code(item: &Segment) -> String { 497 | let mut result = String::new(); 498 | 499 | match item.type_.as_str() { 500 | "text" => { 501 | if let Some(text_data) = item.data.get("text") 502 | && let Some(text_str) = text_data.as_str() { 503 | result.push_str(text_str); 504 | } 505 | } 506 | _ => { 507 | let mut params = Vec::new(); 508 | for (key, value) in item 509 | .data 510 | .as_object() 511 | .expect("I don't want to maintain cqstring, So this has something panic, The reason for this error is that the data part of the segment you passed in is not an Object structure") 512 | .iter() 513 | { 514 | if let Some(value_str) = value.as_str() { 515 | params.push(format!("{key}={value_str}")); 516 | } 517 | } 518 | if !params.is_empty() { 519 | let params_str = params.join(","); 520 | result.push_str(&format!("[CQ:{},{params_str}]", item.type_)); 521 | } else { 522 | result.push_str(&format!("[CQ:{}]", item.type_)); 523 | } 524 | } 525 | } 526 | result 527 | } 528 | 529 | #[cfg(feature = "cqstring")] 530 | pub fn arr_to_cq(message: Message) -> CQMessage { 531 | let mut result = String::new(); 532 | 533 | for item in message.iter() { 534 | result.push_str(&parse_cq_code(item)); 535 | } 536 | 537 | result.into() 538 | } 539 | 540 | #[cfg(feature = "cqstring")] 541 | #[test] 542 | fn __cq_to_arr() { 543 | let cq = "左边的消息[CQ:face,id=178]看看我刚拍的照片[CQ:image,file=123.jpg]右边的消息"; 544 | let msg = cq_to_arr(cq.into()); 545 | println!("{msg:?}") 546 | } 547 | 548 | #[test] 549 | fn check_msg() { 550 | let msg: Message = Message::from_value(json!( 551 | [ 552 | { 553 | "type":"text", 554 | "data":{ 555 | "text":"Some msg" 556 | } 557 | }, 558 | { 559 | "type":"face", 560 | "data":{ 561 | "id":"0" 562 | } 563 | }, 564 | ] 565 | )) 566 | .unwrap(); 567 | let text_value: Segment = serde_json::from_value(json!({ 568 | "type":"text", 569 | "data":{ 570 | "text":"Some msg" 571 | } 572 | })) 573 | .unwrap(); 574 | let face_value: Segment = serde_json::from_value(json!({ 575 | "type":"face", 576 | "data":{ 577 | "id":"0" 578 | } 579 | })) 580 | .unwrap(); 581 | assert_eq!(msg.get("text")[0], text_value); 582 | assert_eq!(msg.get("face")[0], face_value); 583 | 584 | let msg1: Message = Message::from("Hi"); 585 | let msg2: Message = Message::from_value(json!( 586 | [ 587 | { 588 | "type":"text", 589 | "data":{ 590 | "text":"Some msg" 591 | } 592 | } 593 | ] 594 | )) 595 | .unwrap(); 596 | assert!(msg1.contains("text")); 597 | assert!(msg2.contains("text")); 598 | } 599 | --------------------------------------------------------------------------------