添加了一些每日统计的辅助函数

This commit is contained in:
:NoBody: committed 2026-04-08 22:51:34 +08:00
1 parent 47c3e908ec
commit 7096384161
6 files changed
+87 -11

No files matched your search

+3
View File
@@ -243,6 +243,9 @@ mod tests {
async fn join_rooms(&self) -> Result<()> { async fn join_rooms(&self) -> Result<()> {
Ok(()) Ok(())
} }
async fn get_users_count(&self, _room_id: &str) -> Result<usize> {
return Ok(100);
}
async fn send_raw_message( async fn send_raw_message(
&self, &self,
+1 -1
View File
@@ -1,4 +1,3 @@
use tokio::task::JoinHandle; use tokio::task::JoinHandle;
use anyhow::Result; use anyhow::Result;
@@ -51,4 +50,5 @@ pub trait Bot {
async fn start(&self) -> Result<()>; async fn start(&self) -> Result<()>;
async fn join_rooms(&self) -> Result<()>; async fn join_rooms(&self) -> Result<()>;
async fn send_raw_message(&self, room_id: &str, message: &OutboundMessage) -> Result<String>; async fn send_raw_message(&self, room_id: &str, message: &OutboundMessage) -> Result<String>;
async fn get_users_count(&self, room_id: &str) -> Result<usize>;
} }
+9
View File
@@ -135,6 +135,15 @@ impl Bot for MatrixBot {
Ok(response.event_id.to_string()) Ok(response.event_id.to_string())
} }
async fn get_users_count(&self, room_id: &str) -> Result<usize> {
let room = self
.client
.get_room(&RoomId::parse(room_id)?)
.ok_or_else(|| anyhow!("未找到房间: {}", room_id))?;
let members = room.joined_members_count();
Ok(members as usize)
}
} }
#[cfg(test)] #[cfg(test)]
+48 -9
View File
@@ -1,28 +1,67 @@
use std::ops::Add;
use anyhow::{Ok, Result}; use anyhow::{Ok, Result};
use chrono::NaiveDate;
use log::info;
use crate::{config::Config, db};
pub struct ScheduleHandler { pub struct ScheduleHandler {
sche: tokio_cron_scheduler::JobScheduler, //这里可以添加一些定时任务相关的字段,比如定时器,任务列表等 sche: tokio_cron_scheduler::JobScheduler, //这里可以添加一些定时任务相关的字段,比如定时器,任务列表等
} }
impl ScheduleHandler { impl ScheduleHandler {
//new新实例后会自动启动定时任务,所以不需要单独调用start方法
pub async fn new() -> Self { pub async fn new() -> Self {
Self { let _self = Self {
sche: tokio_cron_scheduler::JobScheduler::new().await.unwrap(), sche: tokio_cron_scheduler::JobScheduler::new().await.unwrap(),
//初始化字段 //初始化字段
} };
_self.start().await.unwrap();
_self
} }
pub async fn start(&self) -> Result<()> { async fn start(&self) -> Result<()> {
//这里可以启动定时任务,比如使用tokio的定时器,或者其他的定时任务库 //这里可以启动定时任务,比如使用tokio的定时器,或者其他的定时任务库
info!("定时任务已启动");
self.sche.start().await?;
Ok(())
}
pub async fn add_daily_statistics_and_report_schedule(
&self,
bot: impl crate::bot::define::Bot + Send + Sync + 'static,
cron: impl AsRef<str>,
) -> Result<()> {
let cron = cron.as_ref();
//获取和转换日期
let date = chrono::Local::now()
.naive_local()
.date()
.add(chrono::Duration::hours(8)); //调整时区为北京时间
let date = date.format("%Y年%-m月%-d日").to_string();
//获取签到人数
let db_path = std::path::Path::new("daily_state.sled.db");
let db = db::crud_handler::CrudHandler::new(
db::sled_db::SledDB::new(db_path).expect("无法获取数据库实例"),
);
let states = db.get_all_user_state().await?;
let checked_nums = states.len();
//TODO:完成此函数,重点是获取全部人数,最好低耦合
let md_reply = r#"
# {date}签到统计报告
- 今日签到人数:{checked_nums}
"#; //每日统计报告
Ok(()) Ok(())
} }
pub fn daily_statistics_and_report(&self) -> Result<()> { pub fn add_month_statistics_and_report_schedule(&self, cron: impl AsRef<str>) -> Result<()> {
//这里可以实现每天统计和报告的逻辑,比如统计每天的消息数量,活跃用户等,并生成报告发送到指定的频道 let cron = cron.as_ref();
Ok(())
}
pub fn month_statistics_and_report(&self) -> Result<()> {
//这里可以实现每月统计和报告的逻辑,比如统计每月的消息数量,活跃用户等,并生成报告发送到指定的频道 //这里可以实现每月统计和报告的逻辑,比如统计每月的消息数量,活跃用户等,并生成报告发送到指定的频道
Ok(()) Ok(())
} }
+14 -1
View File
@@ -22,6 +22,16 @@ pub struct MatrixBot {
pub password: String, pub password: String,
pub rooms: Vec<Room>, pub rooms: Vec<Room>,
} }
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum RoomType {
MainRoom, //主房间,用于签到和汇报
SubRoom, //子房间,用于自动踢出,统计(默认)
RecoveryRoom, //恢复房间,用于被踢出用户的恢复,被踢出的用户会自动被邀请到这里
}
fn default_room_type() -> RoomType {
RoomType::SubRoom
}
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Room { pub struct Room {
@@ -32,6 +42,8 @@ pub struct Room {
pub kick_long_time: Option<isize>, pub kick_long_time: Option<isize>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub white_list: Option<Vec<OwnedUserId>>, pub white_list: Option<Vec<OwnedUserId>>,
#[serde(default = "default_room_type")]
pub room_type: RoomType,
} }
use thiserror::Error; use thiserror::Error;
#[derive(Debug, Error)] #[derive(Debug, Error)]
@@ -48,7 +60,7 @@ impl Config {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::config::Room; use crate::config::{Room, RoomType};
#[test] #[test]
fn room_test() { fn room_test() {
@@ -60,5 +72,6 @@ white_list=["@example:foo.bar"]
dbg!(&cfg); dbg!(&cfg);
let a: Room = toml::from_str::<Room>(cfg).unwrap(); let a: Room = toml::from_str::<Room>(cfg).unwrap();
dbg!(&a); dbg!(&a);
assert!(matches!(a.room_type, RoomType::SubRoom));
} }
} }
+12
View File
@@ -32,5 +32,17 @@ impl<T: StorageEngine> CrudHandler<T> {
Ok(()) Ok(())
} }
pub async fn get_all_user_state(&self) -> Result<Vec<(String, db::user_state::UserState)>> {
let mut result = Vec::new();
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 value: db::user_state::UserState = serde_json::from_slice(&value_bytes)?;
result.push((String::from_utf8(key)?, value));
}
}
Ok(result)
}
//TODO:补全其他方法,比如统计…… //TODO:补全其他方法,比如统计……
} }