修改了部分bot代码,增加了super过滤器,修改了md文档
This commit is contained in:
1 parent
99869ac3ad
commit
39645baed4
12 files changed
+180
-18
No files matched your search
@@ -12,4 +12,6 @@
|
|||||||
- [x] 实现基础Sled DB的签到信息记录功能
|
- [x] 实现基础Sled DB的签到信息记录功能
|
||||||
- [x] 实现matrix机器人收发
|
- [x] 实现matrix机器人收发
|
||||||
- [x] 实现每日签到统计
|
- [x] 实现每日签到统计
|
||||||
|
- [ ] 实现level自动调整
|
||||||
|
- [ ] 实现低level自动踢出(每月签到次数低于7次,且level为铜)
|
||||||
- [ ] 实现每月签到统计
|
- [ ] 实现每月签到统计
|
||||||
Binary file not shown.
Binary file not shown.
+63
-2
@@ -3,6 +3,7 @@ use crate::bot::define::{AttendanceHandler, Bot, InboundMessage, MessageEnum, Ou
|
|||||||
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 crate::db::define::StorageEngine;
|
||||||
|
use crate::db::user_state::{UserLevel, UserState};
|
||||||
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;
|
||||||
@@ -140,8 +141,68 @@ async fn start_bot_command_processor(
|
|||||||
|
|
||||||
let argus = &ast.arguments;
|
let argus = &ast.arguments;
|
||||||
match argus.iter().next() {
|
match argus.iter().next() {
|
||||||
Some(a) => match *a {
|
Some(a) => match a.as_str() {
|
||||||
//TODO:完成设置用户等级的功能
|
"set" => {
|
||||||
|
let user_id = argus.iter().nth(1).ok_or_else(|| {
|
||||||
|
anyhow!("请提供用户ID参数,例如:!level set @123:matrix.org super")
|
||||||
|
})?;
|
||||||
|
let level = argus.iter().nth(2).ok_or_else(|| {
|
||||||
|
anyhow!("请提供等级参数,例如:!level set @123:matrix.org super")
|
||||||
|
})?;
|
||||||
|
crud_handler
|
||||||
|
.set_user_level(
|
||||||
|
user_id,
|
||||||
|
UserLevel::from_str(level)
|
||||||
|
.ok_or_else(|| anyhow!("无效的等级参数"))?,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let outbound = OutboundMessage {
|
||||||
|
channel_id: inbound.channel_id.clone(),
|
||||||
|
text: format!("已设置用户 {} 的等级为 {}", user_id, level),
|
||||||
|
reply_to_event_id: Some(inbound.event_id.clone()),
|
||||||
|
};
|
||||||
|
bot.send_raw_message(&outbound.channel_id, &outbound)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
"raise" => {
|
||||||
|
let user_id = argus.iter().nth(1).ok_or_else(|| {
|
||||||
|
anyhow!("请提供用户ID参数,例如:!level raise @123:matrix.org")
|
||||||
|
})?;
|
||||||
|
crud_handler.raise_level(user_id).await?;
|
||||||
|
let outbound = OutboundMessage {
|
||||||
|
channel_id: inbound.channel_id.clone(),
|
||||||
|
text: format!("已提升用户 {} 的等级", user_id),
|
||||||
|
reply_to_event_id: Some(inbound.event_id.clone()),
|
||||||
|
};
|
||||||
|
bot.send_raw_message(&outbound.channel_id, &outbound)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
"super" => {
|
||||||
|
let user_id = argus.iter().nth(1).ok_or_else(|| {
|
||||||
|
anyhow!("请提供用户ID参数,例如:!level super @123:matrix.org")
|
||||||
|
})?;
|
||||||
|
crud_handler.give_super(user_id).await?;
|
||||||
|
let outbound = OutboundMessage {
|
||||||
|
channel_id: inbound.channel_id.clone(),
|
||||||
|
text: format!("已赋予用户 {} 超级权限", user_id),
|
||||||
|
reply_to_event_id: Some(inbound.event_id.clone()),
|
||||||
|
};
|
||||||
|
bot.send_raw_message(&outbound.channel_id, &outbound)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
"clear" => {
|
||||||
|
let user_id = argus.iter().nth(1).ok_or_else(|| {
|
||||||
|
anyhow!("请提供用户ID参数,例如:!level clear @123:matrix.org")
|
||||||
|
})?;
|
||||||
|
crud_handler.clean_user_level(user_id).await?;
|
||||||
|
let outbound = OutboundMessage {
|
||||||
|
channel_id: inbound.channel_id.clone(),
|
||||||
|
text: format!("已清除用户 {} 的等级为默认等级", user_id),
|
||||||
|
reply_to_event_id: Some(inbound.event_id.clone()),
|
||||||
|
};
|
||||||
|
bot.send_raw_message(&outbound.channel_id, &outbound)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
},
|
},
|
||||||
None => {
|
None => {
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
// filters: Option<Vec<Box<dyn Fn(&MessageEnum) -> MessageEnum + Send + Sync>>>,
|
// filters: Option<Vec<Box<dyn Fn(&MessageEnum) -> MessageEnum + Send + Sync>>>,
|
||||||
use crate::bot::define::InboundMessage;
|
use crate::bot::define::InboundMessage;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//支持中文指令
|
//支持中文指令
|
||||||
pub fn support_chinese_command(msg: &InboundMessage) -> InboundMessage {
|
pub fn support_chinese_command(msg: &InboundMessage) -> InboundMessage {
|
||||||
//支持中文指令的简单实现,可以根据需要扩展
|
//支持中文指令的简单实现,可以根据需要扩展
|
||||||
@@ -18,3 +20,7 @@ pub fn support_chinese_command(msg: &InboundMessage) -> InboundMessage {
|
|||||||
//pub fn support_chinese_command(msg: &InboundMessage) -> InboundMessage {
|
//pub fn support_chinese_command(msg: &InboundMessage) -> InboundMessage {
|
||||||
// unimplemented!()
|
// unimplemented!()
|
||||||
//}
|
//}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
+37
-5
@@ -1,10 +1,12 @@
|
|||||||
use anyhow::{Result, anyhow};
|
use anyhow::{Result, anyhow};
|
||||||
use matrix_sdk::{
|
use matrix_sdk::{
|
||||||
Client, Room,
|
Client, Room,
|
||||||
config::SyncSettings,
|
config::{self, SyncSettings},
|
||||||
ruma::{
|
ruma::{
|
||||||
OwnedUserId, RoomId, UserId,
|
OwnedUserId, RoomId, UserId,
|
||||||
events::room::message::{MessageType, OriginalSyncRoomMessageEvent},
|
events::room::message::{
|
||||||
|
MessageType, OriginalSyncRoomMessageEvent, RoomMessageEventContent,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use std::{sync::Arc, time::Duration};
|
use std::{sync::Arc, time::Duration};
|
||||||
@@ -12,7 +14,7 @@ use std::{sync::Arc, time::Duration};
|
|||||||
use crate::{
|
use crate::{
|
||||||
bot::{bot_handler::ChannelManager, define::Bot},
|
bot::{bot_handler::ChannelManager, define::Bot},
|
||||||
config::{Config, RoomType},
|
config::{Config, RoomType},
|
||||||
db::{define::StorageEngine, user_state::UserState},
|
db::{define::StorageEngine, filter::super_filter, user_state::UserState},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -112,11 +114,34 @@ impl Bot for MatrixBot {
|
|||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| anyhow!("Matrix 登录重试失败: {}", e))?;
|
.map_err(|e| anyhow!("Matrix 登录重试失败: {}", e))?;
|
||||||
tokio::spawn(async move {});
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
async fn join_rooms(&self) -> Result<()> {
|
async fn join_rooms(&self) -> Result<()> {
|
||||||
for _room in &self.config.rooms {}
|
let config = Config::get_all();
|
||||||
|
let client = Arc::clone(&self.client);
|
||||||
|
let mut rooms = client.joined_rooms();
|
||||||
|
let room = client
|
||||||
|
.join_room_by_id(
|
||||||
|
config
|
||||||
|
.matrix
|
||||||
|
.clone()
|
||||||
|
.unwrap()
|
||||||
|
.rooms
|
||||||
|
.get(0)
|
||||||
|
.unwrap()
|
||||||
|
.room_id
|
||||||
|
.as_ref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
rooms.push(room);
|
||||||
|
for room in &rooms {
|
||||||
|
let content = RoomMessageEventContent::text_plain("机器人已启动".to_string());
|
||||||
|
tokio::time::timeout(Duration::from_secs(20), room.send(content))
|
||||||
|
.await
|
||||||
|
.expect("room.send() 超时,可能卡在 Matrix 发送请求")
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
async fn send_raw_message(
|
async fn send_raw_message(
|
||||||
@@ -172,6 +197,13 @@ impl Bot for MatrixBot {
|
|||||||
let user_id = user.to_string();
|
let user_id = user.to_string();
|
||||||
if let Some(state) = db.get_raw(&user_id.as_bytes()).await? {
|
if let Some(state) = db.get_raw(&user_id.as_bytes()).await? {
|
||||||
let state = serde_json::from_slice::<UserState>(&state)?;
|
let state = serde_json::from_slice::<UserState>(&state)?;
|
||||||
|
if state.is_checkin_today {
|
||||||
|
continue; // 已经签到的用户不算未签到
|
||||||
|
}
|
||||||
|
|
||||||
|
if super_filter(&state) {
|
||||||
|
continue; // 根据过滤条件过滤用户
|
||||||
|
}
|
||||||
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 current_ms = now.timestamp_millis();
|
let current_ms = now.timestamp_millis();
|
||||||
|
|||||||
@@ -70,6 +70,10 @@ impl ScheduleHandler {
|
|||||||
);
|
);
|
||||||
log::info!("[daily_report] load_all_user_state: begin");
|
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?;
|
||||||
|
let states = states
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, state)| !crate::db::filter::super_filter(state))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
log::info!(
|
log::info!(
|
||||||
"[daily_report] load_all_user_state: done, state_count={}",
|
"[daily_report] load_all_user_state: done, state_count={}",
|
||||||
states.len()
|
states.len()
|
||||||
@@ -112,6 +116,7 @@ impl ScheduleHandler {
|
|||||||
.await?
|
.await?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|(_, state)| !state.is_checkin_today)
|
.filter(|(_, state)| !state.is_checkin_today)
|
||||||
|
.filter(|(_, state)| !crate::db::filter::super_filter(state))
|
||||||
.map(|(user_id, _)| user_id)
|
.map(|(user_id, _)| user_id)
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join(" ,\n");
|
.join(" ,\n");
|
||||||
|
|||||||
+20
-5
@@ -1,6 +1,5 @@
|
|||||||
use crate::db::{self, define::StorageEngine};
|
use crate::db::{self, define::StorageEngine};
|
||||||
use anyhow::{Ok, Result, anyhow};
|
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,
|
||||||
}
|
}
|
||||||
@@ -12,7 +11,11 @@ impl<T: StorageEngine> CrudHandler<T> {
|
|||||||
|
|
||||||
pub async fn checkin(&self, user_id: &str) -> Result<()> {
|
pub async fn checkin(&self, user_id: &str) -> Result<()> {
|
||||||
let key = user_id.as_bytes();
|
let key = user_id.as_bytes();
|
||||||
let mut value = db::user_state::UserState::new();
|
let mut value = if let Some(value_bytes) = self.engine.get_raw(key).await? {
|
||||||
|
serde_json::from_slice::<db::user_state::UserState>(&value_bytes)?
|
||||||
|
} else {
|
||||||
|
db::user_state::UserState::new()
|
||||||
|
};
|
||||||
value.checkin();
|
value.checkin();
|
||||||
let value_bytes = serde_json::to_vec(&value)?;
|
let value_bytes = serde_json::to_vec(&value)?;
|
||||||
|
|
||||||
@@ -50,7 +53,11 @@ impl<T: StorageEngine> CrudHandler<T> {
|
|||||||
level: db::user_state::UserLevel,
|
level: db::user_state::UserLevel,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let key = user_id.as_bytes();
|
let key = user_id.as_bytes();
|
||||||
let mut value = db::user_state::UserState::new();
|
let mut value = if let Some(value_bytes) = self.engine.get_raw(key).await? {
|
||||||
|
serde_json::from_slice::<db::user_state::UserState>(&value_bytes)?
|
||||||
|
} else {
|
||||||
|
db::user_state::UserState::new()
|
||||||
|
};
|
||||||
value.level = level;
|
value.level = level;
|
||||||
let value_bytes = serde_json::to_vec(&value)?;
|
let value_bytes = serde_json::to_vec(&value)?;
|
||||||
|
|
||||||
@@ -60,7 +67,11 @@ impl<T: StorageEngine> CrudHandler<T> {
|
|||||||
|
|
||||||
pub async fn give_super(&self, user_id: &str) -> Result<()> {
|
pub async fn give_super(&self, user_id: &str) -> Result<()> {
|
||||||
let key = user_id.as_bytes();
|
let key = user_id.as_bytes();
|
||||||
let mut value = db::user_state::UserState::new();
|
let mut value = if let Some(value_bytes) = self.engine.get_raw(key).await? {
|
||||||
|
serde_json::from_slice::<db::user_state::UserState>(&value_bytes)?
|
||||||
|
} else {
|
||||||
|
db::user_state::UserState::new()
|
||||||
|
};
|
||||||
value.level = db::user_state::UserLevel::Super;
|
value.level = db::user_state::UserLevel::Super;
|
||||||
let value_bytes = serde_json::to_vec(&value)?;
|
let value_bytes = serde_json::to_vec(&value)?;
|
||||||
|
|
||||||
@@ -70,7 +81,11 @@ impl<T: StorageEngine> CrudHandler<T> {
|
|||||||
|
|
||||||
pub async fn clean_user_level(&self, user_id: &str) -> Result<()> {
|
pub async fn clean_user_level(&self, user_id: &str) -> Result<()> {
|
||||||
let key = user_id.as_bytes();
|
let key = user_id.as_bytes();
|
||||||
let mut value = db::user_state::UserState::new();
|
let mut value = if let Some(value_bytes) = self.engine.get_raw(key).await? {
|
||||||
|
serde_json::from_slice::<db::user_state::UserState>(&value_bytes)?
|
||||||
|
} else {
|
||||||
|
db::user_state::UserState::new()
|
||||||
|
};
|
||||||
value.level = db::user_state::UserLevel::Bronze;
|
value.level = db::user_state::UserLevel::Bronze;
|
||||||
let value_bytes = serde_json::to_vec(&value)?;
|
let value_bytes = serde_json::to_vec(&value)?;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
use crate::db::user_state::UserState;
|
||||||
|
|
||||||
|
//fn temple_filter(state: UserState) -> bool {}
|
||||||
|
|
||||||
|
// 过滤掉超级用户,其他用户都不过滤
|
||||||
|
pub fn super_filter(state: &UserState) -> bool {
|
||||||
|
if state.level == crate::db::user_state::UserLevel::Super {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
pub mod crud_handler;
|
pub mod crud_handler;
|
||||||
pub mod define;
|
pub mod define;
|
||||||
|
pub mod filter;
|
||||||
pub mod sled_db;
|
pub mod sled_db;
|
||||||
pub mod user_state;
|
pub mod user_state;
|
||||||
+34
-6
@@ -21,7 +21,7 @@ pub enum UserLevel {
|
|||||||
}
|
}
|
||||||
impl Default for UserLevel {
|
impl Default for UserLevel {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
UserLevel::Bronze
|
UserLevel::Silver
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,6 +32,31 @@ value:UserState的json字符串
|
|||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
impl UserLevel {
|
||||||
|
pub fn to_str(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
UserLevel::Super => "Super",
|
||||||
|
UserLevel::Bronze => "Bronze",
|
||||||
|
UserLevel::Silver => "Silver",
|
||||||
|
UserLevel::Gold => "Gold",
|
||||||
|
UserLevel::Platinum => "Platinum",
|
||||||
|
UserLevel::Diamond => "Diamond",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_str(s: &str) -> Option<Self> {
|
||||||
|
match s {
|
||||||
|
"Super" => Some(UserLevel::Super),
|
||||||
|
"Bronze" => Some(UserLevel::Bronze),
|
||||||
|
"Silver" => Some(UserLevel::Silver),
|
||||||
|
"Gold" => Some(UserLevel::Gold),
|
||||||
|
"Platinum" => Some(UserLevel::Platinum),
|
||||||
|
"Diamond" => Some(UserLevel::Diamond),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl UserState {
|
impl UserState {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -39,7 +64,7 @@ impl UserState {
|
|||||||
checkin_unix_mills: 0 as u64,
|
checkin_unix_mills: 0 as u64,
|
||||||
checkin_times_in_month: 0,
|
checkin_times_in_month: 0,
|
||||||
checkin_days: Vec::new(),
|
checkin_days: Vec::new(),
|
||||||
level: UserLevel::Bronze,
|
level: UserLevel::Silver,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,11 +78,14 @@ impl UserState {
|
|||||||
if !self.checkin_days.contains(&day) {
|
if !self.checkin_days.contains(&day) {
|
||||||
self.checkin_days.push(day);
|
self.checkin_days.push(day);
|
||||||
}
|
}
|
||||||
|
if self.level == UserLevel::Super {
|
||||||
|
return;
|
||||||
|
}
|
||||||
match self.checkin_times_in_month {
|
match self.checkin_times_in_month {
|
||||||
0..=14 => self.level = UserLevel::Bronze,
|
0..=7 => self.level = UserLevel::Bronze,
|
||||||
15..=30 => self.level = UserLevel::Silver,
|
8..=14 => self.level = UserLevel::Silver,
|
||||||
31..=45 => self.level = UserLevel::Gold,
|
15..=29 => self.level = UserLevel::Gold,
|
||||||
46..=60 => self.level = UserLevel::Platinum,
|
30..=44 => self.level = UserLevel::Platinum,
|
||||||
_ => self.level = UserLevel::Diamond,
|
_ => self.level = UserLevel::Diamond,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
schedule_handler
|
schedule_handler
|
||||||
.add_daily_statistics_and_report_schedule(bot_clone, "* * 3 * * *")
|
.add_daily_statistics_and_report_schedule(bot_clone, "* * 3 * * *")
|
||||||
.await?;
|
.await?;
|
||||||
|
log::info!("Bot is running. Press Ctrl+C to stop.");
|
||||||
tokio::signal::ctrl_c().await?; // 等待 Ctrl+C 信号以优雅地关闭应用程序。
|
tokio::signal::ctrl_c().await?; // 等待 Ctrl+C 信号以优雅地关闭应用程序。
|
||||||
|
|
||||||
let stop_tx = CommandHandler::global_sender();
|
let stop_tx = CommandHandler::global_sender();
|
||||||
|
|||||||
Reference in new issue
Block a user