From ad69931573354b81f828b78ad339776018ef0395 Mon Sep 17 00:00:00 2001 From: ":NoBody:" Date: Sun, 29 Mar 2026 19:55:20 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E4=BA=86=E5=9F=BA=E6=9C=AC?= =?UTF-8?q?=E5=91=BD=E4=BB=A4=E9=83=A8=E5=88=86=EF=BC=8Cmatrix=E7=99=BB?= =?UTF-8?q?=E9=99=86=E5=9C=A8=E6=B5=8B=E8=AF=95=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- example.config.toml | 39 +++++++++ src/bot/bot_handler.rs | 176 +++++++++++++++++++++++++++++++++++++---- src/bot/define.rs | 3 + src/bot/matrix.rs | 71 ++++++++++++++--- src/config.rs | 46 ++++++++++- src/init.rs | 4 +- 6 files changed, 310 insertions(+), 29 deletions(-) diff --git a/example.config.toml b/example.config.toml index e69de29..923d60c 100644 --- a/example.config.toml +++ b/example.config.toml @@ -0,0 +1,39 @@ +# daily_bot 配置示例 +# 将此文件复制为 config.toml 并按你的环境修改。 + +[matrix] +# Matrix homeserver 域名(不带 https://)。 +# 例: matrix.org / your-company.com +home_server = "matrix.org" + +# 机器人账号(完整 Matrix 用户 ID)。 +# 格式: @用户名:域名 +username = "@daily-bot:matrix.org" + +# 机器人密码。 +password = "replace-with-strong-password" + +# 需要管理/监听的房间列表。 + +[[matrix.rooms]] +# 房间 ID。 +# 格式: !xxxx:域名 +room_id = "!exampleRoomA:matrix.org" + +# 是否开启“长期未打卡踢人”逻辑。 +kick_member_if_they_didnot_checkin_for_long_time = true + +# 触发踢人的阈值(单位由你的业务逻辑决定,当前代码仅做配置读取)。 +kick_long_time = 30 + +# 白名单用户(不会被踢)。 +# 格式: @用户名:域名 +white_list = ["@admin:matrix.org", "@owner:matrix.org"] + +[[matrix.rooms]] +room_id = "!exampleRoomB:matrix.org" + +# 可选字段都可以不写;省略时表示不启用对应能力。 +# kick_member_if_they_didnot_checkin_for_long_time = false +# kick_long_time = 0 +# white_list = [] diff --git a/src/bot/bot_handler.rs b/src/bot/bot_handler.rs index ca85d9d..3f94d5e 100644 --- a/src/bot/bot_handler.rs +++ b/src/bot/bot_handler.rs @@ -1,8 +1,8 @@ use crate::bot::command_parser::parse_command; -use crate::bot::define::{AttendanceHandler, MessageEnum}; +use crate::bot::define::{AttendanceHandler, Bot, InboundMessage, MessageEnum, OutboundMessage}; use anyhow::{Result, anyhow}; use async_trait::async_trait; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock}; use tokio::sync::mpsc; use tokio::task::JoinHandle; @@ -18,11 +18,15 @@ fn global_channel() -> &'static (MessageTx, Mutex>) { }) } -pub struct CommandHandler; +type SharedBot = Arc; + +pub struct CommandHandler { + bot: SharedBot, +} impl CommandHandler { - pub fn new() -> Self { - Self + pub fn new(bot: SharedBot) -> Self { + Self { bot } } pub fn global_sender() -> MessageTx { @@ -30,14 +34,34 @@ impl CommandHandler { } } -async fn bot_command_processor(command: AsRef) -> Result<()> { - let command = command.as_ref(); - - let ast = parse_command(command)?; +async fn start_bot_command_processor( + bot: &(dyn Bot + Send + Sync), + inbound: &InboundMessage, + command_text: &str, +) -> Result<()> { + let ast = parse_command(command_text)?; let command = ast.command.as_str(); match command { - "!echo" => {} + "echo" => { + let text = ast.arguments.join(" "); + let outbound = OutboundMessage { + channel_id: inbound.channel_id.clone(), + text, + reply_to_event_id: Some(inbound.event_id.clone()), + }; + bot.send_raw_message(&outbound.channel_id, &outbound) + .await?; + } + "ping" => { + let outbound = OutboundMessage { + channel_id: inbound.channel_id.clone(), + text: "pong".to_string(), + reply_to_event_id: Some(inbound.event_id.clone()), + }; + bot.send_raw_message(&outbound.channel_id, &outbound) + .await?; + } _ => { return Err(anyhow!("unknown command: {}", command)); } @@ -67,15 +91,44 @@ impl AttendanceHandler for CommandHandler { }; let mut rx = rx; + let bot = Arc::clone(&self.bot); let handle = tokio::spawn(async move { while let Some(msg) = rx.recv().await { match msg { MessageEnum::StopMessage => break, - MessageEnum::MatrixMessage(_msg) => { - // TODO: route matrix message to command processor. + MessageEnum::MatrixMessage(msg) => { + let text = msg.text.trim(); + let Some(command_text) = text.strip_prefix('!') else { + continue; + }; + + if let Err(err) = + start_bot_command_processor(bot.as_ref(), &msg, command_text).await + { + log::warn!( + "failed to process matrix command (event_id={}, channel_id={}): {}", + msg.event_id, + msg.channel_id, + err + ); + } } - MessageEnum::TelegramMessage(_msg) => { - // TODO: route telegram message to command processor. + MessageEnum::TelegramMessage(msg) => { + let text = msg.text.trim(); + let Some(command_text) = text.strip_prefix('/') else { + continue; + }; + + if let Err(err) = + start_bot_command_processor(bot.as_ref(), &msg, command_text).await + { + log::warn!( + "failed to process telegram command (event_id={}, channel_id={}): {}", + msg.event_id, + msg.channel_id, + err + ); + } } } } @@ -84,3 +137,98 @@ impl AttendanceHandler for CommandHandler { Ok(handle) } } + +#[cfg(test)] +mod tests { + use super::start_bot_command_processor; + use crate::bot::define::{Bot, InboundMessage, OutboundMessage}; + use anyhow::Result; + use async_trait::async_trait; + use std::sync::Mutex; + + #[derive(Default)] + struct MockBot { + sent: Mutex>, + } + + impl MockBot { + fn sent_messages(&self) -> Vec<(String, OutboundMessage)> { + self.sent.lock().expect("mock sent lock poisoned").clone() + } + } + + #[async_trait] + impl Bot for MockBot { + async fn start(&self) -> Result<()> { + Ok(()) + } + + async fn join_rooms(&self) -> Result<()> { + Ok(()) + } + + async fn send_raw_message( + &self, + room_id: &str, + message: &OutboundMessage, + ) -> Result { + self.sent + .lock() + .expect("mock sent lock poisoned") + .push((room_id.to_string(), message.clone())); + Ok("mock_event_id".to_string()) + } + } + + fn make_inbound(text: &str) -> InboundMessage { + InboundMessage { + event_id: "$event_1".to_string(), + channel_id: "!room:example.org".to_string(), + user_id: "@alice:example.org".to_string(), + text: text.to_string(), + timestamp_ms: 1, + } + } + + #[tokio::test] + async fn processor_ping_sends_pong_to_source_channel() { + let bot = MockBot::default(); + let inbound = make_inbound("!ping"); + + let result = start_bot_command_processor(&bot, &inbound, "ping").await; + + assert!(result.is_ok()); + let sent = bot.sent_messages(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].0, "!room:example.org"); + assert_eq!(sent[0].1.channel_id, "!room:example.org"); + assert_eq!(sent[0].1.text, "pong"); + assert_eq!(sent[0].1.reply_to_event_id.as_deref(), Some("$event_1")); + } + + #[tokio::test] + async fn processor_echo_sends_joined_arguments_to_source_channel() { + let bot = MockBot::default(); + let inbound = make_inbound("!echo hello world"); + + let result = start_bot_command_processor(&bot, &inbound, "echo hello world").await; + + assert!(result.is_ok()); + let sent = bot.sent_messages(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].1.text, "hello world"); + assert_eq!(sent[0].1.channel_id, "!room:example.org"); + assert_eq!(sent[0].1.reply_to_event_id.as_deref(), Some("$event_1")); + } + + #[tokio::test] + async fn processor_unknown_command_returns_error_and_sends_nothing() { + let bot = MockBot::default(); + let inbound = make_inbound("!doesnotexist"); + + let result = start_bot_command_processor(&bot, &inbound, "doesnotexist").await; + + assert!(result.is_err()); + assert_eq!(bot.sent_messages().len(), 0); + } +} diff --git a/src/bot/define.rs b/src/bot/define.rs index 80db6c2..a82ad02 100644 --- a/src/bot/define.rs +++ b/src/bot/define.rs @@ -1,5 +1,6 @@ use std::{sync::OnceLock, time::Duration}; +use serde::{Deserialize, de::DeserializeOwned}; use tokio::task::JoinHandle; use anyhow::Result; @@ -49,4 +50,6 @@ pub enum MessageEnum { #[async_trait] pub trait Bot { async fn start(&self) -> Result<()>; + async fn join_rooms(&self) -> Result<()>; + async fn send_raw_message(&self, room_id: &str, message: &OutboundMessage) -> Result; } diff --git a/src/bot/matrix.rs b/src/bot/matrix.rs index 56ec6f6..a545ad3 100644 --- a/src/bot/matrix.rs +++ b/src/bot/matrix.rs @@ -1,33 +1,40 @@ -use std::{sync::Arc, time::Duration}; - +use anyhow::{Result, anyhow}; use matrix_sdk::{ Client, config::SyncSettings, - ruma::{OwnedUserId, UserId, events::room::message::SyncRoomMessageEvent, user_id}, + ruma::{OwnedUserId, RoomId, UserId, events::room::message::SyncRoomMessageEvent, user_id}, }; +use std::{sync::Arc, time::Duration}; -use crate::bot::define::Bot; +use crate::{bot::define::Bot, config::Config}; -struct MatrixBot { +pub struct MatrixBot { client: Arc, user_id: OwnedUserId, password: String, + config: crate::config::MatrixBot, } impl MatrixBot { - pub async fn new(user_id: &str, password: &str) -> Self { - let user_id = UserId::parse(user_id).expect("用户ID不合法"); - Self { + pub async fn new(user_id: &str, password: &str) -> Result { + let user_id = UserId::parse(user_id)?; + let cfg = Config::get_all(); + let cfg = cfg + .matrix + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Matrix config not found"))?; + Ok(Self { client: Arc::new( Client::builder() .server_name(user_id.server_name()) .build() .await - .expect("创建Matrix客户端失败"), + .map_err(|e| anyhow::anyhow!("创建Matrix客户端失败: {}", e))?, ), user_id: user_id.to_owned(), password: password.to_string(), - } + config: cfg.clone(), + }) } } @@ -49,18 +56,60 @@ impl Bot for MatrixBot { Ok(()) } + async fn join_rooms(&self) -> Result<()> { + for _room in &self.config.rooms {} + Ok(()) + } + async fn send_raw_message( + &self, + room_id: &str, + message: &crate::bot::define::OutboundMessage, + ) -> Result { + let room = self.client.joined_rooms(); + let content = matrix_sdk::ruma::events::room::message::RoomMessageEventContent::text_plain( + message.text.clone(), + ); + let room_id = RoomId::parse(room_id)?; + let room = self + .client + .get_room(&room_id) + .ok_or_else(|| anyhow!("未找到房间: {}", room_id))?; + + let response = room.send(content).await?; + + Ok(response.event_id.to_string()) + } } mod tests { + use matrix_sdk::ruma::{api::client, events::room::message::RoomMessageEventContent}; + use super::*; #[tokio::test] async fn test_matrix_bot() { + use super::Bot; let userid_str = std::env::var("MATRIX_USER").expect("请设置环境变量 MATRIX_USER"); let userid = UserId::parse(&userid_str).expect("用户ID不合法"); let password = std::env::var("MATRIX_PASSWORD").expect("请设置环境变量 MATRIX_PASSWORD"); - let bot = MatrixBot::new(userid.as_ref(), &password).await; + let bot = MatrixBot::new(userid.as_ref(), &password).await.unwrap(); bot.start().await.unwrap(); + let client = Arc::clone(&bot.client); + let rooms = client.joined_rooms(); + //FIXME:似乎没登陆上去,明天再修吧 + /* + running 1 test + [src/bot/matrix.rs:55:9] "Matrix 机器人已登陆 {}" = "Matrix 机器人已登陆 {}" + [src/bot/matrix.rs:55:9] & __self.user_id = + [src/bot/matrix.rs:99:9] &rooms = [] + + */ + dbg!(&rooms); + for room in &rooms { + room.send(RoomMessageEventContent::text_plain("test")) + .await + .unwrap(); + } tokio::signal::ctrl_c().await.unwrap(); } } diff --git a/src/config.rs b/src/config.rs index a021004..6b07a10 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,8 +1,9 @@ +use matrix_sdk::ruma::{OwnedRoomId, OwnedUserId, UserId}; use serde::{Deserialize, Serialize}; use std::{path::Path, sync::OnceLock}; static CONFIG: OnceLock = OnceLock::new(); -pub fn get_config() -> &'static Config { +fn get_config() -> &'static Config { CONFIG.get_or_init(|| { toml::from_str(&std::fs::read_to_string(Path::new("config.toml")).expect("无法读配置文件")) .expect("解析配置文件时发生错误") @@ -14,9 +15,50 @@ pub struct Config { pub matrix: Option, } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct MatrixBot { pub home_server: String, pub username: String, pub password: String, + pub rooms: Vec, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct Room { + pub room_id: OwnedRoomId, + #[serde(skip_serializing_if = "Option::is_none")] + pub kick_member_if_they_didnot_checkin_for_long_time: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub kick_long_time: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub white_list: Option>, +} +use thiserror::Error; +#[derive(Debug, Error)] +enum ConfigError { + #[error("{0} is not exist")] + NonExixtent(String), +} + +impl Config { + pub fn get_all() -> &'static Self { + get_config() + } +} + +#[cfg(test)] +mod tests { + use crate::config::Room; + + #[test] + fn room_test() { + let cfg = r#"room_id="!example:foo.bar" +kick_member_if_they_didnot_checkin_for_long_time=true +kick_long_time=1 +white_list=["@example:foo.bar"] + "#; + dbg!(&cfg); + let a: Room = toml::from_str::(cfg).unwrap(); + dbg!(&a); + } } diff --git a/src/init.rs b/src/init.rs index e2cf3a7..84671a4 100644 --- a/src/init.rs +++ b/src/init.rs @@ -1,7 +1,7 @@ -use crate::config::get_config; +use crate::config::Config; use anyhow::{Ok, Result}; pub async fn init() -> Result<()> { - get_config(); //初始化配置 + Config::get_all(); //初始化配置 env_logger::init(); //初始化日志 Ok(()) }