use crate::{ActionSender, ApiChannelItem, ApiResp, Bot, Nonebot, Plugin};
use std::collections::HashMap;
use tokio::sync::{broadcast, mpsc, watch};
impl Nonebot {
pub fn add_bot(
&mut self,
bot_id: String,
api_sender: mpsc::Sender<ApiChannelItem>,
action_sender: ActionSender,
api_resp_watcher: watch::Receiver<ApiResp>,
) -> Bot {
let bot = Bot::new(
bot_id.clone(),
self.config.gen_bot_config(&bot_id),
api_sender,
action_sender,
api_resp_watcher,
);
self.bots.insert(bot_id.to_string(), bot.clone());
self.bot_sender.send(self.bots.clone()).unwrap();
bot
}
pub fn remove_bot(&mut self, bot_id: String) -> Option<Bot> {
let bot_id = bot_id.to_string();
let bot = self.bots.remove(&bot_id);
self.bot_sender.send(self.bots.clone()).unwrap();
bot
}
pub fn new() -> Self {
let nb_config = crate::config::NbConfig::load();
let (event_sender, _) = broadcast::channel(1024); let (action_sender, action_receiver) = tokio::sync::mpsc::channel(32);
let (bot_sender, bot_getter) = watch::channel(HashMap::new());
Nonebot {
bots: HashMap::new(),
config: nb_config,
event_sender,
action_sender,
action_receiver,
bot_sender,
bot_getter,
plugins: HashMap::new(),
}
}
pub fn add_plugin<P>(&mut self, p: P)
where
P: Plugin + Send + Sync + 'static,
{
self.plugins.insert(p.plugin_name().to_owned(), Box::new(p));
}
pub fn remove_plugin(&mut self, plugin_name: &str) {
self.plugins.remove(plugin_name);
}
#[doc(hidden)]
pub async fn pre_run(&mut self) {
use colored::*;
crate::log::init(self.config.global.debug, self.config.global.trace);
tracing::event!(tracing::Level::INFO, "Loaded Config {:?}", self.config);
tracing::event!(
tracing::Level::DEBUG,
"Full Config {:?}",
self.config.get_full_config()
);
tracing::event!(
tracing::Level::INFO,
"{}",
"高性能自律実験4号機が稼働中····".red()
);
self.add_plugin(crate::logger::Logger);
for (plugin_name, plugin) in &mut self.plugins {
let plugin_config: Option<toml::Value> =
self.config.get_config(&plugin.plugin_name().to_lowercase());
if let Some(plugin_config) = plugin_config {
plugin.load_config(plugin_config).await;
}
plugin.run(self.event_sender.subscribe(), self.bot_getter.clone());
tracing::event!(
tracing::Level::INFO,
"Plugin {} is loaded.",
plugin_name.red()
);
}
}
async fn recv(mut self) {
while let Some(action) = self.action_receiver.recv().await {
self.handle_action(action)
}
}
#[tokio::main]
pub async fn run(self) {
self.async_run().await;
}
#[doc(hidden)]
pub async fn async_run(mut self) {
self.pre_run().await;
crate::comms::strat_comms(&self).await;
self.recv().await;
}
}