This commit is contained in:
parent
12288ced5c
commit
f08af9609e
@ -2,7 +2,7 @@ use log::{error, info};
|
||||
use quickjs_rusty::serde::to_js;
|
||||
use std::{
|
||||
str::FromStr,
|
||||
sync::{Arc, RwLock},
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
};
|
||||
use teloxide::{
|
||||
dispatching::{dialogue::GetChatId, UpdateFilterExt},
|
||||
@ -23,22 +23,26 @@ use crate::{
|
||||
pub type BotHandler =
|
||||
Handler<'static, DependencyMap, BotResult<()>, teloxide::dispatching::DpHandlerDescription>;
|
||||
|
||||
pub fn script_handler(r: Arc<BotRuntime>) -> BotHandler {
|
||||
pub fn script_handler(r: Arc<Mutex<BotRuntime>>) -> BotHandler {
|
||||
let cr = r.clone();
|
||||
dptree::entry()
|
||||
.branch(
|
||||
Update::filter_message()
|
||||
.inspect(|m: Message| println!("Call script"))
|
||||
// check if message is command
|
||||
.filter_map(|m: Message| m.text().and_then(|t| BotCommand::from_str(t).ok()))
|
||||
.inspect(|m: Message| println!("Call script"))
|
||||
// check if command is presented in config
|
||||
.filter_map(move |bc: BotCommand| {
|
||||
let r = std::sync::Arc::clone(&r);
|
||||
let command = bc.command();
|
||||
|
||||
let rc = r.rc.lock().expect("RwLock lock on commands map failed");
|
||||
let r = r.lock().expect("RwLock lock on commands map failed");
|
||||
let rc = &r.rc;
|
||||
|
||||
rc.get_command_message(command)
|
||||
})
|
||||
.inspect(|m: Message| println!("Call script"))
|
||||
.endpoint(handle_botmessage),
|
||||
)
|
||||
.branch(
|
||||
@ -46,7 +50,8 @@ pub fn script_handler(r: Arc<BotRuntime>) -> BotHandler {
|
||||
.filter_map(move |q: CallbackQuery| {
|
||||
q.data.and_then(|data| {
|
||||
let r = std::sync::Arc::clone(&cr);
|
||||
let rc = r.rc.lock().expect("RwLock lock on commands map failed");
|
||||
let r = r.lock().expect("RwLock lock on commands map failed");
|
||||
let rc = &r.rc;
|
||||
|
||||
rc.get_callback_message(&data)
|
||||
})
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
future::Future,
|
||||
sync::{Arc, RwLock},
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
thread::JoinHandle,
|
||||
time::Duration,
|
||||
};
|
||||
@ -14,6 +14,7 @@ use teloxide::{
|
||||
prelude::{Dispatcher, Requester},
|
||||
Bot,
|
||||
};
|
||||
use tokio::runtime::Handle;
|
||||
|
||||
use crate::{
|
||||
bot_handler::{script_handler, BotHandler},
|
||||
@ -28,18 +29,11 @@ pub struct BotRunner {
|
||||
thread: Option<JoinHandle<BotResult<()>>>,
|
||||
}
|
||||
|
||||
unsafe impl Sync for BotRunner {}
|
||||
unsafe impl Send for BotRunner {}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct BotInfo {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
static ref BOT_POOL: RwLock<HashMap<String, BotRunner>> = RwLock::new(HashMap::new());
|
||||
}
|
||||
|
||||
pub static DEFAULT_SCRIPT: &str =
|
||||
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/default_script.js"));
|
||||
|
||||
@ -171,7 +165,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
async fn script_handler_gen(r: Arc<BotRuntime>, plug_handlers: Vec<BotHandler>) -> BotHandler {
|
||||
async fn script_handler_gen(
|
||||
r: Arc<Mutex<BotRuntime>>,
|
||||
plug_handlers: Vec<BotHandler>,
|
||||
) -> BotHandler {
|
||||
let handler = script_handler(r.clone());
|
||||
// each handler will be added to dptree::entry()
|
||||
let handler = plug_handlers
|
||||
@ -182,48 +179,6 @@ async fn script_handler_gen(r: Arc<BotRuntime>, plug_handlers: Vec<BotHandler>)
|
||||
handler
|
||||
}
|
||||
|
||||
pub async fn start_bot(
|
||||
bi: BotInstance,
|
||||
db: &mut DB,
|
||||
plug_handlers: Vec<BotHandler>,
|
||||
) -> BotResult<BotInfo> {
|
||||
let db = db.clone().with_name(bi.name.clone());
|
||||
let controller = BotController::with_db(db.clone(), &bi.token, &bi.script).await?;
|
||||
|
||||
let handler = script_handler(controller.runtime.clone());
|
||||
// each handler will be added to dptree::entry()
|
||||
let handler = plug_handlers
|
||||
.into_iter()
|
||||
// as well as the script handler at the end
|
||||
.chain(std::iter::once(handler))
|
||||
.fold(dptree::entry(), |h, plug| h.branch(plug));
|
||||
|
||||
let thread = spawn_bot_thread(controller.bot.clone(), controller.db.clone(), handler).await?;
|
||||
|
||||
let info = BotInfo {
|
||||
name: bi.name.clone(),
|
||||
};
|
||||
let runner = BotRunner {
|
||||
controller,
|
||||
info: info.clone(),
|
||||
thread: Some(thread),
|
||||
};
|
||||
|
||||
BOT_POOL
|
||||
.write()
|
||||
.map_or_else(
|
||||
|err| {
|
||||
Err(BotError::RwLockError(format!(
|
||||
"Failed to lock BOT_POOL because previous thread paniced, err: {err}"
|
||||
)))
|
||||
},
|
||||
Ok,
|
||||
)?
|
||||
.insert(bi.name.clone(), runner);
|
||||
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
pub async fn spawn_bot_thread(
|
||||
bot: Bot,
|
||||
mut db: DB,
|
||||
@ -235,9 +190,10 @@ pub async fn spawn_bot_thread(
|
||||
let thread = std::thread::spawn(move || -> BotResult<()> {
|
||||
let state_mgr = state_mgr;
|
||||
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
// let rt = tokio::runtime::Builder::new_current_thread()
|
||||
// .enable_all()
|
||||
// .build()?;
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
|
||||
rt.block_on(
|
||||
Dispatcher::builder(bot, handler)
|
||||
|
||||
13
src/main.rs
13
src/main.rs
@ -104,16 +104,14 @@ type CallbackStore = CallbackInfo<Callback>;
|
||||
pub struct BotController {
|
||||
pub bot: Bot,
|
||||
pub db: DB,
|
||||
pub runtime: Arc<BotRuntime>,
|
||||
pub runtime: Arc<Mutex<BotRuntime>>,
|
||||
}
|
||||
|
||||
pub struct BotRuntime {
|
||||
pub rc: Mutex<RunnerConfig>,
|
||||
pub rc: RunnerConfig,
|
||||
pub runner: Runner,
|
||||
}
|
||||
|
||||
unsafe impl Send for BotRuntime {}
|
||||
unsafe impl Sync for BotRuntime {}
|
||||
|
||||
impl Drop for BotController {
|
||||
fn drop(&mut self) {
|
||||
@ -121,8 +119,6 @@ impl Drop for BotController {
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for BotController {}
|
||||
|
||||
const MAIN_BOT_SCRIPT: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/mainbot.js"));
|
||||
|
||||
impl BotController {
|
||||
@ -148,10 +144,7 @@ impl BotController {
|
||||
let mut runner = Runner::init_with_db(&mut db)?;
|
||||
runner.call_attacher(|c, o| attach_user_application(c, o, &db, &bot))??;
|
||||
let rc = runner.init_config(script)?;
|
||||
let runtime = Arc::new(BotRuntime {
|
||||
rc: Mutex::new(rc),
|
||||
runner,
|
||||
});
|
||||
let runtime = Arc::new(Mutex::new(BotRuntime { rc, runner }));
|
||||
|
||||
Ok(Self { bot, db, runtime })
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user