修复了Matrix登陆问题,现在可以收到指令了

This commit is contained in:
:NoBody: committed 2026-03-30 20:48:57 +08:00
1 parent ad69931573
commit 9fda014ce6
5 files changed
+568 -37

No files matched your search

+10 -3
View File
@@ -11,7 +11,7 @@ type MessageRx = mpsc::Receiver<MessageEnum>;
static GLOBAL_CHANNEL: OnceLock<(MessageTx, Mutex<Option<MessageRx>>)> = OnceLock::new();
fn global_channel() -> &'static (MessageTx, Mutex<Option<MessageRx>>) {
pub fn global_channel() -> &'static (MessageTx, Mutex<Option<MessageRx>>) {
GLOBAL_CHANNEL.get_or_init(|| {
let (tx, rx) = mpsc::channel(100);
(tx, Mutex::new(Some(rx)))
@@ -92,12 +92,19 @@ impl AttendanceHandler for CommandHandler {
let mut rx = rx;
let bot = Arc::clone(&self.bot);
let handle = tokio::spawn(async move {
let handle: JoinHandle<()> = tokio::spawn(async move {
while let Some(msg) = rx.recv().await {
match msg {
MessageEnum::StopMessage => break,
MessageEnum::MatrixMessage(msg) => {
let text = msg.text.trim();
let text: &str = msg.text.trim();
log::info!(
"Received Matrix message (event_id={}, channel_id={}, user_id={}): {}",
msg.event_id,
msg.channel_id,
msg.user_id,
msg.text
);
let Some(command_text) = text.strip_prefix('!') else {
continue;
};
+124 -31
View File
@@ -1,18 +1,24 @@
use anyhow::{Result, anyhow};
use matrix_sdk::{
Client,
Client, Room,
config::SyncSettings,
ruma::{OwnedUserId, RoomId, UserId, events::room::message::SyncRoomMessageEvent, user_id},
ruma::{
OwnedUserId, RoomId, UserId,
events::room::message::{MessageType, OriginalSyncRoomMessageEvent},
},
};
use std::{sync::Arc, time::Duration};
use crate::{bot::define::Bot, config::Config};
use crate::{
bot::{bot_handler::global_channel, define::Bot},
config::Config,
};
pub struct MatrixBot {
client: Arc<Client>,
user_id: OwnedUserId,
password: String,
config: crate::config::MatrixBot,
pub client: Arc<Client>,
pub user_id: OwnedUserId,
pub password: String,
pub config: crate::config::MatrixBot,
}
impl MatrixBot {
@@ -23,10 +29,12 @@ impl MatrixBot {
.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())
.homeserver_url(cfg.home_server.clone())
.build()
.await
.map_err(|e| anyhow::anyhow!("创建Matrix客户端失败: {}", e))?,
@@ -38,22 +46,65 @@ impl MatrixBot {
}
}
async fn on_room_message(event: OriginalSyncRoomMessageEvent, room: Room) {
let MessageType::Text(text_content) = &event.content.msgtype else {
return;
};
dbg!(&event);
let (tx, _rx) = global_channel();
let msg = crate::bot::define::InboundMessage {
event_id: event.event_id.to_string(),
channel_id: room.room_id().to_string(),
user_id: event.sender.to_string(),
text: text_content.body.clone(),
timestamp_ms: tokio::time::Instant::now().elapsed().as_millis() as u64,
};
tx.send(super::define::MessageEnum::MatrixMessage(msg))
.await
.unwrap();
}
#[async_trait::async_trait]
impl Bot for MatrixBot {
async fn start(&self) -> anyhow::Result<()> {
let client = Arc::clone(&self.client);
let user_id = self.user_id.clone();
let password = self.password.clone();
log::info!("Matrix 机器人已启动 {}", self.user_id);
tokio::spawn(tokio_retry::Retry::spawn(
tokio_retry::Retry::spawn(
tokio_retry::strategy::FibonacciBackoff::from_millis(100)
.max_delay(Duration::from_secs(120)),
.max_delay(Duration::from_secs(120))
.take(5),
move || {
let client = Arc::clone(&client);
async move { client.sync(SyncSettings::default()).await }
},
));
log::info!("Matrix 机器人已登陆 {}", self.user_id);
dbg!("Matrix 机器人已登陆 {}", &self.user_id);
let user_id = user_id.clone();
let password = password.clone();
async move {
client
.matrix_auth()
.login_username(user_id.as_str(), &password)
.initial_device_display_name("Matrix Bot")
.await?;
log::info!("Matrix 机器人已登陆 {}", &user_id);
client.add_event_handler(on_room_message);
let sync_client = Arc::clone(&client);
tokio::spawn(async move {
let response = client.sync_once(SyncSettings::default()).await.unwrap();
let settings = SyncSettings::default().token(response.next_batch);
if let Err(e) = sync_client.sync(settings).await {
log::error!("Matrix 同步任务退出: {}", e);
}
});
Ok::<(), matrix_sdk::Error>(())
}
},
)
.await
.map_err(|e| anyhow!("Matrix 登录重试失败: {}", e))?;
tokio::spawn(async move {});
Ok(())
}
async fn join_rooms(&self) -> Result<()> {
@@ -65,7 +116,6 @@ impl Bot for MatrixBot {
room_id: &str,
message: &crate::bot::define::OutboundMessage,
) -> Result<String> {
let room = self.client.joined_rooms();
let content = matrix_sdk::ruma::events::room::message::RoomMessageEventContent::text_plain(
message.text.clone(),
);
@@ -81,35 +131,78 @@ impl Bot for MatrixBot {
}
}
#[cfg(test)]
mod tests {
use matrix_sdk::ruma::{api::client, events::room::message::RoomMessageEventContent};
use matrix_sdk::ruma::events::room::message::RoomMessageEventContent;
use std::sync::Arc;
use std::time::Duration;
use super::*;
use super::MatrixBot;
use crate::bot::bot_handler::CommandHandler;
use crate::bot::define::{AttendanceHandler, MessageEnum};
use crate::config::Config;
#[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.unwrap();
let _ = env_logger::Builder::new()
.filter_level(log::LevelFilter::Info)
.is_test(true)
.try_init();
let config = Config::get_all();
eprintln!("[test_matrix_bot] step=build_client");
let bot = tokio::time::timeout(
Duration::from_secs(20),
MatrixBot::new(
&config.matrix.clone().unwrap().username.as_ref(),
&config.matrix.clone().unwrap().password,
),
)
.await
.expect("MatrixBot::new() 超时,可能卡在 homeserver 发现或网络连接")
.unwrap();
eprintln!("[test_matrix_bot] step=start_bot");
bot.start().await.unwrap();
let bot = Arc::new(bot);
let command_bot: Arc<dyn super::Bot + Send + Sync> = bot.clone();
let command_handler = CommandHandler::new(command_bot);
let command_handle = command_handler.handle_commands().await.unwrap();
eprintln!("[test_matrix_bot] step=load_rooms");
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 = []
let mut rooms = client.joined_rooms();
let room = client
.join_room_by_id(
config
.matrix
.clone()
.unwrap()
.rooms
.get(0)
.unwrap()
.room_id
.as_ref(),
)
.await
.unwrap();
rooms.push(room);
//INFO: 这里不知道为啥,加入了房间,但是rooms为空,手动把房间加到rooms里,后续发送消息才能成功
*/
dbg!(&rooms);
for room in &rooms {
room.send(RoomMessageEventContent::text_plain("test"))
let content = RoomMessageEventContent::text_plain("test".to_string());
tokio::time::timeout(Duration::from_secs(20), room.send(content))
.await
.expect("room.send() 超时,可能卡在 Matrix 发送请求")
.unwrap();
}
tokio::signal::ctrl_c().await.unwrap();
tokio::time::sleep(Duration::from_secs(3)).await;
let stop_tx = CommandHandler::global_sender();
let _ = stop_tx.send(MessageEnum::StopMessage).await;
let _ = tokio::time::timeout(Duration::from_secs(5), command_handle).await;
}
}
+30 -3
View File
@@ -1,8 +1,35 @@
use anyhow::Ok;
use std::{sync::Arc, time::Duration};
use anyhow::anyhow;
use daily_bot::bot::{
bot_handler::CommandHandler,
define::{AttendanceHandler, Bot, MessageEnum},
matrix::MatrixBot,
};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
daily_bot::init::init().await?; //执行初始化逻辑,主要是加载配置文件,创建数据库连接池等。
tokio::signal::ctrl_c().await?; //等待Ctrl+C信号以优雅地关闭应用程序。
daily_bot::init::init().await?; // 执行初始化逻辑,主要是加载配置文件,创建数据库连接池等。
let cfg = daily_bot::config::Config::get_all();
let matrix_cfg = cfg
.matrix
.as_ref()
.ok_or_else(|| anyhow!("Matrix config not found"))?;
let bot = MatrixBot::new(matrix_cfg.username.as_ref(), &matrix_cfg.password).await?;
bot.start().await?;
bot.join_rooms().await?;
let bot = Arc::new(bot);
let command_handler = CommandHandler::new(bot);
let command_handle = command_handler.handle_commands().await?;
tokio::signal::ctrl_c().await?; // 等待 Ctrl+C 信号以优雅地关闭应用程序。
let stop_tx = CommandHandler::global_sender();
let _ = stop_tx.send(MessageEnum::StopMessage).await;
let _ = tokio::time::timeout(Duration::from_secs(5), command_handle).await;
Ok(())
}