From d358ed3ddc3034014294ea0de54ac6849a1be898 Mon Sep 17 00:00:00 2001 From: ":NoBody:" Date: Tue, 31 Mar 2026 22:45:38 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86bot=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=EF=BC=8C=E5=9F=BA=E6=9C=AC=E5=AE=9E=E7=8E=B0=E4=BA=86?= =?UTF-8?q?=E7=AD=BE=E5=88=B0=E5=8A=9F=E8=83=BD=EF=BC=8C=E8=BF=98=E9=9C=80?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E5=AE=9A=E6=97=B6=E7=BB=9F=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 178 +++++++++++++++++++++++++++++++++++++-- Cargo.toml | 1 + README.md | 6 +- daily_state.sled.db/conf | 4 + daily_state.sled.db/db | Bin 0 -> 237 bytes src/bot/bot_handler.rs | 62 +++++++++++++- src/bot/define.rs | 3 +- src/bot/matrix.rs | 23 ++--- src/bot/mod.rs | 1 + src/bot/schedule.rs | 28 ++++++ src/db/crud_handler.rs | 16 +++- src/db/define.rs | 1 + src/db/sled_db.rs | 10 +++ src/db/user_state.rs | 24 ++++++ src/main.rs | 2 +- 15 files changed, 334 insertions(+), 25 deletions(-) create mode 100644 daily_state.sled.db/conf create mode 100644 daily_state.sled.db/db create mode 100644 src/bot/schedule.rs diff --git a/Cargo.lock b/Cargo.lock index ce21fe1..191086c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -445,6 +445,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "chrono-tz" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3" +dependencies = [ + "chrono", + "phf 0.12.1", +] + [[package]] name = "cipher" version = "0.4.4" @@ -572,6 +582,17 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "croner" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aa42bcd3d846ebf66e15bd528d1087f75d1c6c1c66ebff626178a106353c576" +dependencies = [ + "chrono", + "derive_builder", + "strum", +] + [[package]] name = "crossbeam-epoch" version = "0.9.18" @@ -652,10 +673,46 @@ dependencies = [ "sled", "thiserror 2.0.18", "tokio", + "tokio-cron-scheduler", "tokio-retry", "toml 1.0.7+spec-1.1.0", ] +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.117", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.117", +] + [[package]] name = "dashmap" version = "6.1.0" @@ -760,6 +817,37 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "derive_builder" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "derive_builder_macro" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" +dependencies = [ + "derive_builder_core", + "syn 2.0.117", +] + [[package]] name = "derive_more" version = "1.0.0" @@ -1567,6 +1655,12 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -2325,6 +2419,17 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050" +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2464,7 +2569,16 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" dependencies = [ - "phf_shared", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" +dependencies = [ + "phf_shared 0.12.1", ] [[package]] @@ -2474,7 +2588,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" dependencies = [ "phf_generator", - "phf_shared", + "phf_shared 0.11.3", ] [[package]] @@ -2483,7 +2597,7 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ - "phf_shared", + "phf_shared 0.11.3", "rand 0.8.5", ] @@ -2496,6 +2610,15 @@ dependencies = [ "siphasher", ] +[[package]] +name = "phf_shared" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project" version = "1.1.11" @@ -3622,7 +3745,7 @@ checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" dependencies = [ "new_debug_unreachable", "parking_lot 0.12.5", - "phf_shared", + "phf_shared 0.11.3", "precomputed-hash", "serde", ] @@ -3634,11 +3757,38 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" dependencies = [ "phf_generator", - "phf_shared", + "phf_shared 0.11.3", "proc-macro2", "quote", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "subtle" version = "2.6.1" @@ -3854,6 +4004,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "tokio-cron-scheduler" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f50e41f200fd8ed426489bd356910ede4f053e30cebfbd59ef0f856f0d7432a" +dependencies = [ + "chrono", + "chrono-tz", + "croner", + "num-derive", + "num-traits", + "tokio", + "tracing", + "uuid", +] + [[package]] name = "tokio-macros" version = "2.6.0" @@ -4462,7 +4628,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57ffde1dc01240bdf9992e3205668b235e59421fd085e8a317ed98da0178d414" dependencies = [ - "phf", + "phf 0.11.3", "phf_codegen", "string_cache", "string_cache_codegen", diff --git a/Cargo.toml b/Cargo.toml index 7e77aaf..b2c904f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ serde_json = "1.0.149" sled = "0.34.7" thiserror = "2.0.18" tokio = {version="1.50.0",features=["full"]} +tokio-cron-scheduler = "0.15.1" tokio-retry = "0.3.0" toml = "1.0.7" diff --git a/README.md b/README.md index 8d955ad..9756e5c 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ - init.rs 程序基础的初始化逻辑 # TODO -- [ ] 实现基础Sled DB的签到信息记录功能 -- [ ] 实现matrix机器人收发 -- [ ] 实现每日签到统计 +- [x] 实现基础Sled DB的签到信息记录功能 +- [x] 实现matrix机器人收发 +- [x] 实现每日签到统计 - [ ] 实现每月签到统计 \ No newline at end of file diff --git a/daily_state.sled.db/conf b/daily_state.sled.db/conf new file mode 100644 index 0000000..4154d7c --- /dev/null +++ b/daily_state.sled.db/conf @@ -0,0 +1,4 @@ +segment_size: 524288 +use_compression: false +version: 0.34 +vQÁ \ No newline at end of file diff --git a/daily_state.sled.db/db b/daily_state.sled.db/db new file mode 100644 index 0000000000000000000000000000000000000000..ad5c596f7b1c9f069950174cd78c22db36e1fa2f GIT binary patch literal 237 zcmeyr>p1^^2&iX(fCl^e3%}Wb?7~IIDp(mA7#UtGHZSDhU|@nOVECw1oX^3DDk-%j(JD8wq$smO zFTW_gpjs)jI6gTeH90#oFTNx{C9zV;s-&niRYxf&wJbG9$x6woC_k?%RY^w)rm8eA tvm(AYH90>oMajwlAzqT1n_3(XG$uDcuOvgs$`Bz1G`3jDD%v!*766}=PCx(v literal 0 HcmV?d00001 diff --git a/src/bot/bot_handler.rs b/src/bot/bot_handler.rs index 0780bab..442aa03 100644 --- a/src/bot/bot_handler.rs +++ b/src/bot/bot_handler.rs @@ -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; static GLOBAL_CHANNEL: OnceLock<(MessageTx, Mutex>)> = OnceLock::new(); -pub fn global_channel() -> &'static (MessageTx, Mutex>) { +fn global_channel() -> &'static (MessageTx, Mutex>) { GLOBAL_CHANNEL.get_or_init(|| { let (tx, rx) = mpsc::channel(100); (tx, Mutex::new(Some(rx))) }) } +pub struct ChannelManager { + tx: MessageTx, + rx: &'static Mutex>, + filters: Option 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 { + self.rx.lock().unwrap().take() + } +} + type SharedBot = Arc; 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)); diff --git a/src/bot/define.rs b/src/bot/define.rs index a82ad02..a5cc42f 100644 --- a/src/bot/define.rs +++ b/src/bot/define.rs @@ -22,7 +22,7 @@ pub struct OutboundMessage { pub reply_to_event_id: Option, } -#[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>; } +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum MessageEnum { MatrixMessage(InboundMessage), TelegramMessage(InboundMessage), diff --git a/src/bot/matrix.rs b/src/bot/matrix.rs index 73ff5d2..55f098a 100644 --- a/src/bot/matrix.rs +++ b/src/bot/matrix.rs @@ -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 = 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() } } diff --git a/src/bot/mod.rs b/src/bot/mod.rs index 3ce9616..19f318b 100644 --- a/src/bot/mod.rs +++ b/src/bot/mod.rs @@ -2,3 +2,4 @@ pub mod bot_handler; pub mod command_parser; pub mod define; pub mod matrix; +pub mod schedule; diff --git a/src/bot/schedule.rs b/src/bot/schedule.rs new file mode 100644 index 0000000..6574901 --- /dev/null +++ b/src/bot/schedule.rs @@ -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(()) + } +} diff --git a/src/db/crud_handler.rs b/src/db/crud_handler.rs index a12ab8b..5ad5409 100644 --- a/src/db/crud_handler.rs +++ b/src/db/crud_handler.rs @@ -18,5 +18,19 @@ impl CrudHandler { 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:补全其他方法,比如统计…… } diff --git a/src/db/define.rs b/src/db/define.rs index 8be6ade..3b0bc8b 100644 --- a/src/db/define.rs +++ b/src/db/define.rs @@ -10,6 +10,7 @@ pub trait StorageEngine: Sized + Send + Sync { async fn get_raw(&self, key: &[u8]) -> Result>>; 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>>; } //上层语义化存储实现 diff --git a/src/db/sled_db.rs b/src/db/sled_db.rs index dcf96f4..6a0afbc 100644 --- a/src/db/sled_db.rs +++ b/src/db/sled_db.rs @@ -59,6 +59,16 @@ impl StorageEngine for SledDB { self.sled_db.flush()?; Ok(()) } + async fn get_all_keys(&self) -> Result>> { + let keys = self + .sled_db + .iter() + .keys() + .filter_map(|res| res.ok()) + .map(|k| k.to_vec()) + .collect(); + Ok(keys) + } } //INFO: AI写的集成测试 diff --git a/src/db/user_state.rs b/src/db/user_state.rs index 48b4a52..87bc0ee 100644 --- a/src/db/user_state.rs +++ b/src/db/user_state.rs @@ -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, //每月在哪天签到了 } +#[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) { diff --git a/src/main.rs b/src/main.rs index 73ab7b0..0eca9d7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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;