可以正常运行每日签到,正在完善签到等级功能

This commit is contained in:
:NoBody: committed 2026-04-12 21:50:04 +08:00
1 parent 9dbd544b47
commit 99869ac3ad
8 files changed
+357 -110

No files matched your search

Binary file not shown.
Binary file not shown.
+238 -106
View File
@@ -2,6 +2,7 @@ use crate::bot::command_parser::parse_command;
use crate::bot::define::{AttendanceHandler, Bot, InboundMessage, MessageEnum, OutboundMessage}; use crate::bot::define::{AttendanceHandler, Bot, InboundMessage, MessageEnum, OutboundMessage};
use crate::bot::filters::support_chinese_command; use crate::bot::filters::support_chinese_command;
use crate::db::crud_handler; use crate::db::crud_handler;
use crate::db::define::StorageEngine;
use anyhow::{Result, anyhow}; use anyhow::{Result, anyhow};
use async_trait::async_trait; use async_trait::async_trait;
use std::path::Path; use std::path::Path;
@@ -91,7 +92,7 @@ impl CommandHandler {
} }
async fn start_bot_command_processor( async fn start_bot_command_processor(
bot: &(dyn Bot + Send + Sync), bot: &SharedBot,
inbound: &InboundMessage, inbound: &InboundMessage,
command_text: &str, command_text: &str,
) -> Result<()> { ) -> Result<()> {
@@ -118,11 +119,150 @@ async fn start_bot_command_processor(
bot.send_raw_message(&outbound.channel_id, &outbound) bot.send_raw_message(&outbound.channel_id, &outbound)
.await?; .await?;
} }
"reset" => {
let crud_handler = crud_handler::CrudHandler::new(crate::db::sled_db::SledDB::new(
Path::new("daily_state.sled.db"),
)?);
crud_handler.reset_all_user_daily_state().await?;
let outbound = OutboundMessage {
channel_id: inbound.channel_id.clone(),
text: "已重置所有用户的每日签到状态".to_string(),
reply_to_event_id: Some(inbound.event_id.clone()),
};
bot.send_raw_message(&outbound.channel_id, &outbound)
.await?;
}
"level" => {
let crud_handler = crud_handler::CrudHandler::new(crate::db::sled_db::SledDB::new(
Path::new("daily_state.sled.db"),
)?);
let argus = &ast.arguments;
match argus.iter().next() {
Some(a) => match *a {
//TODO:完成设置用户等级的功能
_ => {}
},
None => {
let outbound = OutboundMessage {
channel_id: inbound.channel_id.clone(),
text:
"请提供选项,用户ID和等级参数,例如:!level set @123:matrix.org super"
.to_string(),
reply_to_event_id: Some(inbound.event_id.clone()),
};
bot.send_raw_message(&outbound.channel_id, &outbound)
.await?;
}
}
}
"list" => {
let crud_handler = crud_handler::CrudHandler::new(crate::db::sled_db::SledDB::new(
Path::new("daily_state.sled.db"),
)?);
let is_raw = ast.options.iter().any(|(k, _)| k == "raw");
let argus = &ast.arguments;
for arg in argus {
if arg == "all" {
let all_user_state = crud_handler.get_all_user_state().await?;
match is_raw {
true => {
let text = serde_json::to_string_pretty(&all_user_state)?;
let outbound = OutboundMessage {
channel_id: inbound.channel_id.clone(),
text,
reply_to_event_id: Some(inbound.event_id.clone()),
};
bot.send_raw_message(&outbound.channel_id, &outbound)
.await?;
}
false => {
let text = all_user_state
.into_iter()
.map(|(user_id, state)| {
format!("用户 {} 的签到状态: {:?}", user_id, state)
})
.collect::<Vec<String>>()
.join("\n");
let outbound = OutboundMessage {
channel_id: inbound.channel_id.clone(),
text,
reply_to_event_id: Some(inbound.event_id.clone()),
};
bot.send_raw_message(&outbound.channel_id, &outbound)
.await?;
}
}
break;
}
let user_id = arg.trim();
let is_checked = crud_handler.is_exist(user_id).await?;
let last_checkin_time = crud_handler.get_last_checkin_time(user_id).await?;
let outbound = match is_raw {
true => {
let db = crate::db::sled_db::SledDB::new(Path::new("daily_state.sled.db"))?;
let state = db
.get_raw(user_id.as_bytes())
.await?
.unwrap_or("空".as_bytes().to_vec());
let text = serde_json::to_string_pretty(&state)?;
OutboundMessage {
channel_id: inbound.channel_id.clone(),
text,
reply_to_event_id: Some(inbound.event_id.clone()),
}
}
false => {
let text = if is_checked {
format!(
"用户 {} 已签到过了,最后一次签到时间: {}",
user_id,
last_checkin_time
.map(|ts| {
let dt = chrono::DateTime::from_timestamp(
(ts / 1000) as i64,
((ts % 1000) * 1_000_000) as u32,
)?;
Some(dt.format("%Y-%m-%d %H:%M:%S").to_string())
})
.flatten()
.unwrap_or("未知".to_string())
)
} else {
format!("用户 {} 尚未签到过", user_id)
};
OutboundMessage {
channel_id: inbound.channel_id.clone(),
text,
reply_to_event_id: Some(inbound.event_id.clone()),
}
}
};
bot.send_raw_message(&outbound.channel_id, &outbound)
.await?;
}
}
"checkin" => { "checkin" => {
let crud_handler = crud_handler::CrudHandler::new(crate::db::sled_db::SledDB::new( let crud_handler = crud_handler::CrudHandler::new(crate::db::sled_db::SledDB::new(
Path::new("daily_state.sled.db"), Path::new("daily_state.sled.db"),
)?); )?);
let is_checked = crud_handler.is_exist(&inbound.user_id).await?;
match is_checked {
true => {
let outbound = OutboundMessage {
channel_id: inbound.channel_id.clone(),
text: format!("您已签到过了,请勿重复签到"),
reply_to_event_id: Some(inbound.event_id.clone()),
};
bot.send_raw_message(&outbound.channel_id, &outbound)
.await?;
return Ok(());
}
false => {
crud_handler.checkin(&inbound.user_id).await?; crud_handler.checkin(&inbound.user_id).await?;
let outbound = OutboundMessage { let outbound = OutboundMessage {
channel_id: inbound.channel_id.clone(), channel_id: inbound.channel_id.clone(),
@@ -132,8 +272,89 @@ async fn start_bot_command_processor(
bot.send_raw_message(&outbound.channel_id, &outbound) bot.send_raw_message(&outbound.channel_id, &outbound)
.await?; .await?;
} }
}
}
"test_report" => {} "test" => {
let test_project = &ast.arguments.iter().next();
match test_project {
None => {
let outbound = OutboundMessage {
channel_id: inbound.channel_id.clone(),
text: format!("请提供测试项目名称"),
reply_to_event_id: Some(inbound.event_id.clone()),
};
bot.send_raw_message(&outbound.channel_id, &outbound)
.await?;
return Ok(());
}
Some(test_project) => {
let test_project = test_project.trim().to_string();
log::info!(
"test command received: project={}, channel_id={}, event_id={}",
test_project,
inbound.channel_id,
inbound.event_id
);
let outbound = OutboundMessage {
channel_id: inbound.channel_id.clone(),
text: format!("测试项目: {}", test_project),
reply_to_event_id: Some(inbound.event_id.clone()),
};
bot.send_raw_message(&outbound.channel_id, &outbound)
.await?;
let outbound = OutboundMessage {
channel_id: inbound.channel_id.clone(),
text: format!("测试已开始"),
reply_to_event_id: Some(inbound.event_id.clone()),
};
bot.send_raw_message(&outbound.channel_id, &outbound)
.await?;
let result: Result<&str> = match test_project.as_str() {
"example" => Ok("测试通过"),
"daily_report" => {
log::info!(
"test project daily_report started (channel_id={}, event_id={})",
inbound.channel_id,
inbound.event_id
);
crate::bot::schedule::ScheduleHandler::daily_statistics_and_report_schedule(Arc::clone(bot)).await?;
log::info!(
"test project daily_report finished (channel_id={}, event_id={})",
inbound.channel_id,
inbound.event_id
);
Ok("日报测试通过")
}
_ => Err(anyhow!("未知测试项目")),
};
match result {
Ok(result_text) => {
let outbound = OutboundMessage {
channel_id: inbound.channel_id.clone(),
text: format!("测试结果: {}", result_text),
reply_to_event_id: Some(inbound.event_id.clone()),
};
bot.send_raw_message(&outbound.channel_id, &outbound)
.await?;
}
Err(err) => {
let outbound = OutboundMessage {
channel_id: inbound.channel_id.clone(),
text: format!("测试失败: {}", err),
reply_to_event_id: Some(inbound.event_id.clone()),
};
bot.send_raw_message(&outbound.channel_id, &outbound)
.await?;
}
}
}
}
}
_ => { _ => {
return Err(anyhow!("unknown command: {}", command)); return Err(anyhow!("unknown command: {}", command));
} }
@@ -178,11 +399,17 @@ impl AttendanceHandler for CommandHandler {
msg.text msg.text
); );
let Some(command_text) = text.strip_prefix('!') else { let Some(command_text) = text.strip_prefix('!') else {
log::debug!(
"ignore non-command matrix message (event_id={}, channel_id={}): {}",
msg.event_id,
msg.channel_id,
text
);
continue; continue;
}; };
if let Err(err) = if let Err(err) =
start_bot_command_processor(bot.as_ref(), &msg, command_text).await start_bot_command_processor(&bot, &msg, command_text).await
{ {
log::warn!( log::warn!(
"failed to process matrix command (event_id={}, channel_id={}): {}", "failed to process matrix command (event_id={}, channel_id={}): {}",
@@ -195,11 +422,17 @@ impl AttendanceHandler for CommandHandler {
MessageEnum::TelegramMessage(msg) => { MessageEnum::TelegramMessage(msg) => {
let text = msg.text.trim(); let text = msg.text.trim();
let Some(command_text) = text.strip_prefix('/') else { let Some(command_text) = text.strip_prefix('/') else {
log::debug!(
"ignore non-command telegram message (event_id={}, channel_id={}): {}",
msg.event_id,
msg.channel_id,
text
);
continue; continue;
}; };
if let Err(err) = if let Err(err) =
start_bot_command_processor(bot.as_ref(), &msg, command_text).await start_bot_command_processor(&bot, &msg, command_text).await
{ {
log::warn!( log::warn!(
"failed to process telegram command (event_id={}, channel_id={}): {}", "failed to process telegram command (event_id={}, channel_id={}): {}",
@@ -218,105 +451,4 @@ impl AttendanceHandler for CommandHandler {
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {}
use super::start_bot_command_processor;
use crate::bot::define::{Bot, InboundMessage, OutboundMessage};
use anyhow::{Ok, Result};
use async_trait::async_trait;
use std::sync::Mutex;
#[derive(Default)]
struct MockBot {
sent: Mutex<Vec<(String, OutboundMessage)>>,
}
impl MockBot {
fn sent_messages(&self) -> Vec<(String, OutboundMessage)> {
self.sent.lock().expect("mock sent lock poisoned").clone()
}
}
#[async_trait]
impl Bot for MockBot {
async fn start(&self) -> Result<()> {
Ok(())
}
async fn get_users_who_unchecked_for_long_time(
&self,
) -> Result<Vec<(String, Option<usize>)>> {
Ok(vec![("@user1:example.org".to_string(), Some(100))])
}
async fn join_rooms(&self) -> Result<()> {
Ok(())
}
async fn get_users_count(&self, _room_id: &str) -> Result<usize> {
return Ok(100);
}
async fn send_raw_message(
&self,
room_id: &str,
message: &OutboundMessage,
) -> Result<String> {
self.sent
.lock()
.expect("mock sent lock poisoned")
.push((room_id.to_string(), message.clone()));
Ok("mock_event_id".to_string())
}
}
fn make_inbound(text: &str) -> InboundMessage {
InboundMessage {
event_id: "$event_1".to_string(),
channel_id: "!room:example.org".to_string(),
user_id: "@alice:example.org".to_string(),
text: text.to_string(),
timestamp_ms: 1,
}
}
#[tokio::test]
async fn processor_ping_sends_pong_to_source_channel() {
let bot = MockBot::default();
let inbound = make_inbound("!ping");
let result = start_bot_command_processor(&bot, &inbound, "ping").await;
assert!(result.is_ok());
let sent = bot.sent_messages();
assert_eq!(sent.len(), 1);
assert_eq!(sent[0].0, "!room:example.org");
assert_eq!(sent[0].1.channel_id, "!room:example.org");
assert_eq!(sent[0].1.text, "pong");
assert_eq!(sent[0].1.reply_to_event_id.as_deref(), Some("$event_1"));
}
#[tokio::test]
async fn processor_echo_sends_joined_arguments_to_source_channel() {
let bot = MockBot::default();
let inbound = make_inbound("!echo hello world");
let result = start_bot_command_processor(&bot, &inbound, "echo hello world").await;
assert!(result.is_ok());
let sent = bot.sent_messages();
assert_eq!(sent.len(), 1);
assert_eq!(sent[0].1.text, "hello world");
assert_eq!(sent[0].1.channel_id, "!room:example.org");
assert_eq!(sent[0].1.reply_to_event_id.as_deref(), Some("$event_1"));
}
#[tokio::test]
async fn processor_unknown_command_returns_error_and_sends_nothing() {
let bot = MockBot::default();
let inbound = make_inbound("!doesnotexist");
let result = start_bot_command_processor(&bot, &inbound, "doesnotexist").await;
assert!(result.is_err());
assert_eq!(bot.sent_messages().len(), 0);
}
}
+4 -1
View File
@@ -174,9 +174,12 @@ impl Bot for MatrixBot {
let state = serde_json::from_slice::<UserState>(&state)?; let state = serde_json::from_slice::<UserState>(&state)?;
let checkin_ms = i64::try_from(state.checkin_unix_mills).unwrap_or(i64::MAX); let checkin_ms = i64::try_from(state.checkin_unix_mills).unwrap_or(i64::MAX);
let unchecked_ms = now.timestamp_millis().saturating_sub(checkin_ms); let unchecked_ms = now.timestamp_millis().saturating_sub(checkin_ms);
let unchecked_days = chrono::Duration::try_milliseconds(unchecked_ms) let current_ms = now.timestamp_millis();
let unchecked_days = chrono::Duration::try_milliseconds(current_ms - unchecked_ms)
.map(|d| d.num_days()) .map(|d| d.num_days())
.unwrap_or(0); .unwrap_or(0);
result.push((user_id, Some(unchecked_days as usize))); result.push((user_id, Some(unchecked_days as usize)));
} else { } else {
result.push((user_id, None)); result.push((user_id, None));
+32
View File
@@ -54,18 +54,26 @@ impl ScheduleHandler {
Ok(()) Ok(())
} }
pub async fn daily_statistics_and_report_schedule(bot: SharedBot) -> Result<()> { pub async fn daily_statistics_and_report_schedule(bot: SharedBot) -> Result<()> {
log::info!("[daily_report] start");
//获取和转换日期 //获取和转换日期
let date = chrono::Local::now() let date = chrono::Local::now()
.naive_local() .naive_local()
.date() .date()
.add(chrono::Duration::hours(8)); //调整时区为北京时间 .add(chrono::Duration::hours(8)); //调整时区为北京时间
let date = date.format("%Y年%-m月%-d日").to_string(); let date = date.format("%Y年%-m月%-d日").to_string();
log::info!("[daily_report] date_resolved: {}", date);
//获取签到人数 //获取签到人数
let db_path = std::path::Path::new("daily_state.sled.db"); let db_path = std::path::Path::new("daily_state.sled.db");
log::info!("[daily_report] open_db: {}", db_path.display());
let db = db::crud_handler::CrudHandler::new( let db = db::crud_handler::CrudHandler::new(
db::sled_db::SledDB::new(db_path).expect("无法获取数据库实例"), db::sled_db::SledDB::new(db_path).expect("无法获取数据库实例"),
); );
log::info!("[daily_report] load_all_user_state: begin");
let states = db.get_all_user_state().await?; let states = db.get_all_user_state().await?;
log::info!(
"[daily_report] load_all_user_state: done, state_count={}",
states.len()
);
let checked_nums = states.len(); let checked_nums = states.len();
let config = Config::get_all().clone(); let config = Config::get_all().clone();
@@ -79,11 +87,26 @@ impl ScheduleHandler {
.next() .next()
.expect("应该有一个主房间,但是配置文件未提供") .expect("应该有一个主房间,但是配置文件未提供")
.clone(); .clone();
log::info!(
"[daily_report] get_users_count: begin, room_id={}",
main_room_id.room_id
);
let all_user_nums = bot.get_users_count(main_room_id.room_id.as_str()).await?; let all_user_nums = bot.get_users_count(main_room_id.room_id.as_str()).await?;
log::info!(
"[daily_report] get_users_count: done, all_user_nums={}",
all_user_nums
);
let unchecked_nums = all_user_nums - checked_nums; let unchecked_nums = all_user_nums - checked_nums;
let checkin_rate = (checked_nums as f64 / all_user_nums as f64 * 100.0).round() as u32; let checkin_rate = (checked_nums as f64 / all_user_nums as f64 * 100.0).round() as u32;
log::info!("[daily_report] get_users_who_unchecked_for_long_time: begin");
let users_table = bot.get_users_who_unchecked_for_long_time().await?; let users_table = bot.get_users_who_unchecked_for_long_time().await?;
log::info!(
"[daily_report] get_users_who_unchecked_for_long_time: done, row_count={},user_table={:#?}",
&users_table.len(),
&users_table
);
log::info!("[daily_report] reload_all_user_state_for_today_unchecked: begin");
let today_unchecked_users = db let today_unchecked_users = db
.get_all_user_state() .get_all_user_state()
.await? .await?
@@ -92,6 +115,7 @@ impl ScheduleHandler {
.map(|(user_id, _)| user_id) .map(|(user_id, _)| user_id)
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(" ,\n"); .join(" ,\n");
log::info!("[daily_report] reload_all_user_state_for_today_unchecked: done");
let above_7days_unchecked_users = users_table let above_7days_unchecked_users = users_table
.iter() .iter()
.filter(|(_, unchecked_days)| { .filter(|(_, unchecked_days)| {
@@ -161,6 +185,10 @@ impl ScheduleHandler {
"# "#
); //每日统计报告 ); //每日统计报告
log::info!(
"[daily_report] send_raw_message: begin, room_id={}",
main_room_id.room_id
);
bot.send_raw_message( bot.send_raw_message(
main_room_id.room_id.as_str(), main_room_id.room_id.as_str(),
&OutboundMessage { &OutboundMessage {
@@ -170,7 +198,11 @@ impl ScheduleHandler {
}, },
) )
.await?; .await?;
log::info!("[daily_report] send_raw_message: done");
log::info!("[daily_report] reset_all_user_daily_state: begin");
db.reset_all_user_daily_state().await?; //重置每日签到状态 db.reset_all_user_daily_state().await?; //重置每日签到状态
log::info!("[daily_report] reset_all_user_daily_state: done");
log::info!("[daily_report] finished");
Ok(()) Ok(())
} }
+81 -1
View File
@@ -1,5 +1,6 @@
use crate::db::{self, define::StorageEngine}; use crate::db::{self, define::StorageEngine};
use anyhow::Result; use anyhow::{Ok, Result, anyhow};
use chrono::naive::serde;
pub struct CrudHandler<T: StorageEngine> { pub struct CrudHandler<T: StorageEngine> {
pub engine: T, pub engine: T,
} }
@@ -19,6 +20,64 @@ impl<T: StorageEngine> CrudHandler<T> {
Ok(()) Ok(())
} }
//需要保证user_id存在,否则会panic
pub async fn raise_level(&self, user_id: &str) -> Result<()> {
let key = user_id.as_bytes();
let value_bytes = self
.engine
.get_raw(key)
.await?
.ok_or_else(|| anyhow!("用户不存在"))?;
let mut value = serde_json::from_slice::<db::user_state::UserState>(&value_bytes)?;
match value.level {
db::user_state::UserLevel::Super => {}
db::user_state::UserLevel::Bronze => value.level = db::user_state::UserLevel::Silver,
db::user_state::UserLevel::Silver => value.level = db::user_state::UserLevel::Gold,
db::user_state::UserLevel::Gold => value.level = db::user_state::UserLevel::Platinum,
db::user_state::UserLevel::Platinum => value.level = db::user_state::UserLevel::Diamond,
db::user_state::UserLevel::Diamond => {}
}
let new_value_bytes = serde_json::to_vec(&value)?;
self.engine.set_raw(key, &new_value_bytes).await?;
Ok(())
}
pub async fn set_user_level(
&self,
user_id: &str,
level: db::user_state::UserLevel,
) -> Result<()> {
let key = user_id.as_bytes();
let mut value = db::user_state::UserState::new();
value.level = level;
let value_bytes = serde_json::to_vec(&value)?;
self.engine.set_raw(key, &value_bytes).await?;
Ok(())
}
pub async fn give_super(&self, user_id: &str) -> Result<()> {
let key = user_id.as_bytes();
let mut value = db::user_state::UserState::new();
value.level = db::user_state::UserLevel::Super;
let value_bytes = serde_json::to_vec(&value)?;
self.engine.set_raw(key, &value_bytes).await?;
Ok(())
}
pub async fn clean_user_level(&self, user_id: &str) -> Result<()> {
let key = user_id.as_bytes();
let mut value = db::user_state::UserState::new();
value.level = db::user_state::UserLevel::Bronze;
let value_bytes = serde_json::to_vec(&value)?;
self.engine.set_raw(key, &value_bytes).await?;
Ok(())
}
pub async fn reset_all_user_daily_state(&self) -> Result<()> { pub async fn reset_all_user_daily_state(&self) -> Result<()> {
let mut keys = self.engine.get_all_keys().await?; let mut keys = self.engine.get_all_keys().await?;
for key in keys.drain(..) { for key in keys.drain(..) {
@@ -44,6 +103,27 @@ impl<T: StorageEngine> CrudHandler<T> {
Ok(result) Ok(result)
} }
pub async fn is_exist(&self, user_id: &str) -> Result<bool> {
let re = self.engine.get_raw(user_id.as_bytes()).await?;
match re {
Some(user) => {
let user = serde_json::from_slice::<db::user_state::UserState>(&user)?;
match user.is_checkin_today {
true => {
return Ok(true);
}
false => {
return Ok(false);
}
}
}
None => {
return Ok(false);
}
}
}
pub async fn get_last_checkin_time(&self, user_id: &str) -> Result<Option<u64>> { pub async fn get_last_checkin_time(&self, user_id: &str) -> Result<Option<u64>> {
let key = user_id.as_bytes(); let key = user_id.as_bytes();
if let Some(value_bytes) = self.engine.get_raw(key).await? { if let Some(value_bytes) = self.engine.get_raw(key).await? {
+1 -1
View File
@@ -27,7 +27,7 @@ pub struct SledDB {
impl SledDB { impl SledDB {
pub fn new(path: &Path) -> Result<Self> { pub fn new(path: &Path) -> Result<Self> {
let db = sled::open(path)?; let db = get_sled_db(path)?;
Ok(Self { sled_db: db }) Ok(Self { sled_db: db })
} }
+1 -1
View File
@@ -45,7 +45,7 @@ impl UserState {
pub fn checkin(&mut self) { pub fn checkin(&mut self) {
self.is_checkin_today = true; self.is_checkin_today = true;
let unix_time = tokio::time::Instant::now().elapsed().as_millis() as u64; let unix_time = chrono::Utc::now().timestamp_millis() as u64;
self.checkin_unix_mills = unix_time; self.checkin_unix_mills = unix_time;
self.checkin_times_in_month += 1; self.checkin_times_in_month += 1;