完成了基本命令部分,matrix登陆在测试中
This commit is contained in:
1 parent
bbbdd9eac5
commit
ad69931573
6 files changed
+310
-29
No files matched your search
+162
-14
@@ -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<Option<MessageRx>>) {
|
||||
})
|
||||
}
|
||||
|
||||
pub struct CommandHandler;
|
||||
type SharedBot = Arc<dyn Bot + Send + Sync>;
|
||||
|
||||
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<str>) -> 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<Vec<(String, OutboundMessage)>>,
|
||||
}
|
||||
|
||||
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<String> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<String>;
|
||||
}
|
||||
+60
-11
@@ -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<Client>,
|
||||
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<Self> {
|
||||
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<String> {
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user