62 lines
1.7 KiB
Rust
62 lines
1.7 KiB
Rust
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<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 {
|
|
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 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)
|
|
}
|
|
}
|