修改了bot代码,基本实现了签到功能,还需实现定时统计
This commit is contained in:
1 parent
f86ed8c286
commit
d358ed3ddc
15 files changed
+334
-25
No files matched your search
+59
-3
@@ -1,7 +1,9 @@
|
||||
use crate::bot::command_parser::parse_command;
|
||||
use crate::bot::define::{AttendanceHandler, Bot, InboundMessage, MessageEnum, OutboundMessage};
|
||||
use crate::db::crud_handler;
|
||||
use anyhow::{Result, anyhow};
|
||||
use async_trait::async_trait;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
@@ -11,13 +13,57 @@ type MessageRx = mpsc::Receiver<MessageEnum>;
|
||||
|
||||
static GLOBAL_CHANNEL: OnceLock<(MessageTx, Mutex<Option<MessageRx>>)> = OnceLock::new();
|
||||
|
||||
pub fn global_channel() -> &'static (MessageTx, Mutex<Option<MessageRx>>) {
|
||||
fn global_channel() -> &'static (MessageTx, Mutex<Option<MessageRx>>) {
|
||||
GLOBAL_CHANNEL.get_or_init(|| {
|
||||
let (tx, rx) = mpsc::channel(100);
|
||||
(tx, Mutex::new(Some(rx)))
|
||||
})
|
||||
}
|
||||
|
||||
pub struct ChannelManager {
|
||||
tx: MessageTx,
|
||||
rx: &'static Mutex<Option<MessageRx>>,
|
||||
filters: Option<Vec<Box<dyn Fn(&MessageEnum) -> MessageEnum + Send + Sync>>>,
|
||||
}
|
||||
|
||||
//channel的包装,提供过滤功能,后续可以考虑增加更多功能,比如广播等
|
||||
impl ChannelManager {
|
||||
pub fn new() -> Self {
|
||||
let (tx, rx) = global_channel();
|
||||
|
||||
Self {
|
||||
tx: tx.clone(),
|
||||
rx,
|
||||
filters: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn filter_message(&self, msg: &MessageEnum) -> MessageEnum {
|
||||
let mut result_msg = msg.clone();
|
||||
if let Some(filters) = &self.filters {
|
||||
for filter in filters {
|
||||
result_msg = filter(&result_msg);
|
||||
}
|
||||
}
|
||||
result_msg
|
||||
}
|
||||
//这里先过滤,在发送,后续可以考虑在接收时过滤
|
||||
pub async fn send(&self, value: MessageEnum) -> Result<()> {
|
||||
let tx = self.tx.clone();
|
||||
let msg = self.filter_message(&value);
|
||||
|
||||
tx.send(msg)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to send message: {}", e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_receiver(&self) -> Option<MessageRx> {
|
||||
self.rx.lock().unwrap().take()
|
||||
}
|
||||
}
|
||||
|
||||
type SharedBot = Arc<dyn Bot + Send + Sync>;
|
||||
|
||||
pub struct CommandHandler {
|
||||
@@ -62,9 +108,19 @@ async fn start_bot_command_processor(
|
||||
bot.send_raw_message(&outbound.channel_id, &outbound)
|
||||
.await?;
|
||||
}
|
||||
"checkin"=>{
|
||||
|
||||
"checkin" => {
|
||||
let crud_handler = crud_handler::CrudHandler::new(crate::db::sled_db::SledDB::new(
|
||||
Path::new("daily_state.sled.db"),
|
||||
)?);
|
||||
|
||||
crud_handler.checkin(&inbound.user_id).await?;
|
||||
let outbound = OutboundMessage {
|
||||
channel_id: inbound.channel_id.clone(),
|
||||
text: format!(" {} 已签到成功", inbound.user_id),
|
||||
reply_to_event_id: Some(inbound.event_id.clone()),
|
||||
};
|
||||
bot.send_raw_message(&outbound.channel_id, &outbound)
|
||||
.await?;
|
||||
}
|
||||
_ => {
|
||||
return Err(anyhow!("unknown command: {}", command));
|
||||
|
||||
+2
-1
@@ -22,7 +22,7 @@ pub struct OutboundMessage {
|
||||
pub reply_to_event_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct InboundMessage {
|
||||
pub event_id: String,
|
||||
pub channel_id: String,
|
||||
@@ -42,6 +42,7 @@ pub trait AttendanceHandler {
|
||||
async fn handle_commands(&self) -> Result<JoinHandle<()>>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum MessageEnum {
|
||||
MatrixMessage(InboundMessage),
|
||||
TelegramMessage(InboundMessage),
|
||||
|
||||
+13
-10
@@ -10,7 +10,7 @@ use matrix_sdk::{
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use crate::{
|
||||
bot::{bot_handler::global_channel, define::Bot},
|
||||
bot::{bot_handler::ChannelManager, define::Bot},
|
||||
config::Config,
|
||||
};
|
||||
|
||||
@@ -51,17 +51,23 @@ async fn on_room_message(event: OriginalSyncRoomMessageEvent, room: Room) {
|
||||
return;
|
||||
};
|
||||
dbg!(&event);
|
||||
let (tx, _rx) = global_channel();
|
||||
let cm = ChannelManager::new();
|
||||
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,
|
||||
timestamp_ms: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis() as u64,
|
||||
};
|
||||
tx.send(super::define::MessageEnum::MatrixMessage(msg))
|
||||
if let Err(e) = cm
|
||||
.send(super::define::MessageEnum::MatrixMessage(msg))
|
||||
.await
|
||||
.unwrap();
|
||||
{
|
||||
log::error!("Failed to send matrix message to command handler: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -169,7 +175,7 @@ mod tests {
|
||||
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();
|
||||
let _command_handle = command_handler.handle_commands().await.unwrap();
|
||||
|
||||
eprintln!("[test_matrix_bot] step=load_rooms");
|
||||
let client = Arc::clone(&bot.client);
|
||||
@@ -200,9 +206,6 @@ mod tests {
|
||||
.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;
|
||||
tokio::signal::ctrl_c().await.unwrap()
|
||||
}
|
||||
}
|
||||
@@ -2,3 +2,4 @@ pub mod bot_handler;
|
||||
pub mod command_parser;
|
||||
pub mod define;
|
||||
pub mod matrix;
|
||||
pub mod schedule;
|
||||
@@ -0,0 +1,28 @@
|
||||
use anyhow::{Ok, Result};
|
||||
use tokio_cron_scheduler::{Job, JobScheduler};
|
||||
pub struct ScheduleHandler {
|
||||
//这里可以添加一些定时任务相关的字段,比如定时器,任务列表等
|
||||
}
|
||||
|
||||
impl ScheduleHandler {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
//初始化字段
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start(&self) -> Result<()> {
|
||||
//这里可以启动定时任务,比如使用tokio的定时器,或者其他的定时任务库
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn daily_statistics_and_report(&self) -> Result<()> {
|
||||
//这里可以实现每天统计和报告的逻辑,比如统计每天的消息数量,活跃用户等,并生成报告发送到指定的频道
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn month_statistics_and_report(&self) -> Result<()> {
|
||||
//这里可以实现每月统计和报告的逻辑,比如统计每月的消息数量,活跃用户等,并生成报告发送到指定的频道
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user