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

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

No files matched your search

Generated
+172 -6
View File
@@ -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",
+1
View File
@@ -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"
+3 -3
View File
@@ -9,7 +9,7 @@
- init.rs 程序基础的初始化逻辑
# TODO
- [ ] 实现基础Sled DB的签到信息记录功能
- [ ] 实现matrix机器人收发
- [ ] 实现每日签到统计
- [x] 实现基础Sled DB的签到信息记录功能
- [x] 实现matrix机器人收发
- [x] 实现每日签到统计
- [ ] 实现每月签到统计
+4
View File
@@ -0,0 +1,4 @@
segment_size: 524288
use_compression: false
version: 0.34
vQ
Binary file not shown.
+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) {