修改了bot代码,基本实现了签到功能,还需实现定时统计

This commit is contained in:
:NoBody: committed 2026-04-05 22:49:47 +08:00
1 parent f86ed8c286
commit d358ed3ddc
15 files changed
+334 -25

No files matched your search

+59 -3
View File
@@ -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
View File
@@ -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
View File
@@ -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()
}
}
+1
View File
@@ -2,3 +2,4 @@ pub mod bot_handler;
pub mod command_parser;
pub mod define;
pub mod matrix;
pub mod schedule;
+28
View File
@@ -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(())
}
}
+15 -1
View File
@@ -18,5 +18,19 @@ impl<T: StorageEngine> CrudHandler<T> {
self.engine.set_raw(key, &value_bytes).await?;
Ok(())
}
//TODO:补全其他方法,比如每日清理,统计……
pub async fn reset_all_user_daily_state(&self) -> Result<()> {
let mut keys = self.engine.get_all_keys().await?;
for key in keys.drain(..) {
if let Some(value_bytes) = self.engine.get_raw(&key).await? {
let mut value: db::user_state::UserState = serde_json::from_slice(&value_bytes)?;
value.reset_daily();
let new_value_bytes = serde_json::to_vec(&value)?;
self.engine.set_raw(&key, &new_value_bytes).await?;
}
}
Ok(())
}
//TODO:补全其他方法,比如统计……
}
+1
View File
@@ -10,6 +10,7 @@ pub trait StorageEngine: Sized + Send + Sync {
async fn get_raw(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
async fn set_raw(&self, key: &[u8], value: &[u8]) -> Result<()>;
async fn delete_raw(&self, key: &[u8]) -> Result<()>;
async fn get_all_keys(&self) -> Result<Vec<Vec<u8>>>;
}
//上层语义化存储实现
+10
View File
@@ -59,6 +59,16 @@ impl StorageEngine for SledDB {
self.sled_db.flush()?;
Ok(())
}
async fn get_all_keys(&self) -> Result<Vec<Vec<u8>>> {
let keys = self
.sled_db
.iter()
.keys()
.filter_map(|res| res.ok())
.map(|k| k.to_vec())
.collect();
Ok(keys)
}
}
//INFO: AI写的集成测试
+24
View File
@@ -4,11 +4,27 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct UserState {
pub is_checkin_today: bool,
pub level: UserLevel,
pub checkin_unix_second: u64,
pub checkin_times_in_month: usize,
pub checkin_days: Vec<u32>, //每月在哪天签到了
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum UserLevel {
Super = 0, //表示不受限制的用户,直接享受最高权限,主要用于管理员账号
Bronze = 1,
Silver = 2,
Gold = 3,
Platinum = 4,
Diamond = 5,
}
impl Default for UserLevel {
fn default() -> Self {
UserLevel::Bronze
}
}
/*
key:用户id
value:UserState的json字符串
@@ -23,6 +39,7 @@ impl UserState {
checkin_unix_second: 0,
checkin_times_in_month: 0,
checkin_days: Vec::new(),
level: UserLevel::Bronze,
}
}
@@ -36,6 +53,13 @@ impl UserState {
if !self.checkin_days.contains(&day) {
self.checkin_days.push(day);
}
match self.checkin_times_in_month {
0..=14 => self.level = UserLevel::Bronze,
15..=30 => self.level = UserLevel::Silver,
31..=45 => self.level = UserLevel::Gold,
46..=60 => self.level = UserLevel::Platinum,
_ => self.level = UserLevel::Diamond,
}
}
pub fn reset_daily(&mut self) {
+1 -1
View File
@@ -26,7 +26,7 @@ async fn main() -> anyhow::Result<()> {
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;