修改了部分bot代码

This commit is contained in:
:NoBody: committed 2026-03-26 20:33:08 +08:00
1 parent 821168a770
commit bbbdd9eac5
10 files changed
+162 -17

No files matched your search

+1 -1
View File
@@ -1 +1 @@
flake-profile-1-link
flake-profile-2-link
-1
View File
@@ -1 +0,0 @@
/nix/store/8l5iic7kj6fjdgzip9p55h65j9n1yq87-nix-shell-env
+1
View File
@@ -0,0 +1 @@
/nix/store/v6n6l504w5s0c6cks1ip7kl7lzn1z1wy-nix-shell-env
Generated
+34 -1
View File
@@ -642,12 +642,14 @@ dependencies = [
"anyhow",
"async-trait",
"env_logger",
"log",
"matrix-sdk",
"reqwest 0.13.2",
"serde",
"sled",
"thiserror 2.0.18",
"tokio",
"tokio-retry",
"toml 1.0.7+spec-1.1.0",
]
@@ -2471,6 +2473,26 @@ dependencies = [
"siphasher",
]
[[package]]
name = "pin-project"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1749c7ed4bcaf4c3d0a3efc28538844fb29bcdd7d2b67b2be7e20ba861ff517"
dependencies = [
"pin-project-internal",
]
[[package]]
name = "pin-project-internal"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b20ed30f105399776b9c883e68e536ef602a16ae6f596d2c473591d6ad64c6"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@@ -3670,7 +3692,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.2",
"once_cell",
"rustix",
"windows-sys 0.61.2",
@@ -3820,6 +3842,17 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "tokio-retry"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f57eb36ecbe0fc510036adff84824dd3c24bb781e21bfa67b69d556aa85214f"
dependencies = [
"pin-project",
"rand 0.8.5",
"tokio",
]
[[package]]
name = "tokio-rustls"
version = "0.26.4"
+2
View File
@@ -7,11 +7,13 @@ edition = "2024"
anyhow = "1.0.102"
async-trait = "0.1.89"
env_logger = "0.11.9"
log = "0.4.29"
reqwest = "0.13.2"
serde = {version="1.0.228",features=["derive"]}
sled = "0.34.7"
thiserror = "2.0.18"
tokio = {version="1.50.0",features=["full"]}
tokio-retry = "0.3.0"
toml = "1.0.7"
[dependencies.matrix-sdk]
+21 -4
View File
@@ -5,16 +5,33 @@
utils.url = "github:numtide/flake-utils";
};
outputs = { self, nixpkgs, utils, naersk }:
utils.lib.eachDefaultSystem (system:
outputs =
{
self,
nixpkgs,
utils,
naersk,
}:
utils.lib.eachDefaultSystem (
system:
let
pkgs = import nixpkgs { inherit system; };
naersk-lib = pkgs.callPackage naersk { };
in
{
defaultPackage = naersk-lib.buildPackage ./.;
devShell = with pkgs; mkShell {
buildInputs = [ cargo rustc rustfmt pre-commit rustPackages.clippy ];
devShell =
with pkgs;
mkShell {
buildInputs = [
cargo
rustc
rustfmt
pre-commit
rustPackages.clippy
pkg-config
sqlite
];
RUST_SRC_PATH = rustPlatform.rustLibSrc;
};
}
+29 -4
View File
@@ -1,4 +1,5 @@
use crate::bot::define::{AttendanceBot, MessageEnum};
use crate::bot::command_parser::parse_command;
use crate::bot::define::{AttendanceHandler, MessageEnum};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use std::sync::{Mutex, OnceLock};
@@ -17,9 +18,9 @@ fn global_channel() -> &'static (MessageTx, Mutex<Option<MessageRx>>) {
})
}
pub struct Bot;
pub struct CommandHandler;
impl Bot {
impl CommandHandler {
pub fn new() -> Self {
Self
}
@@ -29,8 +30,32 @@ impl Bot {
}
}
async fn bot_command_processor(command: AsRef<str>) -> Result<()> {
let command = command.as_ref();
let ast = parse_command(command)?;
let command = ast.command.as_str();
match command {
"!echo" => {}
_ => {
return Err(anyhow!("unknown command: {}", command));
}
}
let arguments = ast.arguments;
let options = ast.options;
for argument in arguments {
log::trace!("Argument: {}", argument);
}
for (k, v) in options {
log::trace!("Option: {}={}", k, v);
}
Ok(())
}
#[async_trait]
impl AttendanceBot for Bot {
impl AttendanceHandler for CommandHandler {
async fn handle_commands(&self) -> Result<JoinHandle<()>> {
let rx = {
let (_tx, rx_slot) = global_channel();
+7 -2
View File
@@ -1,8 +1,9 @@
use std::{sync::OnceLock, time::Duration};
use tokio::task::JoinHandle;
use anyhow::Result;
use async_trait::async_trait;
#[async_trait]
pub trait Sender {
async fn send(&self, message: OutboundMessage) -> Result<String>;
@@ -36,7 +37,7 @@ pub struct InputBatch {
}
#[async_trait]
pub trait AttendanceBot {
pub trait AttendanceHandler {
async fn handle_commands(&self) -> Result<JoinHandle<()>>;
}
@@ -45,3 +46,7 @@ pub enum MessageEnum {
TelegramMessage(InboundMessage),
StopMessage,
}
#[async_trait]
pub trait Bot {
async fn start(&self) -> Result<()>;
}
+65 -2
View File
@@ -1,3 +1,66 @@
struct MatrixBot {}
use std::{sync::Arc, time::Duration};
impl MatrixBot {}
use matrix_sdk::{
Client,
config::SyncSettings,
ruma::{OwnedUserId, UserId, events::room::message::SyncRoomMessageEvent, user_id},
};
use crate::bot::define::Bot;
struct MatrixBot {
client: Arc<Client>,
user_id: OwnedUserId,
password: String,
}
impl MatrixBot {
pub async fn new(user_id: &str, password: &str) -> Self {
let user_id = UserId::parse(user_id).expect("用户ID不合法");
Self {
client: Arc::new(
Client::builder()
.server_name(user_id.server_name())
.build()
.await
.expect("创建Matrix客户端失败"),
),
user_id: user_id.to_owned(),
password: password.to_string(),
}
}
}
#[async_trait::async_trait]
impl Bot for MatrixBot {
async fn start(&self) -> anyhow::Result<()> {
let client = Arc::clone(&self.client);
log::info!("Matrix 机器人已启动 {}", self.user_id);
tokio::spawn(tokio_retry::Retry::spawn(
tokio_retry::strategy::FibonacciBackoff::from_millis(100)
.max_delay(Duration::from_secs(120)),
move || {
let client = Arc::clone(&client);
async move { client.sync(SyncSettings::default()).await }
},
));
log::info!("Matrix 机器人已登陆 {}", self.user_id);
dbg!("Matrix 机器人已登陆 {}", &self.user_id);
Ok(())
}
}
mod tests {
use super::*;
#[tokio::test]
async fn test_matrix_bot() {
let userid_str = std::env::var("MATRIX_USER").expect("请设置环境变量 MATRIX_USER");
let userid = UserId::parse(&userid_str).expect("用户ID不合法");
let password = std::env::var("MATRIX_PASSWORD").expect("请设置环境变量 MATRIX_PASSWORD");
let bot = MatrixBot::new(userid.as_ref(), &password).await;
bot.start().await.unwrap();
tokio::signal::ctrl_c().await.unwrap();
}
}
+2 -2
View File
@@ -2,7 +2,7 @@ use anyhow::Ok;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
daily_bot::init::init().await?;
daily_bot::init::init().await?; //执行初始化逻辑,主要是加载配置文件,创建数据库连接池等。
tokio::signal::ctrl_c().await?; //等待Ctrl+C信号以优雅地关闭应用程序。
Ok(())
}