(init) botlog module

This commit is contained in:
ModulatingForce 2024-02-13 07:54:35 -05:00
commit eb6c5ec58c
8 changed files with 382 additions and 68 deletions

View file

@ -33,7 +33,7 @@ use crate::core::ratelimiter;
use crate::core::botmodules;
use crate::core::botmodules::ModulesManager;
use crate::core::identity::{IdentityManager,Permissible};
use crate::core::identity::{IdentityManager,Permissible,ChangeResult};
use std::rc::Rc;
use std::cell::RefCell;
@ -49,6 +49,51 @@ use core::borrow::Borrow;
use super::botmodules::bot_actions::actions_util::BotAR;
use casual_logger::{Level,Log};
pub mod botlog {
/*
Module intends to add some layers to logging with the module user only requiring to pass :
- String Log message
- Option<String> - Code Module
- Option<PrivmsgMessage> - this is used to parse out Chatter & Channel into the logs
*/
use casual_logger::{Level,Log};
use twitch_irc::message::PrivmsgMessage;
// trace, debug, info, notice, warn, error, fatal
fn trace(in_msg:&str,module:Option<String>,prvmsg:Option<PrivmsgMessage>,) -> () {
}
fn debug(prvmsg:Option<PrivmsgMessage>,in_msg:&str) -> () {
}
fn info(prvmsg:Option<PrivmsgMessage>,in_msg:&str) -> () {
}
fn notice(prvmsg:Option<PrivmsgMessage>,in_msg:&str) -> () {
}
fn warn(prvmsg:Option<PrivmsgMessage>,in_msg:&str) -> () {
}
fn error(prvmsg:Option<PrivmsgMessage>,in_msg:&str) -> () {
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum ChType {
Channel(String),
@ -110,15 +155,18 @@ impl Chat {
}
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"));
contextratelimiter.increment_counter();
println!("{:?}",self.ratelimiters);
// println!("{:?}",self.ratelimiters);
Log::trace(&format!("{:?}",self.ratelimiters));
},
ratelimiter::LimiterResp::Skip => {
(); // do nothing otherwise
}
}
Log::flush();
}
async fn say(&self, _:String, _:String) -> () {
@ -278,29 +326,42 @@ impl BotInstance
ServerMessage::Notice(msg) => {
match &msg.channel_login {
Some(chnl) => println!("NOTICE : (#{}) {}", chnl, msg.message_text),
None => println!("NOTICE : {}", msg.message_text),
Some(chnl) => {
// println!("NOTICE : (#{}) {}", chnl, msg.message_text)
Log::notice(&format!("NOTICE : (#{}) {}", chnl, msg.message_text));
},
None => {
// println!("NOTICE : {}", msg.message_text);
Log::notice(&format!("NOTICE : {}", msg.message_text));
},
}
}
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));
println!("Privmsg section");
// println!("Privmsg section");
Log::debug(&format!("Privmsg section"));
BotInstance::listener_main_prvmsg(Arc::clone(&bot), &msg).await;
BotInstance::listener_main_prvmsg(Arc::clone(&bot), &msg).await;
},
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));
},
ServerMessage::Join(msg) => {
println!("JOINED: {}", msg.channel_login);
// println!("JOINED: {}", msg.channel_login);
Log::notice(&format!("JOINED: {}", msg.channel_login));
},
ServerMessage::Part(msg) => {
println!("PARTED: {}", msg.channel_login);
// println!("PARTED: {}", msg.channel_login);
Log::notice(&format!("PARTED: {}", msg.channel_login));
},
_ => {}
}
};
Log::flush();
}
});
@ -342,7 +403,8 @@ impl BotInstance
pub async fn listener_main_prvmsg(bot:BotAR,msg:&PrivmsgMessage) -> () {
println!(">> Inner listenermain_prvmsg()");
// println!(">> Inner listenermain_prvmsg()");
Log::trace(">> Inner listenermain_prvmsg()");
// let a = a;
// println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text);
@ -353,20 +415,24 @@ impl BotInstance
let hacts = Arc::clone(&botlock.botmodules.botactions);
// let hacts = 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()));
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");
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");
// let bot = bot;
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");
let _act = match a {
@ -385,7 +451,8 @@ impl BotInstance
// println!("args : {v}");
// }
println!("Reviewing internal commands");
// println!("Reviewing internal commands");
Log::trace("Reviewing internal commands");
let inpt = msg.message_text.split("\n").next().expect("ERROR during BotCommand");
let inpt = msg.message_text.split(" ").next().expect("ERROR during BotCommand");
@ -413,29 +480,60 @@ impl BotInstance
}
if confirmed_bot_command {
println!("Confirmed bot command");
// println!("Confirmed bot command");
Log::debug("Confirmed bot command");
println!("Going for botlock");
// println!("Going for botlock");
Log::trace("Going for botlock");
let botlock = bot.read().await;
println!("Going for identity");
// println!("Going for identity");
Log::trace("Going for identity");
let id = botlock.get_identity();
let eval = {
let mut id = id.write().await;
println!("Unlocking identity");
id.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await
// println!("Unlocking identity");
Log::trace("Unlocking identity");
let (a,b) = 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
// if let ChangeResult::Success(b) = b {
// // let b = b.to_lowercase();
// // let b = b.contains(&"Auto Promoted Mod".to_lowercase());
// if b.to_lowercase().contains(&"Auto Promoted Mod".to_lowercase()) {
// let chat =
// }
// }
(a,b)
};
println!("Checking if permissible");
// println!("Checking if permissible");
Log::trace("Checking if permissible");
let (eval , rolechange) = eval;
if let ChangeResult::Success(b) = rolechange {
if b.to_lowercase().contains(&"Auto Promoted Mod".to_lowercase()) {
// println!("Read() lock Bot");
Log::trace("Read() lock Bot");
let botlock = bot.read().await;
let outstr = "o7 a Mod. I kneel to serve! pepeKneel ".to_string();
(*botlock).botmgrs.chat.say_in_reply_to(msg, outstr).await;
}
}
match eval {
Permissible::Allow => {
println!("Executed as permissible");
// println!("Executed as permissible");
Log::debug("Executed as permissible");
let a = Arc::clone(&bot);
c.execute(a, msg.clone()).await;
println!("exit out of execution");
// println!("exit out of execution");
Log::trace("exit out of execution");
}
Permissible::Block => {
println!("User Not allowed to run command")
// println!("User Not allowed to run command");
Log::info("User Not allowed to run command");
},
// _ => (),
};
@ -459,11 +557,14 @@ impl BotInstance
// // [ ] 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");
// self
// bot
Log::flush();
}

View file

@ -25,6 +25,7 @@ use std::rc::Rc;
use async_trait::async_trait;
use casual_logger::{Level,Log};
/*
@ -199,13 +200,16 @@ impl BotActionTrait for Listener
{
async fn add_to_bot(self, bot:BotInstance) {
println!("Adding action to bot");
// println!("Adding action to bot");
Log::trace("Adding action to bot");
self.add_to_modmgr(bot.botmodules).await;
}
async fn add_to_modmgr(self, modmgr:Arc<ModulesManager>) {
// let modmgr = *modmgr.lock().await;
println!("Adding action to module manager");
// println!("Adding action to module manager");
Log::trace("Adding action to module manager");
modmgr.add_botaction(self.module.clone(), BotAction::L(self)).await;
}

View file

@ -385,7 +385,7 @@ pub enum ChatBadge {
}
enum ChangeResult {
pub enum ChangeResult {
Success(String),
Failed(String),
NoChange(String),
@ -411,7 +411,7 @@ impl IdentityManager {
// pub fn can_user_run_PRVMSG(self,msg:&PrivmsgMessage,cmdreqroles:Vec<UserRole>) -> Result<Permissible,Box<dyn Error>>
// pub fn can_user_run_PRVMSG(&self,msg:&PrivmsgMessage,cmdreqroles:Vec<UserRole>) -> Permissible
// pub async fn can_user_run_PRVMSG(self,msg:&PrivmsgMessage,cmdreqroles:Vec<UserRole>) -> Permissible
pub async fn can_user_run_PRVMSG(&mut self,msg:&PrivmsgMessage,cmdreqroles:Vec<UserRole>) -> Permissible
pub async fn can_user_run_PRVMSG(&mut self,msg:&PrivmsgMessage,cmdreqroles:Vec<UserRole>) -> (Permissible,ChangeResult)
{
// println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text);
@ -454,6 +454,15 @@ impl IdentityManager {
// cmdreqroles
// ) ;
// return a;
// return self.can_user_run(msg.sender.name.to_owned(),
// ChType::Channel(msg.channel_login.to_owned()),
// sender_badge,
// cmdreqroles
// ).await
// * NOTE : We're preferring to pass the ChangeResult up , where we have access to Chat via BotInstance
// that have more strained chatting rules
return self.can_user_run(msg.sender.name.to_owned(),
ChType::Channel(msg.channel_login.to_owned()),
sender_badge,
@ -465,7 +474,7 @@ impl IdentityManager {
// [ ] Call can_user_run()
// (self,Permissible::Block)
Permissible::Block
(Permissible::Block,ChangeResult::NoChange("".to_string()))
}
@ -475,7 +484,8 @@ impl IdentityManager {
chat_badge:ChatBadge,
cmdreqroles:Vec<UserRole>
// ) -> Result<Permissible,Box<dyn Error>> {
) -> Permissible {
) -> (Permissible,ChangeResult) {
println!{"Checking within can_user_run()"};
/*
canUserRun -
@ -519,10 +529,12 @@ impl IdentityManager {
if cmdreqroles.len() == 0 {
// return Ok(Permissible::Allow)
return Permissible::Allow
return (Permissible::Allow , ChangeResult::NoChange("Command has no required cmdreqroles".to_string()))
}
let mut modrolechange = ChangeResult::NoChange("".to_string());
match chat_badge {
@ -535,7 +547,7 @@ impl IdentityManager {
cmdreqroles.contains(&UserRole::Mod(ChType::Channel(String::new()))) ||
cmdreqroles.contains(&UserRole::SupMod(ChType::Channel(String::new()))) {
// return Ok(Permissible::Allow)
return Permissible::Allow
return (Permissible::Allow , ChangeResult::NoChange("Broadcaster Role".to_string()))
}
},
@ -563,30 +575,29 @@ impl IdentityManager {
usrroles.read().await.contains(&UserRole::SupMod(channelname.clone())) => { // <-- working got to this point
// println!("contains mod : {}", usrroles.read().await.contains(&UserRole::Mod(channelname.clone())));
// println!("contains supmod : {}", usrroles.read().await.contains(&UserRole::SupMod(channelname.clone())));
// if usrroles.read().await.contains(&UserRole::Mod(channelname.clone())) ||
// usrroles.read().await.contains(&UserRole::SupMod(channelname.clone())) {
// Do nothing - this is expected
// Do nothing when theh have a mod badge and have either a supmod or mod badge for the channel
println!("Already a mod in roles");
// let a = &*self;
// let mut lock = a.special_roles_users.write().await;
// println!("lock created > adding with a mod role o7");
// roleslock.get_mut(&usr.to_lowercase())
// // .expect("ERROR")
// .unwrap()
// .write().await
// // .get_mut()
// .push(UserRole::Mod(channelname.clone()));
// println!("debug special roles : {:?}",self.special_roles_users);
}
_ => {
// In the event they have a mod badge , are running a bot command, but don't have a channel mod role yet...
println!("lock created > adding with a mod role o7");
roleslock.get_mut(&usr.to_lowercase())
// .expect("ERROR")
.unwrap()
.write().await
// .get_mut()
.push(UserRole::Mod(channelname.clone()));
let mut roleslock = roleslock;
let mut a = roleslock.get_mut(&usr.to_lowercase()).unwrap();
let mut alock = a.write().await;
alock.push(UserRole::Mod(channelname.clone()));
modrolechange = ChangeResult::Success("Auto Promoted Mod".to_string());
// alock.get_mut(&usr.to_lowercase())
// .get_or_insert_with(|| UserRole::Mod(channelname.clone()))
// // .expect("ERROR")
// .unwrap()
// .write().await
// // .get_mut()
// .push(UserRole::Mod(channelname.clone()));
} // <-- I'm assuming problem got to here
}
@ -612,7 +623,7 @@ impl IdentityManager {
if a.read().await.contains(&UserRole::Mod(channelname.clone())) || a.read().await.contains(&UserRole::SupMod(channelname.clone())){
// return Ok(Permissible::Allow);
println!("Special roles found for user : A mod idenfified ");
return Permissible::Allow
return (Permissible::Allow , modrolechange)
}
}
}
@ -625,7 +636,7 @@ impl IdentityManager {
if let Some(a) = (&*self).special_roles_users.read().await.get(&usr.to_lowercase()) {
if a.read().await.contains(&UserRole::SupMod(channelname.clone())) {
// return Ok(Permissible::Allow);
return Permissible::Allow
return (Permissible::Allow,modrolechange)
}
}
}
@ -641,12 +652,12 @@ impl IdentityManager {
println!("special roles contains BotAdmin: {}",a.read().await.contains(&UserRole::BotAdmin));
if a.read().await.contains(&UserRole::BotAdmin) {
// return Ok(Permissible::Allow);
return Permissible::Allow
return (Permissible::Allow,modrolechange)
}
}
}
Permissible::Block
(Permissible::Block , ChangeResult::NoChange("Not any permissiable condition".to_string()))
}
// pub async fn promote(&mut self,trgchatter:String,channel:Option<ChType>,trg_role:Option<UserRole>) -> ChangeResult {

View file

@ -7,15 +7,23 @@ use std::process::Output;
use crate::core::botinstance::ArcBox;
use crate::core::botinstance::BotInstance;
use casual_logger::Extension;
use tokio::sync::RwLock;
use std::sync::Arc;
pub type BotAR = Arc<RwLock<BotInstance>>;
use casual_logger::{Level,Log};
#[tokio::main]
pub async fn main() {
Log::set_file_ext(Extension::Log);
Log::set_level(Level::Trace);
// Log::set_level(Level::Notice);
let bot = BotInstance::init().await;
Log::debug("Checking bot actions");
let a = Arc::clone(&bot.botmodules.botactions);
let a = a.read().await;
// let a = *a;
@ -23,18 +31,32 @@ pub async fn main() {
for (_,acts) in &*a {
for act in acts {
match act {
crate::core::botmodules::BotAction::C(b) => println!("bot actiions: {}",b.command),
crate::core::botmodules::BotAction::L(l) => println!("bot actiions: {}",l.name),
_ => println!("Not a valid match??"),
crate::core::botmodules::BotAction::C(b) => {
// println!("bot actiions: {}",b.command)
Log::info(&format!("bot actions: {}",b.command));
},
crate::core::botmodules::BotAction::L(l) => {
// println!("bot actiions: {}",l.name)
Log::info(&format!("bot actions: {}",l.name));
},
_ => {
// println!("Not a valid match??")
Log::info("Not a valid match??");
},
}
}
};
println!("Starting runner..");
// println!("Starting runner..");
Log::notice("Starting Bot Runner");
Log::flush();
bot.runner().await;
println!("ERROR : EXIT Game loop");
// println!("ERROR : EXIT Game loop");
// let msg = Log::fatal("ERROR : EXIT Game loop");
panic!("{}",Log::fatal("ERROR : EXIT Game loop"));
}

View file

@ -87,12 +87,12 @@ async fn good_girl(mut bot:BotAR,msg:PrivmsgMessage)
// - More Info : https://rust-random.github.io/rand/rand/trait.Rng.html#method.gen_ratio
if msg.sender.name == "ModulatingForce" || msg.sender.name == "mzNToRi" // && msg.message_text.contains("GoodGirl")
if msg.sender.name.to_lowercase() == "ModulatingForce".to_lowercase() || msg.sender.name.to_lowercase() == "mzNToRi".to_lowercase() // && msg.message_text.contains("GoodGirl")
{
// chat.say_in_reply_to(&msg,String::from("GoodGirl")).await;
//if rng.gen_ratio(1,5) {
println!("In GoodGirl() > Pausechamp");
let rollwin = rand::thread_rng().gen_ratio(1,10);
let rollwin = rand::thread_rng().gen_ratio(1,8);
if rollwin {
println!("In GoodGirl() > Win");
let a = Arc::clone(&bot);