diff --git a/.direnv/flake-profile b/.direnv/flake-profile index 0c05709..c7ae5b7 120000 --- a/.direnv/flake-profile +++ b/.direnv/flake-profile @@ -1 +1 @@ -flake-profile-1-link \ No newline at end of file +flake-profile-2-link \ No newline at end of file diff --git a/.direnv/flake-profile-1-link b/.direnv/flake-profile-1-link deleted file mode 120000 index 5cb044b..0000000 --- a/.direnv/flake-profile-1-link +++ /dev/null @@ -1 +0,0 @@ -/nix/store/8l5iic7kj6fjdgzip9p55h65j9n1yq87-nix-shell-env \ No newline at end of file diff --git a/.direnv/flake-profile-2-link b/.direnv/flake-profile-2-link new file mode 120000 index 0000000..b35761f --- /dev/null +++ b/.direnv/flake-profile-2-link @@ -0,0 +1 @@ +/nix/store/v6n6l504w5s0c6cks1ip7kl7lzn1z1wy-nix-shell-env \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 830c6dc..ad9faf4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index 70c4ddb..d93bbb9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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] diff --git a/flake.nix b/flake.nix index 680de52..eb3f389 100644 --- a/flake.nix +++ b/flake.nix @@ -5,18 +5,35 @@ 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 ]; - RUST_SRC_PATH = rustPlatform.rustLibSrc; - }; + devShell = + with pkgs; + mkShell { + buildInputs = [ + cargo + rustc + rustfmt + pre-commit + rustPackages.clippy + pkg-config + sqlite + ]; + RUST_SRC_PATH = rustPlatform.rustLibSrc; + }; } ); } diff --git a/src/bot/bot_handler.rs b/src/bot/bot_handler.rs index 5265c61..ca85d9d 100644 --- a/src/bot/bot_handler.rs +++ b/src/bot/bot_handler.rs @@ -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>) { }) } -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) -> 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> { let rx = { let (_tx, rx_slot) = global_channel(); diff --git a/src/bot/define.rs b/src/bot/define.rs index 4496c50..80db6c2 100644 --- a/src/bot/define.rs +++ b/src/bot/define.rs @@ -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; @@ -36,7 +37,7 @@ pub struct InputBatch { } #[async_trait] -pub trait AttendanceBot { +pub trait AttendanceHandler { async fn handle_commands(&self) -> Result>; } @@ -45,3 +46,7 @@ pub enum MessageEnum { TelegramMessage(InboundMessage), StopMessage, } +#[async_trait] +pub trait Bot { + async fn start(&self) -> Result<()>; +} diff --git a/src/bot/matrix.rs b/src/bot/matrix.rs index e71c992..56ec6f6 100644 --- a/src/bot/matrix.rs +++ b/src/bot/matrix.rs @@ -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, + 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(); + } +} diff --git a/src/main.rs b/src/main.rs index c0112e4..8a0658f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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(()) }