This commit is contained in:
ModulatingForce 2024-02-25 10:40:54 -05:00
parent 66e82de28f
commit 0a7a4b539a
9 changed files with 2093 additions and 1874 deletions

View file

@ -1,7 +1,7 @@
pub mod botinstance; pub mod botinstance;
pub mod ratelimiter;
pub mod botmodules; pub mod botmodules;
pub mod identity; pub mod identity;
pub mod ratelimiter;
// pub fn init() -> () // pub fn init() -> ()
// { // {

View file

@ -1,21 +1,20 @@
// use futures::lock::Mutex; // use futures::lock::Mutex;
use tokio::sync::mpsc::UnboundedReceiver; use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::RwLock; use tokio::sync::RwLock;
use twitch_irc::login::StaticLoginCredentials; use twitch_irc::login::StaticLoginCredentials;
use twitch_irc::ClientConfig;
use twitch_irc::SecureTCPTransport;
use twitch_irc::TwitchIRCClient;
use twitch_irc::message::PrivmsgMessage; use twitch_irc::message::PrivmsgMessage;
use twitch_irc::message::ServerMessage; use twitch_irc::message::ServerMessage;
use twitch_irc::transport::tcp::TCPTransport; use twitch_irc::transport::tcp::TCPTransport;
use twitch_irc::transport::tcp::TLS; use twitch_irc::transport::tcp::TLS;
use twitch_irc::ClientConfig;
use twitch_irc::SecureTCPTransport;
use twitch_irc::TwitchIRCClient;
// use std::borrow::Borrow; // use std::borrow::Borrow;
use dotenv::dotenv;
use std::borrow::BorrowMut; use std::borrow::BorrowMut;
use std::boxed; use std::boxed;
use std::cell::Ref; use std::cell::Ref;
use std::env; use std::env;
use dotenv::dotenv;
use std::collections::HashMap; use std::collections::HashMap;
@ -27,16 +26,15 @@ use tokio::sync::Mutex;
use crate::core::botmodules::BotAction; use crate::core::botmodules::BotAction;
use crate::core::botmodules::BotAction;
use crate::core::ratelimiter::RateLimiter;
use crate::core::ratelimiter; use crate::core::ratelimiter;
use crate::core::ratelimiter::RateLimiter;
use crate::core::botmodules; use crate::core::botmodules;
use crate::core::botmodules::ModulesManager; use crate::core::botmodules::ModulesManager;
use crate::core::identity::{IdentityManager,Permissible,ChangeResult}; use crate::core::identity::{ChangeResult, IdentityManager, Permissible};
use std::rc::Rc;
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
// use futures::lock::Mutex; // use futures::lock::Mutex;
@ -48,10 +46,8 @@ use core::borrow::Borrow;
// pub type BotAR = Arc<RwLock<BotInstance>>; // pub type BotAR = Arc<RwLock<BotInstance>>;
use super::botmodules::bot_actions::actions_util::BotAR; use super::botmodules::bot_actions::actions_util::BotAR;
use casual_logger::{Level, Log}; use casual_logger::{Level, Log};
pub mod botlog { pub mod botlog {
/* /*
@ -76,17 +72,20 @@ pub mod botlog {
*/ */
pub fn trace(in_msg:&str,in_module:Option<String>,in_prvmsg:Option<&PrivmsgMessage>) -> () pub fn trace(
{ in_msg: &str,
in_module: Option<String>,
in_prvmsg: Option<&PrivmsgMessage>,
) -> () {
let (chnl, chatter) = match in_prvmsg { let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => { Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(Some(prvmsg.channel_login.clone()),Some(prvmsg.sender.name.clone())) // <-- Clone fine atm while we're just working with Strings (
} Some(prvmsg.channel_login.clone()),
None => { Some(prvmsg.sender.name.clone()),
(None,None) ) // <-- Clone fine atm while we're just working with Strings
} }
None => (None, None),
}; };
Log::trace_t( Log::trace_t(
@ -94,23 +93,24 @@ pub mod botlog {
casual_logger::Table::default() // casual_logger::Table::default() //
.str("Channel", &format!("{:?}", chnl)) .str("Channel", &format!("{:?}", chnl))
.str("Chatter", &format!("{:?}", chatter)) .str("Chatter", &format!("{:?}", chatter))
.str("Code_Module",&format!("{:?}",in_module)) .str("Code_Module", &format!("{:?}", in_module)),
); );
} }
pub fn debug(in_msg:&str,in_module:Option<String>,in_prvmsg:Option<&PrivmsgMessage>) -> () { pub fn debug(
in_msg: &str,
in_module: Option<String>,
in_prvmsg: Option<&PrivmsgMessage>,
) -> () {
let (chnl, chatter) = match in_prvmsg { let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => { Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(Some(prvmsg.channel_login.clone()),Some(prvmsg.sender.name.clone())) // <-- Clone fine atm while we're just working with Strings (
} Some(prvmsg.channel_login.clone()),
None => { Some(prvmsg.sender.name.clone()),
(None,None) ) // <-- Clone fine atm while we're just working with Strings
} }
None => (None, None),
}; };
Log::debug_t( Log::debug_t(
@ -118,21 +118,20 @@ pub mod botlog {
casual_logger::Table::default() // casual_logger::Table::default() //
.str("Channel", &format!("{:?}", chnl)) .str("Channel", &format!("{:?}", chnl))
.str("Chatter", &format!("{:?}", chatter)) .str("Chatter", &format!("{:?}", chatter))
.str("Code_Module",&format!("{:?}",in_module)) .str("Code_Module", &format!("{:?}", in_module)),
); );
} }
pub fn info(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgMessage>) -> () { pub fn info(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgMessage>) -> () {
let (chnl, chatter) = match in_prvmsg { let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => { Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(Some(prvmsg.channel_login.clone()),Some(prvmsg.sender.name.clone())) // <-- Clone fine atm while we're just working with Strings (
} Some(prvmsg.channel_login.clone()),
None => { Some(prvmsg.sender.name.clone()),
(None,None) ) // <-- Clone fine atm while we're just working with Strings
} }
None => (None, None),
}; };
Log::info_t( Log::info_t(
@ -140,21 +139,24 @@ pub mod botlog {
casual_logger::Table::default() // casual_logger::Table::default() //
.str("Channel", &format!("{:?}", chnl)) .str("Channel", &format!("{:?}", chnl))
.str("Chatter", &format!("{:?}", chatter)) .str("Chatter", &format!("{:?}", chatter))
.str("Code_Module",&format!("{:?}",in_module)) .str("Code_Module", &format!("{:?}", in_module)),
); );
} }
pub fn notice(in_msg:&str,in_module:Option<String>,in_prvmsg:Option<&PrivmsgMessage>) -> () { pub fn notice(
in_msg: &str,
in_module: Option<String>,
in_prvmsg: Option<&PrivmsgMessage>,
) -> () {
let (chnl, chatter) = match in_prvmsg { let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => { Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(Some(prvmsg.channel_login.clone()),Some(prvmsg.sender.name.clone())) // <-- Clone fine atm while we're just working with Strings (
} Some(prvmsg.channel_login.clone()),
None => { Some(prvmsg.sender.name.clone()),
(None,None) ) // <-- Clone fine atm while we're just working with Strings
} }
None => (None, None),
}; };
Log::notice_t( Log::notice_t(
@ -162,21 +164,20 @@ pub mod botlog {
casual_logger::Table::default() // casual_logger::Table::default() //
.str("Channel", &format!("{:?}", chnl)) .str("Channel", &format!("{:?}", chnl))
.str("Chatter", &format!("{:?}", chatter)) .str("Chatter", &format!("{:?}", chatter))
.str("Code_Module",&format!("{:?}",in_module)) .str("Code_Module", &format!("{:?}", in_module)),
); );
} }
pub fn warn(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgMessage>) -> () { pub fn warn(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgMessage>) -> () {
let (chnl, chatter) = match in_prvmsg { let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => { Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(Some(prvmsg.channel_login.clone()),Some(prvmsg.sender.name.clone())) // <-- Clone fine atm while we're just working with Strings (
} Some(prvmsg.channel_login.clone()),
None => { Some(prvmsg.sender.name.clone()),
(None,None) ) // <-- Clone fine atm while we're just working with Strings
} }
None => (None, None),
}; };
Log::warn_t( Log::warn_t(
@ -184,21 +185,24 @@ pub mod botlog {
casual_logger::Table::default() // casual_logger::Table::default() //
.str("Channel", &format!("{:?}", chnl)) .str("Channel", &format!("{:?}", chnl))
.str("Chatter", &format!("{:?}", chatter)) .str("Chatter", &format!("{:?}", chatter))
.str("Code_Module",&format!("{:?}",in_module)) .str("Code_Module", &format!("{:?}", in_module)),
); );
} }
pub fn error(in_msg:&str,in_module:Option<String>,in_prvmsg:Option<&PrivmsgMessage>) -> () { pub fn error(
in_msg: &str,
in_module: Option<String>,
in_prvmsg: Option<&PrivmsgMessage>,
) -> () {
let (chnl, chatter) = match in_prvmsg { let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => { Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(Some(prvmsg.channel_login.clone()),Some(prvmsg.sender.name.clone())) // <-- Clone fine atm while we're just working with Strings (
} Some(prvmsg.channel_login.clone()),
None => { Some(prvmsg.sender.name.clone()),
(None,None) ) // <-- Clone fine atm while we're just working with Strings
} }
None => (None, None),
}; };
Log::error_t( Log::error_t(
@ -206,21 +210,24 @@ pub mod botlog {
casual_logger::Table::default() // casual_logger::Table::default() //
.str("Channel", &format!("{:?}", chnl)) .str("Channel", &format!("{:?}", chnl))
.str("Chatter", &format!("{:?}", chatter)) .str("Chatter", &format!("{:?}", chatter))
.str("Code_Module",&format!("{:?}",in_module)) .str("Code_Module", &format!("{:?}", in_module)),
); );
} }
pub fn fatal<'a>(in_msg:&'a str,in_module:Option<String>,in_prvmsg:Option<&PrivmsgMessage>) -> &'a str { pub fn fatal<'a>(
in_msg: &'a str,
in_module: Option<String>,
in_prvmsg: Option<&PrivmsgMessage>,
) -> &'a str {
let (chnl, chatter) = match in_prvmsg { let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => { Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text)); //Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(Some(prvmsg.channel_login.clone()),Some(prvmsg.sender.name.clone())) // <-- Clone fine atm while we're just working with Strings (
} Some(prvmsg.channel_login.clone()),
None => { Some(prvmsg.sender.name.clone()),
(None,None) ) // <-- Clone fine atm while we're just working with Strings
} }
None => (None, None),
}; };
Log::fatal_t( Log::fatal_t(
@ -228,22 +235,18 @@ pub mod botlog {
casual_logger::Table::default() // casual_logger::Table::default() //
.str("Channel", &format!("{:?}", chnl)) .str("Channel", &format!("{:?}", chnl))
.str("Chatter", &format!("{:?}", chatter)) .str("Chatter", &format!("{:?}", chatter))
.str("Code_Module",&format!("{:?}",in_module)) .str("Code_Module", &format!("{:?}", in_module)),
); );
in_msg in_msg
} }
} }
#[derive(Debug, PartialEq, Eq, Hash, Clone)] #[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum ChType { pub enum ChType {
Channel(String), Channel(String),
} }
pub use ChType::Channel; pub use ChType::Channel;
#[derive(Clone)] #[derive(Clone)]
@ -253,10 +256,10 @@ pub struct Chat {
} }
impl Chat { impl Chat {
pub fn init(
ratelimiters: HashMap<ChType, RateLimiter>,
pub fn init(ratelimiters:HashMap<ChType, RateLimiter>, client: TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>,
client:TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>) -> Chat { ) -> Chat {
Chat { Chat {
ratelimiters: Arc::new(Mutex::new(ratelimiters)), ratelimiters: Arc::new(Mutex::new(ratelimiters)),
client: client, client: client,
@ -268,8 +271,6 @@ impl Chat {
self.ratelimiters.lock().await.insert(chnl, n); self.ratelimiters.lock().await.insert(chnl, n);
} }
// pub async fn say_in_reply_to(&mut self, msg:& PrivmsgMessage , mut outmsg:String) -> () { // pub async fn say_in_reply_to(&mut self, msg:& PrivmsgMessage , mut outmsg:String) -> () {
pub async fn say_in_reply_to(&self, msg: &PrivmsgMessage, mut outmsg: String) -> () { pub async fn say_in_reply_to(&self, msg: &PrivmsgMessage, mut outmsg: String) -> () {
/* /*
@ -301,20 +302,26 @@ impl Chat {
self.client.say_in_reply_to(msg, outmsg).await.unwrap(); self.client.say_in_reply_to(msg, outmsg).await.unwrap();
// println!("(#{}) > {}", msg.channel_login, "rate limit counter increase"); // println!("(#{}) > {}", msg.channel_login, "rate limit counter increase");
// Log::trace(&format!("(#{}) > {}", msg.channel_login, "rate limit counter increase")); // Log::trace(&format!("(#{}) > {}", msg.channel_login, "rate limit counter increase"));
botlog::trace(&format!("(#{}) > {}", msg.channel_login, "rate limit counter increase"), botlog::trace(
&format!(
"(#{}) > {}",
msg.channel_login, "rate limit counter increase"
),
Some("Chat > say_in_reply_to".to_string()), Some("Chat > say_in_reply_to".to_string()),
Some(&msg)); Some(&msg),
);
contextratelimiter.increment_counter(); contextratelimiter.increment_counter();
// println!("{:?}",self.ratelimiters); // println!("{:?}",self.ratelimiters);
// Log::trace(&format!("{:?}",self.ratelimiters)); // Log::trace(&format!("{:?}",self.ratelimiters));
botlog::trace(&format!("{:?}",self.ratelimiters), botlog::trace(
&format!("{:?}", self.ratelimiters),
Some("Chat > say_in_reply_to".to_string()), Some("Chat > say_in_reply_to".to_string()),
Some(&msg)); Some(&msg),
}, );
}
ratelimiter::LimiterResp::Skip => { ratelimiter::LimiterResp::Skip => {
(); // do nothing otherwise (); // do nothing otherwise
} }
} }
Log::flush(); Log::flush();
} }
@ -322,35 +329,22 @@ impl Chat {
async fn say(&self, _: String, _: String) -> () { async fn say(&self, _: String, _: String) -> () {
// more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say // more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say
// self.client.say(msg,outmsg).await.unwrap(); // self.client.say(msg,outmsg).await.unwrap();
} }
async fn me(&self, _: String, _: String) -> () { async fn me(&self, _: String, _: String) -> () {
// more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say // more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say
// self.client.me(msg,outmsg).await.unwrap(); // self.client.me(msg,outmsg).await.unwrap();
} }
async fn me_in_reply_to(&self, _: String, _: String) -> () { async fn me_in_reply_to(&self, _: String, _: String) -> () {
// more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say // more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say
// self.client.me(msg,outmsg).await.unwrap(); // self.client.me(msg,outmsg).await.unwrap();
} }
} }
#[derive(Clone)] #[derive(Clone)]
pub struct BotManagers { pub struct BotManagers {
// pub botmodules : ModulesManager, // pub botmodules : ModulesManager,
@ -359,11 +353,10 @@ pub struct BotManagers {
} }
impl BotManagers { impl BotManagers {
pub fn init(
pub fn init(ratelimiters:HashMap<ChType, RateLimiter>, ratelimiters: HashMap<ChType, RateLimiter>,
client:TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>) client: TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>,
-> BotManagers { ) -> BotManagers {
BotManagers { BotManagers {
identity: Arc::new(RwLock::new(IdentityManager::init())), identity: Arc::new(RwLock::new(IdentityManager::init())),
chat: Chat::init(ratelimiters, client), chat: Chat::init(ratelimiters, client),
@ -373,23 +366,19 @@ impl BotManagers {
pub fn rIdentity(self) -> Arc<RwLock<IdentityManager>> { pub fn rIdentity(self) -> Arc<RwLock<IdentityManager>> {
self.identity self.identity
} }
} }
pub struct ArcBox<T: Clone>(pub Arc<Mutex<T>>); pub struct ArcBox<T: Clone>(pub Arc<Mutex<T>>);
impl<T: Clone> ArcBox<T> { impl<T: Clone> ArcBox<T> {
pub fn inst(&self) -> &Mutex<T> { pub fn inst(&self) -> &Mutex<T> {
&self.0 &self.0
} }
} }
//#[derive(Clone)] //#[derive(Clone)]
// #[derive(Copy)] // <-- Cannot be derived // #[derive(Copy)] // <-- Cannot be derived
pub struct BotInstance pub struct BotInstance {
{
pub prefix: char, pub prefix: char,
pub bot_channel: ChType, pub bot_channel: ChType,
pub incoming_messages: Arc<RwLock<UnboundedReceiver<ServerMessage>>>, pub incoming_messages: Arc<RwLock<UnboundedReceiver<ServerMessage>>>,
@ -398,22 +387,20 @@ pub struct BotInstance
pub bot_channels: Vec<ChType>, pub bot_channels: Vec<ChType>,
pub botmgrs: BotManagers, pub botmgrs: BotManagers,
//modesmgr : ModesManager, // Silent/Quiet , uwu , frisky/horny //modesmgr : ModesManager, // Silent/Quiet , uwu , frisky/horny
} }
impl BotInstance {
pub async fn init() -> BotInstance {
impl BotInstance
{
pub async fn init() -> BotInstance
{
dotenv().ok(); dotenv().ok();
let login_name = env::var("login_name").unwrap().to_owned(); let login_name = env::var("login_name").unwrap().to_owned();
let oauth_token = env::var("access_token").unwrap().to_owned(); let oauth_token = env::var("access_token").unwrap().to_owned();
let prefix = env::var("prefix").unwrap().to_owned().chars().next().expect("ERROR : when defining prefix"); let prefix = env::var("prefix")
.unwrap()
.to_owned()
.chars()
.next()
.expect("ERROR : when defining prefix");
/* /*
Vector of channels to join Vector of channels to join
@ -426,9 +413,10 @@ impl BotInstance
botchannels.push(Channel(String::from(chnl))); botchannels.push(Channel(String::from(chnl)));
} }
let config = ClientConfig::new_simple( let config = ClientConfig::new_simple(StaticLoginCredentials::new(
StaticLoginCredentials::new(login_name.to_owned(), Some(oauth_token.to_owned())) login_name.to_owned(),
); Some(oauth_token.to_owned()),
));
let (incoming_messages, client) = let (incoming_messages, client) =
TwitchIRCClient::<SecureTCPTransport, StaticLoginCredentials>::new(config); TwitchIRCClient::<SecureTCPTransport, StaticLoginCredentials>::new(config);
@ -447,8 +435,6 @@ impl BotInstance
//self.chat.ratelimiters.insert(Channel(String::from(chnl)),n); //self.chat.ratelimiters.insert(Channel(String::from(chnl)),n);
} }
// let b = BotInstance { // let b = BotInstance {
// prefix : prefix, // prefix : prefix,
// bot_channel : Channel(login_name) , // bot_channel : Channel(login_name) ,
@ -473,95 +459,95 @@ impl BotInstance
} }
pub async fn runner(self) -> () { pub async fn runner(self) -> () {
let bot = Arc::new(RwLock::new(self)); let bot = Arc::new(RwLock::new(self));
let join_handle = tokio::spawn(async move { let join_handle = tokio::spawn(async move {
let a = bot.read().await; let a = bot.read().await;
let mut a = a.incoming_messages.write().await; let mut a = a.incoming_messages.write().await;
while let Some(message) = a.recv().await { while let Some(message) = a.recv().await {
match message { match message {
ServerMessage::Notice(msg) => { ServerMessage::Notice(msg) => {
match &msg.channel_login { match &msg.channel_login {
Some(chnl) => { Some(chnl) => {
// println!("NOTICE : (#{}) {}", chnl, msg.message_text) // println!("NOTICE : (#{}) {}", chnl, msg.message_text)
// Log::notice(&format!("NOTICE : (#{}) {}", chnl, msg.message_text)); // Log::notice(&format!("NOTICE : (#{}) {}", chnl, msg.message_text));
botlog::notice(&format!("NOTICE : (#{}) {}", chnl, msg.message_text), botlog::notice(
&format!("NOTICE : (#{}) {}", chnl, msg.message_text),
Some("BotInstance > runner()".to_string()), Some("BotInstance > runner()".to_string()),
None); None,
);
}, }
None => { None => {
// println!("NOTICE : {}", msg.message_text); // println!("NOTICE : {}", msg.message_text);
// Log::notice(&format!("NOTICE : {}", msg.message_text)); // Log::notice(&format!("NOTICE : {}", msg.message_text));
botlog::notice(&format!("NOTICE : {}", msg.message_text), botlog::notice(
&format!("NOTICE : {}", msg.message_text),
Some("BotInstance > runner()".to_string()), Some("BotInstance > runner()".to_string()),
None); None,
}, );
}
} }
} }
ServerMessage::Privmsg(msg) => { ServerMessage::Privmsg(msg) => {
// println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text);
// Log::trace(&format!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text)); // Log::trace(&format!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text));
botlog::debug(&format!("Twitch Chat > {} @ #{}: {}", msg.channel_login, msg.sender.name, msg.message_text), botlog::debug(
&format!(
"Twitch Chat > {} @ #{}: {}",
msg.channel_login, msg.sender.name, msg.message_text
),
Some("BotInstance > runner()".to_string()), Some("BotInstance > runner()".to_string()),
Some(&msg)); Some(&msg),
);
// println!("Privmsg section"); // println!("Privmsg section");
// Log::debug(&format!("Privmsg section")); // Log::debug(&format!("Privmsg section"));
botlog::trace(&format!("Privmsg section"), botlog::trace(
&format!("Privmsg section"),
Some("BotInstance > runner()".to_string()), Some("BotInstance > runner()".to_string()),
Some(&msg)); Some(&msg),
);
BotInstance::listener_main_prvmsg(Arc::clone(&bot), &msg).await; BotInstance::listener_main_prvmsg(Arc::clone(&bot), &msg).await;
}
},
ServerMessage::Whisper(msg) => { ServerMessage::Whisper(msg) => {
// println!("(w) {}: {}", msg.sender.name, msg.message_text); // println!("(w) {}: {}", msg.sender.name, msg.message_text);
// Log::trace(&format!("(w) {}: {}", msg.sender.name, msg.message_text)); // Log::trace(&format!("(w) {}: {}", msg.sender.name, msg.message_text));
botlog::trace(&format!("(w) {}: {}", msg.sender.name, msg.message_text), botlog::trace(
&format!("(w) {}: {}", msg.sender.name, msg.message_text),
Some("BotInstance > runner()".to_string()), Some("BotInstance > runner()".to_string()),
None); None,
}, );
}
ServerMessage::Join(msg) => { ServerMessage::Join(msg) => {
// println!("JOINED: {}", msg.channel_login); // println!("JOINED: {}", msg.channel_login);
// Log::notice(&format!("JOINED: {}", msg.channel_login)); // Log::notice(&format!("JOINED: {}", msg.channel_login));
botlog::notice(&format!("JOINED: {}", msg.channel_login), botlog::notice(
&format!("JOINED: {}", msg.channel_login),
Some("BotInstance > runner()".to_string()), Some("BotInstance > runner()".to_string()),
None); None,
}, );
}
ServerMessage::Part(msg) => { ServerMessage::Part(msg) => {
// println!("PARTED: {}", msg.channel_login); // println!("PARTED: {}", msg.channel_login);
// Log::notice(&format!("PARTED: {}", msg.channel_login)); // Log::notice(&format!("PARTED: {}", msg.channel_login));
botlog::notice(&format!("PARTED: {}", msg.channel_login), botlog::notice(
&format!("PARTED: {}", msg.channel_login),
Some("BotInstance > runner()".to_string()), Some("BotInstance > runner()".to_string()),
None); None,
}, );
}
_ => {} _ => {}
}; };
Log::flush(); Log::flush();
} }
}); });
join_handle.await.unwrap(); join_handle.await.unwrap();
} }
pub fn get_botmodules(self) -> Arc<ModulesManager> { pub fn get_botmodules(self) -> Arc<ModulesManager> {
self.botmodules self.botmodules
} }
pub async fn get_botmgrs(self) -> BotManagers { pub async fn get_botmgrs(self) -> BotManagers {
@ -573,23 +559,21 @@ impl BotInstance
Arc::clone(&self.botmgrs.identity) Arc::clone(&self.botmgrs.identity)
} }
pub fn get_prefix(&self) -> char { pub fn get_prefix(&self) -> char {
(*self).prefix (*self).prefix
} }
// ----------------- // -----------------
// PRIVATE FUNCTIONS // PRIVATE FUNCTIONS
pub async fn listener_main_prvmsg(bot: BotAR, msg: &PrivmsgMessage) -> () { pub async fn listener_main_prvmsg(bot: BotAR, msg: &PrivmsgMessage) -> () {
// println!(">> Inner listenermain_prvmsg()"); // println!(">> Inner listenermain_prvmsg()");
// Log::trace(">> Inner listenermain_prvmsg()"); // Log::trace(">> Inner listenermain_prvmsg()");
botlog::trace(">> Inner listenermain_prvmsg()", botlog::trace(
">> Inner listenermain_prvmsg()",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
// let a = a; // let a = a;
// println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text);
@ -602,37 +586,41 @@ impl BotInstance
let a = hacts.read().await; let a = hacts.read().await;
// println!("hacts size : {}",(*a).len()); // println!("hacts size : {}",(*a).len());
// Log::debug(&format!("hacts size : {}",(*a).len())); // Log::debug(&format!("hacts size : {}",(*a).len()));
botlog::trace(&format!("hacts size : {}",(*a).len()), botlog::trace(
&format!("hacts size : {}", (*a).len()),
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
// println!(">> Inner listenermain_prvmsg() >> before for loop of bot actions"); // println!(">> Inner listenermain_prvmsg() >> before for loop of bot actions");
// Log::trace(">> Inner listenermain_prvmsg() >> before for loop of bot actions"); // Log::trace(">> Inner listenermain_prvmsg() >> before for loop of bot actions");
botlog::trace(">> Inner listenermain_prvmsg() >> before for loop of bot actions", botlog::trace(
">> Inner listenermain_prvmsg() >> before for loop of bot actions",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
for (_m, acts) in &*hacts.read().await { for (_m, acts) in &*hacts.read().await {
// println!(">> Inner listenermain_prvmsg() >> checking bot actions"); // println!(">> Inner listenermain_prvmsg() >> checking bot actions");
// Log::trace(">> Inner listenermain_prvmsg() >> checking bot actions"); // Log::trace(">> Inner listenermain_prvmsg() >> checking bot actions");
botlog::trace(">> Inner listenermain_prvmsg() >> checking bot actions", botlog::trace(
">> Inner listenermain_prvmsg() >> checking bot actions",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
// let bot = bot; // let bot = bot;
for a in acts { for a in acts {
// println!(">> Inner listenermain_prvmsg() >> checking bot actions >> 2"); // println!(">> Inner listenermain_prvmsg() >> checking bot actions >> 2");
// Log::trace(">> Inner listenermain_prvmsg() >> checking bot actions >> 2"); // Log::trace(">> Inner listenermain_prvmsg() >> checking bot actions >> 2");
botlog::trace(">> Inner listenermain_prvmsg() >> checking bot actions >> 2", botlog::trace(
">> Inner listenermain_prvmsg() >> checking bot actions >> 2",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
let _act = match a { let _act = match a {
crate::core::botmodules::BotAction::C(c) => { crate::core::botmodules::BotAction::C(c) => {
/* /*
BotCommand handling - BotCommand handling -
@ -650,15 +638,18 @@ impl BotInstance
// println!("Reviewing internal commands"); // println!("Reviewing internal commands");
// Log::trace("Reviewing internal commands"); // Log::trace("Reviewing internal commands");
botlog::trace("Reviewing internal commands", botlog::trace(
"Reviewing internal commands",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
// let inpt = msg.message_text.split("\n").next().expect("ERROR during BotCommand"); // let inpt = msg.message_text.split("\n").next().expect("ERROR during BotCommand");
let inpt = msg.message_text.split(" ").next().expect("ERROR during BotCommand"); let inpt = msg
.message_text
.split(" ")
.next()
.expect("ERROR during BotCommand");
// [x] Check if a bot command based on ... // [x] Check if a bot command based on ...
// [x] prefix + command // [x] prefix + command
@ -672,7 +663,6 @@ impl BotInstance
// [x] prefix + alias // [x] prefix + alias
for alias in &c.alias { for alias in &c.alias {
let instr = bot.read().await.get_prefix(); let instr = bot.read().await.get_prefix();
if inpt == String::from(instr) + alias.as_str() { if inpt == String::from(instr) + alias.as_str() {
confirmed_bot_command = true; confirmed_bot_command = true;
@ -682,22 +672,28 @@ impl BotInstance
if confirmed_bot_command { if confirmed_bot_command {
// println!("Confirmed bot command"); // println!("Confirmed bot command");
// Log::debug("Confirmed bot command"); // Log::debug("Confirmed bot command");
botlog::debug("Confirmed bot command", botlog::debug(
"Confirmed bot command",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
// println!("Going for botlock"); // println!("Going for botlock");
// Log::trace("Going for botlock"); // Log::trace("Going for botlock");
botlog::trace("Going for botlock", botlog::trace(
"Going for botlock",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
let botlock = bot.read().await; let botlock = bot.read().await;
// println!("Going for identity"); // println!("Going for identity");
// Log::trace("Going for identity"); // Log::trace("Going for identity");
botlog::trace("Going for identity", botlog::trace(
"Going for identity",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
let id = botlock.get_identity(); let id = botlock.get_identity();
@ -705,12 +701,14 @@ impl BotInstance
let mut id = id.write().await; let mut id = id.write().await;
// println!("Unlocking identity"); // println!("Unlocking identity");
// Log::trace("Unlocking identity"); // Log::trace("Unlocking identity");
botlog::trace("Unpacking identity", botlog::trace(
"Unpacking identity",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
let (a, b) =
let (a,b) = id.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await; id.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await;
// // [-] #todo : need ot add functionality around here to do an o7 when a mod has been promoted => Preferring to do this outside the mutex // // [-] #todo : need ot add functionality around here to do an o7 when a mod has been promoted => Preferring to do this outside the mutex
// if let ChangeResult::Success(b) = b { // if let ChangeResult::Success(b) = b {
// // let b = b.to_lowercase(); // // let b = b.to_lowercase();
@ -723,29 +721,36 @@ impl BotInstance
}; };
// println!("Checking if permissible"); // println!("Checking if permissible");
Log::trace("Checking if permissible"); Log::trace("Checking if permissible");
botlog::trace("Checking if permissible", botlog::trace(
"Checking if permissible",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
let (eval, rolechange) = eval; let (eval, rolechange) = eval;
if let ChangeResult::Success(b) = rolechange { if let ChangeResult::Success(b) = rolechange {
if b.to_lowercase()
if b.to_lowercase().contains(&"Auto Promoted Mod".to_lowercase()) { .contains(&"Auto Promoted Mod".to_lowercase())
botlog::notice("Assigning Mod UserRole to Mod", {
Some("botinstance > listener_main_prvmsg()".to_string()), Some(&msg)); botlog::notice(
"Assigning Mod UserRole to Mod",
Some("botinstance > listener_main_prvmsg()".to_string()),
Some(&msg),
);
// println!("Read() lock Bot"); // println!("Read() lock Bot");
// Log::trace("Read() lock Bot"); // Log::trace("Read() lock Bot");
botlog::trace("Read() lock Bot", botlog::trace(
"Read() lock Bot",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
let botlock = bot.read().await; let botlock = bot.read().await;
let outstr = "o7 a Mod. I kneel to serve! pepeKneel ".to_string(); let outstr =
"o7 a Mod. I kneel to serve! pepeKneel ".to_string();
(*botlock).botmgrs.chat.say_in_reply_to(msg, outstr).await; (*botlock).botmgrs.chat.say_in_reply_to(msg, outstr).await;
} }
} }
@ -753,69 +758,61 @@ impl BotInstance
Permissible::Allow => { Permissible::Allow => {
// println!("Executed as permissible"); // println!("Executed as permissible");
// Log::debug("Executed as permissible"); // Log::debug("Executed as permissible");
botlog::debug("Executed as permissible", botlog::debug(
"Executed as permissible",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
let a = Arc::clone(&bot); let a = Arc::clone(&bot);
c.execute(a, msg.clone()).await; c.execute(a, msg.clone()).await;
// println!("exit out of execution"); // println!("exit out of execution");
// Log::trace("exit out of execution"); // Log::trace("exit out of execution");
botlog::trace("exit out of execution", botlog::trace(
"exit out of execution",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
} }
Permissible::Block => { Permissible::Block => {
// println!("User Not allowed to run command"); // println!("User Not allowed to run command");
// Log::info("User Not allowed to run command"); // Log::info("User Not allowed to run command");
botlog::info("User Not allowed to run command", botlog::info(
"User Not allowed to run command",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
}, );
// _ => (), } // _ => (),
}; };
};
} }
}
},
crate::core::botmodules::BotAction::L(l) => { crate::core::botmodules::BotAction::L(l) => {
let a = Arc::clone(&bot); let a = Arc::clone(&bot);
l.execute(a, msg.clone()).await; l.execute(a, msg.clone()).await;
}, }
_ => (), _ => (),
}; };
} }
}; }
// // [ ] There should be a BotCommand Listener to check for prefixes ran // // [ ] There should be a BotCommand Listener to check for prefixes ran
// println!("End of Separate Listener Main prvmsg"); // println!("End of Separate Listener Main prvmsg");
// Log::trace("End of Separate Listener Main prvmsg"); // Log::trace("End of Separate Listener Main prvmsg");
botlog::trace("End of Separate Listener Main prvmsg", botlog::trace(
"End of Separate Listener Main prvmsg",
Some("BotInstance > listener_main_prvmsg()".to_string()), Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(&msg)); Some(&msg),
);
// self // self
// bot // bot
Log::flush(); Log::flush();
} }
} }
// ====================================== // ======================================
// ====================================== // ======================================
// ====================================== // ======================================
@ -823,10 +820,6 @@ impl BotInstance
// UNIT TEST MODULES // UNIT TEST MODULES
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
fn always() { fn always() {

View file

@ -1,4 +1,4 @@
use core::{panic}; use core::panic;
use std::error::Error; use std::error::Error;
use std::collections::HashMap; use std::collections::HashMap;
@ -15,15 +15,11 @@ use std::future::Future;
// Important to use tokios Mutex here since std Mutex doesn't work with async functions // Important to use tokios Mutex here since std Mutex doesn't work with async functions
use tokio::sync::Mutex; use tokio::sync::Mutex;
use crate::core::botinstance::{self, botlog, BotInstance}; use crate::core::botinstance::{self, botlog, BotInstance};
use std::rc::Rc; use std::rc::Rc;
// use tokio::sync::RwLock; // use tokio::sync::RwLock;
use async_trait::async_trait; use async_trait::async_trait;
use casual_logger::{Level, Log}; use casual_logger::{Level, Log};
@ -62,13 +58,12 @@ pub use ModType::BotModule;
use botinstance::ChType; use botinstance::ChType;
pub use ChType::Channel;
use twitch_irc::message::PrivmsgMessage; use twitch_irc::message::PrivmsgMessage;
pub use ChType::Channel;
use self::bot_actions::actions_util; use self::bot_actions::actions_util;
use self::bot_actions::actions_util::BotAR; use self::bot_actions::actions_util::BotAR;
#[derive(Debug)] #[derive(Debug)]
enum StatusLvl { enum StatusLvl {
Instance, Instance,
@ -82,30 +77,24 @@ pub enum ModStatusType {
} }
// #[derive(Clone)] // #[derive(Clone)]
pub enum BotAction pub enum BotAction {
{
C(BotCommand), C(BotCommand),
L(Listener), L(Listener),
R(Routine), R(Routine),
} }
impl BotAction { impl BotAction {
pub async fn execute(&self, m: BotAR, n: PrivmsgMessage) -> () {
pub async fn execute(&self,m:BotAR,n:PrivmsgMessage) -> ()
{
match self { match self {
BotAction::L(a) => a.execute(m, n).await, BotAction::L(a) => a.execute(m, n).await,
BotAction::C(a) => a.execute(m, n).await, BotAction::C(a) => a.execute(m, n).await,
_ => (), _ => (),
} }
} }
} }
#[async_trait] #[async_trait]
pub trait BotActionTrait pub trait BotActionTrait {
{
async fn add_to_bot(self, bot: BotInstance); async fn add_to_bot(self, bot: BotInstance);
async fn add_to_modmgr(self, modmgr: Arc<ModulesManager>); async fn add_to_modmgr(self, modmgr: Arc<ModulesManager>);
} }
@ -121,43 +110,40 @@ pub struct BotCommand {
pub required_roles: Vec<identity::UserRole>, pub required_roles: Vec<identity::UserRole>,
} }
impl BotCommand impl BotCommand {
{
pub async fn execute(&self, m: BotAR, n: PrivmsgMessage) -> () { pub async fn execute(&self, m: BotAR, n: PrivmsgMessage) -> () {
((*self).exec_body)(m, n).await; ((*self).exec_body)(m, n).await;
} }
} }
#[async_trait] #[async_trait]
impl BotActionTrait for BotCommand impl BotActionTrait for BotCommand {
{
async fn add_to_bot(self, bot: BotInstance) { async fn add_to_bot(self, bot: BotInstance) {
self.add_to_modmgr(bot.botmodules).await; self.add_to_modmgr(bot.botmodules).await;
} }
// async fn add_to_modmgr(self, modmgr:Arc<Mutex<ModulesManager>>) { // async fn add_to_modmgr(self, modmgr:Arc<Mutex<ModulesManager>>) {
async fn add_to_modmgr(self, modmgr: Arc<ModulesManager>) { async fn add_to_modmgr(self, modmgr: Arc<ModulesManager>) {
modmgr.add_botaction(self.module.clone(), BotAction::C(self)).await modmgr
.add_botaction(self.module.clone(), BotAction::C(self))
.await
} }
} }
pub mod bot_actions { pub mod bot_actions {
pub mod actions_util { pub mod actions_util {
use std::future::Future;
use std::boxed::Box; use std::boxed::Box;
use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use std::rc::Rc; use std::rc::Rc;
use crate::core::botinstance::{BotInstance, BotManagers, Chat}; use crate::core::botinstance::{BotInstance, BotManagers, Chat};
use twitch_irc::message::PrivmsgMessage;
use std::cell::RefCell; use std::cell::RefCell;
use std::sync::{Arc}; use std::sync::Arc;
use twitch_irc::message::PrivmsgMessage;
// use futures::lock::Mutex; // use futures::lock::Mutex;
// Important to use tokios Mutex here since std Mutex doesn't work with async functions // Important to use tokios Mutex here since std Mutex doesn't work with async functions
use tokio::sync::{Mutex, RwLock}; use tokio::sync::{Mutex, RwLock};
@ -165,47 +151,42 @@ pub mod bot_actions {
pub type BotAM = Arc<Mutex<BotInstance>>; pub type BotAM = Arc<Mutex<BotInstance>>;
pub type BotAR = Arc<RwLock<BotInstance>>; pub type BotAR = Arc<RwLock<BotInstance>>;
pub type ExecBody = Box<dyn Fn(BotAR,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>; pub type ExecBody = Box<
dyn Fn(BotAR, PrivmsgMessage) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,
>;
pub fn asyncbox<T>(f: fn(BotAR, PrivmsgMessage) -> T) -> ExecBody pub fn asyncbox<T>(f: fn(BotAR, PrivmsgMessage) -> T) -> ExecBody
where where
T: Future<Output=()> + Send + 'static T: Future<Output = ()> + Send + 'static,
{ {
Box::new(move |a, b| Box::pin(f(a, b))) Box::new(move |a, b| Box::pin(f(a, b)))
} }
} }
} }
pub struct Listener {
pub struct Listener
{
pub module: ModType, pub module: ModType,
pub name: String, pub name: String,
pub exec_body: bot_actions::actions_util::ExecBody, pub exec_body: bot_actions::actions_util::ExecBody,
pub help : String pub help: String,
} }
impl Listener impl Listener {
{
pub async fn execute(&self, m: BotAR, n: PrivmsgMessage) -> () { pub async fn execute(&self, m: BotAR, n: PrivmsgMessage) -> () {
((*self).exec_body)(m, n).await; ((*self).exec_body)(m, n).await;
} }
} }
#[async_trait] #[async_trait]
impl BotActionTrait for Listener impl BotActionTrait for Listener {
{
async fn add_to_bot(self, bot: BotInstance) { async fn add_to_bot(self, bot: BotInstance) {
// println!("Adding action to bot"); // println!("Adding action to bot");
// Log::trace("Adding action to bot"); // Log::trace("Adding action to bot");
botinstance::botlog::trace("Adding action to bot", botinstance::botlog::trace(
"Adding action to bot",
Some("BotModules > BotActionTrait > add_to_bot()".to_string()), Some("BotModules > BotActionTrait > add_to_bot()".to_string()),
None); None,
);
self.add_to_modmgr(bot.botmodules).await; self.add_to_modmgr(bot.botmodules).await;
} }
@ -213,24 +194,24 @@ impl BotActionTrait for Listener
// let modmgr = *modmgr.lock().await; // let modmgr = *modmgr.lock().await;
// println!("Adding action to module manager"); // println!("Adding action to module manager");
// Log::trace("Adding action to module manager"); // Log::trace("Adding action to module manager");
botinstance::botlog::trace("Adding action to module manager", botinstance::botlog::trace(
"Adding action to module manager",
Some("BotModules > BotActionTrait > add_to_bot()".to_string()), Some("BotModules > BotActionTrait > add_to_bot()".to_string()),
None); None,
);
modmgr.add_botaction(self.module.clone(), BotAction::L(self)).await; modmgr
.add_botaction(self.module.clone(), BotAction::L(self))
.await;
} }
} }
#[derive(Debug)] #[derive(Debug)]
struct Routine {} struct Routine {}
// #[derive(Clone)] // #[derive(Clone)]
pub struct ModulesManager pub struct ModulesManager {
{
statusdb: Arc<RwLock<HashMap<ModType, Vec<ModStatusType>>>>, statusdb: Arc<RwLock<HashMap<ModType, Vec<ModStatusType>>>>,
pub botactions: Arc<RwLock<HashMap<ModType, Vec<BotAction>>>>, pub botactions: Arc<RwLock<HashMap<ModType, Vec<BotAction>>>>,
} }
@ -249,13 +230,8 @@ botactions
*/ */
impl ModulesManager impl ModulesManager {
{ pub async fn init() -> Arc<ModulesManager> {
pub async fn init() -> Arc<ModulesManager>
{
let m = HashMap::new(); let m = HashMap::new();
let act = HashMap::new(); let act = HashMap::new();
@ -267,22 +243,21 @@ impl ModulesManager
// :: [x] initialize core modules // :: [x] initialize core modules
// println!("ModulesManager > init() > Adding modules"); // println!("ModulesManager > init() > Adding modules");
botlog::debug("ModulesManager > init() > Adding modules", botlog::debug(
"ModulesManager > init() > Adding modules",
Some("ModulesManager > init()".to_string()), Some("ModulesManager > init()".to_string()),
None None,
); );
let mgra = Arc::new(mgr); let mgra = Arc::new(mgr);
crate::core::identity::init(Arc::clone(&mgra)).await; crate::core::identity::init(Arc::clone(&mgra)).await;
crate::modules::init(Arc::clone(&mgra)).await; crate::modules::init(Arc::clone(&mgra)).await;
// println!(">> Modules Manager : End of Init"); // println!(">> Modules Manager : End of Init");
botlog::trace(">> Modules Manager : End of Init", botlog::trace(
">> Modules Manager : End of Init",
Some("ModulesManager > init()".to_string()), Some("ModulesManager > init()".to_string()),
None None,
); );
mgra mgra
@ -299,29 +274,26 @@ impl ModulesManager
ModStatusType::Enabled(StatusLvl::Instance) ModStatusType::Enabled(StatusLvl::Instance)
} }
pub fn togglestatus(&self, _: ModType, _: ChType) -> ModStatusType { pub fn togglestatus(&self, _: ModType, _: ChType) -> ModStatusType {
// enables or disables based on current status // enables or disables based on current status
ModStatusType::Enabled(StatusLvl::Instance) ModStatusType::Enabled(StatusLvl::Instance)
} }
pub fn setstatus(&self, _: ModType, _: ModStatusType) -> Result<&str, Box<dyn Error>> { pub fn setstatus(&self, _: ModType, _: ModStatusType) -> Result<&str, Box<dyn Error>> {
// sets the status based given ModSatusType // sets the status based given ModSatusType
// e.g., b.setstatus(BodModule("GambaCore"), Enabled(Channel("modulatingforce"))).expect("ERROR") // e.g., b.setstatus(BodModule("GambaCore"), Enabled(Channel("modulatingforce"))).expect("ERROR")
Ok("") Ok("")
} }
pub async fn add_botaction(&self, in_module: ModType, in_action: BotAction) { pub async fn add_botaction(&self, in_module: ModType, in_action: BotAction) {
// println!("Add botaction called"); // println!("Add botaction called");
botlog::trace("Add botaction called", botlog::trace(
"Add botaction called",
Some("ModulesManager > init()".to_string()), Some("ModulesManager > init()".to_string()),
None None,
); );
/* /*
adds a BotAction to the Modules Manager - This will require a BotModule passed as well adds a BotAction to the Modules Manager - This will require a BotModule passed as well
This will including the logic of a valid add This will including the logic of a valid add
@ -341,20 +313,15 @@ impl ModulesManager
// help : String::from("This will listen and react to sock randomly"), // help : String::from("This will listen and react to sock randomly"),
// }; // };
// As a Demonstration, the listener's Module is added and Enabled at Instance level // As a Demonstration, the listener's Module is added and Enabled at Instance level
// [x] Before Adding, validate the following : // [x] Before Adding, validate the following :
// - If BotAction to Add is a BotCommand , In Module Manager DB (botactions), // - If BotAction to Add is a BotCommand , In Module Manager DB (botactions),
// Check All Other BotAction Command Names & Aliases to ensure they don't conflict // Check All Other BotAction Command Names & Aliases to ensure they don't conflict
async fn find_conflict_module(mgr:& ModulesManager, act:& BotAction) -> Option<ModType> async fn find_conflict_module(mgr: &ModulesManager, act: &BotAction) -> Option<ModType> {
{
// Some(BotModule(String::from("GambaCore"))) // Some(BotModule(String::from("GambaCore")))
// match act { // match act {
// BotAction::C(c) => { // BotAction::C(c) => {
// Some(BotModule(String::from("GambaCore"))) // Some(BotModule(String::from("GambaCore")))
@ -364,15 +331,12 @@ impl ModulesManager
// } // }
if let BotAction::C(incmd) = act { if let BotAction::C(incmd) = act {
// let n = & mgr.botactions; // let n = & mgr.botactions;
let d = mgr.botactions.read().await; let d = mgr.botactions.read().await;
let d = &(*d); let d = &(*d);
for (module, moduleactions) in d { for (module, moduleactions) in d {
for modact in moduleactions.iter() { for modact in moduleactions.iter() {
if let BotAction::C(dbcmd) = &modact { if let BotAction::C(dbcmd) = &modact {
// At this point, there is an command incmd and looked up dbcmd // At this point, there is an command incmd and looked up dbcmd
@ -393,20 +357,16 @@ impl ModulesManager
// Returning State - with the identified module // Returning State - with the identified module
// return Some((module.clone(),BotAction::C(dbcmd))); // return Some((module.clone(),BotAction::C(dbcmd)));
return Some(module.clone()); // works return Some(module.clone()); // works
} }
} }
// [x] Then do the same check except for each c.alias // [x] Then do the same check except for each c.alias
for inalias in &incmd.alias { for inalias in &incmd.alias {
if inalias.to_lowercase() == dbcmd.command.to_lowercase() { if inalias.to_lowercase() == dbcmd.command.to_lowercase() {
// Returning State - with the identified module // Returning State - with the identified module
// return Some((module.clone(),BotAction::C(dbcmd))); // return Some((module.clone(),BotAction::C(dbcmd)));
return Some(module.clone()); // works return Some(module.clone()); // works
} }
for a in &dbcmd.alias { for a in &dbcmd.alias {
@ -414,25 +374,18 @@ impl ModulesManager
// Returning State - with the identified module // Returning State - with the identified module
// return Some((module.clone(),BotAction::C(dbcmd))); // return Some((module.clone(),BotAction::C(dbcmd)));
return Some(module.clone()); // works return Some(module.clone()); // works
} }
} }
}
} }
} }
}
} }
// return Some(BotModule(String::from("GambaCore"))) // return Some(BotModule(String::from("GambaCore")))
} }
// for all other scenarios (e.g., Listener, Routine), find no conflicts // for all other scenarios (e.g., Listener, Routine), find no conflicts
None None
} }
// if let probmod = find_conflict_module(&self, &in_action) { // if let probmod = find_conflict_module(&self, &in_action) {
@ -441,7 +394,10 @@ impl ModulesManager
// } // }
match find_conflict_module(&self, &in_action).await { match find_conflict_module(&self, &in_action).await {
// Some(c) => panic!("ERROR: Could not add {:?} ; there was a conflict with existing module {:?}", in_action , c ), // Some(c) => panic!("ERROR: Could not add {:?} ; there was a conflict with existing module {:?}", in_action , c ),
Some(c) => panic!("ERROR: Could not add module; there was a conflict with existing module {:?}", c ), Some(c) => panic!(
"ERROR: Could not add module; there was a conflict with existing module {:?}",
c
),
None => (), None => (),
} }
@ -463,21 +419,19 @@ impl ModulesManager
modactions.push(in_action); modactions.push(in_action);
// println!(">> Modules Manager : Called Add bot Action"); // println!(">> Modules Manager : Called Add bot Action");
botlog::trace(">> Modules Manager : Called Add bot Action", botlog::trace(
">> Modules Manager : Called Add bot Action",
Some("ModulesManager > init()".to_string()), Some("ModulesManager > init()".to_string()),
None None,
); );
// println!("add_botaction - botactions size : {}",modactions.len()); // println!("add_botaction - botactions size : {}",modactions.len());
botlog::trace(&format!("add_botaction - botactions size : {}",modactions.len()), botlog::trace(
&format!("add_botaction - botactions size : {}", modactions.len()),
Some("ModulesManager > init()".to_string()), Some("ModulesManager > init()".to_string()),
None None,
); );
} }
fn statuscleanup(&self, _: Option<ChType>) -> () { fn statuscleanup(&self, _: Option<ChType>) -> () {
// internal cleans up statusdb . For example : // internal cleans up statusdb . For example :
// - remove redudancies . If we see several Enabled("m"), only keep 1x // - remove redudancies . If we see several Enabled("m"), only keep 1x
@ -487,7 +441,4 @@ impl ModulesManager
// Passing None to chnl may be a heavy operation, as this will review and look at the whole table // Passing None to chnl may be a heavy operation, as this will review and look at the whole table
() ()
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,10 +1,8 @@
use std::time::Instant; use std::time::Instant;
const TIME_THRESHOLD_S: u64 = 30; const TIME_THRESHOLD_S: u64 = 30;
const MSG_THRESHOLD: u32 = 20; const MSG_THRESHOLD: u32 = 20;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RateLimiter { pub struct RateLimiter {
timer: Instant, timer: Instant,
@ -16,7 +14,6 @@ pub enum LimiterResp {
Skip, // as outside of rate limits Skip, // as outside of rate limits
} }
impl RateLimiter { impl RateLimiter {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
@ -26,7 +23,6 @@ impl RateLimiter {
} }
pub fn check_limiter(&mut self) -> LimiterResp { pub fn check_limiter(&mut self) -> LimiterResp {
if self.timer.elapsed().as_secs() >= TIME_THRESHOLD_S { if self.timer.elapsed().as_secs() >= TIME_THRESHOLD_S {
// # [x] elapsed >= TIME_THRESHOLD_S // # [x] elapsed >= TIME_THRESHOLD_S
self.timer = Instant::now(); self.timer = Instant::now();

View file

@ -1,3 +1,2 @@
pub mod core; pub mod core;
pub mod modules; pub mod modules;

View file

@ -1,5 +1,3 @@
// pub mod core; // pub mod core;
// pub mod modules; // pub mod modules;
//use myLib; //use myLib;
@ -13,15 +11,14 @@ use botLib::core::botinstance::{self,BotInstance};
// use core::botinstance::{self,BotInstance}; // use core::botinstance::{self,BotInstance};
use casual_logger::Extension; use casual_logger::Extension;
use tokio::sync::RwLock;
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::RwLock;
pub type BotAR = Arc<RwLock<BotInstance>>; pub type BotAR = Arc<RwLock<BotInstance>>;
use casual_logger::{Level, Log}; use casual_logger::{Level, Log};
#[tokio::main] #[tokio::main]
pub async fn main() { pub async fn main() {
Log::set_file_ext(Extension::Log); Log::set_file_ext(Extension::Log);
Log::set_level(Level::Trace); Log::set_level(Level::Trace);
// Log::set_level(Level::Notice); // Log::set_level(Level::Notice);
@ -40,22 +37,33 @@ pub async fn main() {
botLib::core::botmodules::BotAction::C(b) => { botLib::core::botmodules::BotAction::C(b) => {
// println!("bot actiions: {}",b.command) // println!("bot actiions: {}",b.command)
// Log::info(&format!("bot actions: {}",b.command)); // Log::info(&format!("bot actions: {}",b.command));
botinstance::botlog::info(&format!("bot actions: {}",b.command), Some("main()".to_string()), None); botinstance::botlog::info(
}, &format!("bot actions: {}", b.command),
Some("main()".to_string()),
None,
);
}
botLib::core::botmodules::BotAction::L(l) => { botLib::core::botmodules::BotAction::L(l) => {
// println!("bot actiions: {}",l.name) // println!("bot actiions: {}",l.name)
// Log::info(&format!("bot actions: {}",l.name)); // Log::info(&format!("bot actions: {}",l.name));
botinstance::botlog::info(&format!("bot actions: {}",l.name), Some("main()".to_string()), None); botinstance::botlog::info(
}, &format!("bot actions: {}", l.name),
Some("main()".to_string()),
None,
);
}
_ => { _ => {
// println!("Not a valid match??") // println!("Not a valid match??")
// Log::info("Not a valid match??"); // Log::info("Not a valid match??");
botinstance::botlog::info("Not a valid match??", Some("main()".to_string()), None); botinstance::botlog::info(
}, "Not a valid match??",
Some("main()".to_string()),
None,
);
}
}
} }
} }
};
// println!("Starting runner.."); // println!("Starting runner..");
// Log::notice("Starting Bot Runner"); // Log::notice("Starting Bot Runner");
@ -71,5 +79,4 @@ pub async fn main() {
// panic!("{}",Log::fatal("ERROR : EXIT Game loop")); // panic!("{}",Log::fatal("ERROR : EXIT Game loop"));
let a = botinstance::botlog::fatal("ERROR : EXIT Game loop", Some("main()".to_string()), None); let a = botinstance::botlog::fatal("ERROR : EXIT Game loop", Some("main()".to_string()), None);
panic!("{}", a); panic!("{}", a);
} }

View file

@ -10,18 +10,16 @@ pub use crate::core::botmodules::ModulesManager;
// use crate::core::botinstance; // use crate::core::botinstance;
pub use crate::core::botinstance::BotInstance; pub use crate::core::botinstance::BotInstance;
use std::sync::Arc;
use futures::lock::Mutex; use futures::lock::Mutex;
use std::sync::Arc;
// [ ] Load submodules // [ ] Load submodules
mod experiments; mod experiments;
// [ ] init() function that accepts bot instance - this is passed to init() on submodules // [ ] init() function that accepts bot instance - this is passed to init() on submodules
pub async fn init(mgr:Arc<ModulesManager>) pub async fn init(mgr: Arc<ModulesManager>) {
{
// Modules initializer loads modules into the bot // Modules initializer loads modules into the bot
// this is achieved by calling submodules that also have fn init() defined // this is achieved by calling submodules that also have fn init() defined

View file

@ -1,4 +1,3 @@
/* /*
Submodules - Submodules -
@ -14,8 +13,8 @@
use std::future::Future; use std::future::Future;
use crate::core::botmodules::{ModulesManager,Listener,BotModule,BotActionTrait, BotCommand};
use crate::core::botmodules::bot_actions::actions_util::{self, BotAR}; use crate::core::botmodules::bot_actions::actions_util::{self, BotAR};
use crate::core::botmodules::{BotActionTrait, BotCommand, BotModule, Listener, ModulesManager};
use crate::core::botinstance::{self, BotInstance, ChType}; use crate::core::botinstance::{self, BotInstance, ChType};
use futures::lock::Mutex; use futures::lock::Mutex;
@ -23,19 +22,14 @@ use twitch_irc::message::PrivmsgMessage;
use crate::core::identity; use crate::core::identity;
use rand::Rng; use rand::Rng;
use std::rc::Rc; use std::rc::Rc;
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
// pub fn init(mgr:&mut ModulesManager) // pub fn init(mgr:&mut ModulesManager)
pub async fn init(mgr:Arc<ModulesManager>) pub async fn init(mgr: Arc<ModulesManager>) {
{
// BotCommand { // BotCommand {
// module : BotModule(String::from("experiments 004")), // module : BotModule(String::from("experiments 004")),
// command : String::from("test1"), // command call name // command : String::from("test1"), // command call name
@ -48,43 +42,35 @@ pub async fn init(mgr:Arc<ModulesManager>)
// ], // ],
// }.add_to_modmgr(mgr); // }.add_to_modmgr(mgr);
let botc1 = BotCommand { let botc1 = BotCommand {
module: BotModule(String::from("experiments001")), module: BotModule(String::from("experiments001")),
command: String::from("test1"), // command call name command: String::from("test1"), // command call name
alias: vec![String::from("tester1"), String::from("testy1")], // String of alternative names alias: vec![String::from("tester1"), String::from("testy1")], // String of alternative names
exec_body: actions_util::asyncbox(testy), exec_body: actions_util::asyncbox(testy),
help: String::from("Test Command tester"), help: String::from("Test Command tester"),
required_roles : vec![ required_roles: vec![identity::UserRole::BotAdmin],
identity::UserRole::BotAdmin
],
}; };
botc1.add_to_modmgr(Arc::clone(&mgr)).await; botc1.add_to_modmgr(Arc::clone(&mgr)).await;
let list1 = Listener { let list1 = Listener {
module: BotModule(String::from("experiments001")), module: BotModule(String::from("experiments001")),
name: String::from("GoodGirl Listener"), name: String::from("GoodGirl Listener"),
exec_body: actions_util::asyncbox(good_girl), exec_body: actions_util::asyncbox(good_girl),
help : String::from("") help: String::from(""),
}; };
list1.add_to_modmgr(Arc::clone(&mgr)).await; list1.add_to_modmgr(Arc::clone(&mgr)).await;
} }
async fn good_girl(mut bot: BotAR, msg: PrivmsgMessage) {
async fn good_girl(mut bot:BotAR,msg:PrivmsgMessage)
{
// println!("In GoodGirl() Listener"); // println!("In GoodGirl() Listener");
// Change below from debug to trace if required later // Change below from debug to trace if required later
botinstance::botlog::debug("In GoodGirl() Listener", botinstance::botlog::debug(
"In GoodGirl() Listener",
Some("experiments > goodgirl()".to_string()), Some("experiments > goodgirl()".to_string()),
Some(&msg)); Some(&msg),
);
//println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); //println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text);
@ -92,37 +78,42 @@ async fn good_girl(mut bot:BotAR,msg:PrivmsgMessage)
// - For example gen_ratio(2,3) is 2 out of 3 or 0.67% (numerator,denomitator) // - For example gen_ratio(2,3) is 2 out of 3 or 0.67% (numerator,denomitator)
// - More Info : https://rust-random.github.io/rand/rand/trait.Rng.html#method.gen_ratio // - More Info : https://rust-random.github.io/rand/rand/trait.Rng.html#method.gen_ratio
if msg.sender.name.to_lowercase() == "ModulatingForce".to_lowercase()
if msg.sender.name.to_lowercase() == "ModulatingForce".to_lowercase() || msg.sender.name.to_lowercase() == "mzNToRi".to_lowercase() // && msg.message_text.contains("GoodGirl") || msg.sender.name.to_lowercase() == "mzNToRi".to_lowercase()
// && msg.message_text.contains("GoodGirl")
{ {
// chat.say_in_reply_to(&msg,String::from("GoodGirl")).await; // chat.say_in_reply_to(&msg,String::from("GoodGirl")).await;
//if rng.gen_ratio(1,5) { //if rng.gen_ratio(1,5) {
// println!("In GoodGirl() > Pausechamp"); // println!("In GoodGirl() > Pausechamp");
botinstance::botlog::debug("In GoodGirl() > Pausechamp", botinstance::botlog::debug(
"In GoodGirl() > Pausechamp",
Some("experiments > goodgirl()".to_string()), Some("experiments > goodgirl()".to_string()),
Some(&msg)); Some(&msg),
);
let rollwin = rand::thread_rng().gen_ratio(1, 8); let rollwin = rand::thread_rng().gen_ratio(1, 8);
if rollwin { if rollwin {
// println!("In GoodGirl() > Win"); // println!("In GoodGirl() > Win");
botinstance::botlog::debug("In GoodGirl() > Win", botinstance::botlog::debug(
"In GoodGirl() > Win",
Some("experiments > goodgirl()".to_string()), Some("experiments > goodgirl()".to_string()),
Some(&msg)); Some(&msg),
);
let a = Arc::clone(&bot); let a = Arc::clone(&bot);
let botlock = a.read().await; let botlock = a.read().await;
botlock.botmgrs.chat.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await; botlock
.botmgrs
.chat
.say_in_reply_to(&msg, String::from("GoodGirl xdd "))
.await;
}
}
} }
async fn testy(mut _chat: BotAR, msg: PrivmsgMessage) {
}
}
async fn testy(mut _chat:BotAR,msg:PrivmsgMessage)
{
println!("testy triggered!"); // NOTE : This test function intends to print (e.g., to stdout) at fn call println!("testy triggered!"); // NOTE : This test function intends to print (e.g., to stdout) at fn call
botinstance::botlog::debug("testy triggered!", botinstance::botlog::debug(
"testy triggered!",
Some("experiments > testy()".to_string()), Some("experiments > testy()".to_string()),
Some(&msg)); Some(&msg),
);
} }