设计了部分Bot架构

This commit is contained in:
:NoBody: committed 2026-03-24 14:43:43 +08:00
1 parent 743d0b5d3d
commit 5586bd78a4
2 files changed
+40 -18

No files matched your search

+40 -16
View File
@@ -1,33 +1,57 @@
use crate::bot::define::{AttendanceBot, MessageEnum};
use anyhow::Ok;
use anyhow::Result;
use matrix_sdk::async_trait;
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use std::sync::{Mutex, OnceLock};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
pub struct Bot {
pub messages_receiver: mpsc::Receiver<MessageEnum>,
pub message_sender: mpsc::Sender<MessageEnum>,
type MessageTx = mpsc::Sender<MessageEnum>;
type MessageRx = mpsc::Receiver<MessageEnum>;
static GLOBAL_CHANNEL: OnceLock<(MessageTx, Mutex<Option<MessageRx>>)> = OnceLock::new();
fn global_channel() -> &'static (MessageTx, Mutex<Option<MessageRx>>) {
GLOBAL_CHANNEL.get_or_init(|| {
let (tx, rx) = mpsc::channel(100);
(tx, Mutex::new(Some(rx)))
})
}
pub struct Bot;
impl Bot {
fn new() -> Self {
let (tx, rx) = mpsc::channel(100);
Self {
messages_receiver: rx,
message_sender: tx,
}
pub fn new() -> Self {
Self
}
pub fn global_sender() -> MessageTx {
global_channel().0.clone()
}
}
#[async_trait]
impl AttendanceBot for Bot {
async fn handle_commands(&self) -> Result<JoinHandle<()>> {
let bot = Bot::new();
let (_tx, mut rx) = (bot.message_sender, bot.messages_receiver);
let rx = {
let (_tx, rx_slot) = global_channel();
rx_slot
.lock()
.map_err(|_| anyhow!("global receiver lock poisoned"))?
.take()
.ok_or_else(|| anyhow!("global receiver has already been taken"))?
};
let mut rx = rx;
let handle = tokio::spawn(async move {
while let Some(msg) = rx.blocking_recv() {
while let Some(msg) = rx.recv().await {
match msg {
_ => {}
MessageEnum::StopMessage => break,
MessageEnum::MatrixMessage(_msg) => {
// TODO: route matrix message to command processor.
}
MessageEnum::TelegramMessage(_msg) => {
// TODO: route telegram message to command processor.
}
}
}
});
-2
View File
@@ -10,7 +10,6 @@ pub trait Sender {
#[async_trait]
pub trait Receiver {
// Pull user inputs from upstream and return a cursor for incremental sync.
async fn recv(&self, msg: InboundMessage) -> Result<()>;
}
@@ -46,4 +45,3 @@ pub enum MessageEnum {
TelegramMessage(InboundMessage),
StopMessage,
}