use crate::bot::define::{AttendanceBot, MessageEnum}; use anyhow::{Result, anyhow}; use async_trait::async_trait; use std::sync::{Mutex, OnceLock}; use tokio::sync::mpsc; use tokio::task::JoinHandle; type MessageTx = mpsc::Sender; type MessageRx = mpsc::Receiver; static GLOBAL_CHANNEL: OnceLock<(MessageTx, Mutex>)> = OnceLock::new(); fn global_channel() -> &'static (MessageTx, Mutex>) { GLOBAL_CHANNEL.get_or_init(|| { let (tx, rx) = mpsc::channel(100); (tx, Mutex::new(Some(rx))) }) } pub struct Bot; impl Bot { 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> { 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.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. } } } }); Ok(handle) } }