完成了基本命令部分,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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user