(cont) comments & cleanup

(cont)

cont
This commit is contained in:
ModulatingForce 2024-03-02 09:44:09 -05:00
parent d998e2f290
commit a2747b1ad5
6 changed files with 89 additions and 169 deletions

View file

@ -2,8 +2,3 @@ pub mod botinstance;
pub mod botmodules; pub mod botmodules;
pub mod identity; pub mod identity;
pub mod ratelimiter; pub mod ratelimiter;
// pub fn init() -> ()
// {
// println!("I was here");
// }

View file

@ -1,51 +1,29 @@
// use futures::lock::Mutex;
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::RwLock;
use twitch_irc::login::StaticLoginCredentials;
use twitch_irc::message::PrivmsgMessage;
use twitch_irc::message::ServerMessage;
use twitch_irc::transport::tcp::TCPTransport;
use twitch_irc::transport::tcp::TLS;
use twitch_irc::ClientConfig;
use twitch_irc::SecureTCPTransport;
use twitch_irc::TwitchIRCClient;
// use std::borrow::Borrow;
use dotenv::dotenv;
// use std::borrow::BorrowMut;
// use std::boxed;
// use std::cell::Ref;
use std::env;
use std::sync::Arc;
use std::env;
use std::collections::HashMap; use std::collections::HashMap;
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::{RwLock,Mutex};
use twitch_irc::login::StaticLoginCredentials;
use twitch_irc::message::{PrivmsgMessage,ServerMessage};
use twitch_irc::transport::tcp::{TCPTransport,TLS};
use twitch_irc::{ClientConfig,SecureTCPTransport,TwitchIRCClient};
use dotenv::dotenv;
use casual_logger::Log;
use rand::Rng; use rand::Rng;
// Important to use tokios Mutex here since std Mutex doesn't work with async functions
use tokio::sync::Mutex;
// use crate::core::botmodules::BotAction;
use crate::core::ratelimiter; use crate::core::ratelimiter;
use crate::core::ratelimiter::RateLimiter; use crate::core::ratelimiter::RateLimiter;
// use crate::core::botmodules;
use crate::core::botmodules::ModulesManager; use crate::core::botmodules::ModulesManager;
use crate::core::botmodules::bot_actions::actions_util::BotAR;
use crate::core::identity::{ChangeResult, IdentityManager, Permissible}; use crate::core::identity::{ChangeResult, IdentityManager, Permissible};
// use std::cell::RefCell;
// use std::rc::Rc;
use std::sync::Arc;
// use futures::lock::Mutex;
// use std::pin::Pin;
//use std::borrow::Borrow;
// use core::borrow::Borrow;
// pub type BotAR = Arc<RwLock<BotInstance>>;
use super::botmodules::bot_actions::actions_util::BotAR;
// use casual_logger::{Level, Log};
use casual_logger::Log;
pub mod botlog { pub mod botlog {

View file

@ -1,8 +1,8 @@
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;
use std::time::Instant;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RateLimiter { pub struct RateLimiter {
timer: Instant, timer: Instant,
@ -12,6 +12,7 @@ pub struct RateLimiter {
pub enum LimiterResp { pub enum LimiterResp {
Allow, // when it's evaluated to be within limits Allow, // when it's evaluated to be within limits
Skip, // as outside of rate limits Skip, // as outside of rate limits
// Enqueue, // [FUTURE]
} }
impl Default for RateLimiter { impl Default for RateLimiter {
@ -30,16 +31,13 @@ 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
self.timer = Instant::now(); self.timer = Instant::now();
self.msgcounter = 0; self.msgcounter = 0;
LimiterResp::Allow LimiterResp::Allow
} else if self.msgcounter < MSG_THRESHOLD { } else if self.msgcounter < MSG_THRESHOLD {
// # [x] elapsed < TIME_THRESHOLD_S && msgcounter < MSG_THRESHOLD
LimiterResp::Allow LimiterResp::Allow
// } else if self.msgcounter >= MSG_THRESHOLD {
} else { } else {
// # [x] elapsed < TIME_THRESHOLD_S && msgcounter >= MSG_THRESHOLD // when elapsed() < TIME_THRESHOLD_S && msgcounter >= MSG_THRESHOLD
LimiterResp::Skip LimiterResp::Skip
} }
} }

View file

@ -1,23 +1,14 @@
// pub mod core;
// pub mod modules;
//use myLib;
//pub mod lib;
// use std::process::Output;
// use crate::core::botinstance::ArcBox;
// use bot_lib::core::botinstance::ArcBox;
use bot_lib::core::botinstance::{self, BotInstance};
// use core::botinstance::{self,BotInstance};
use casual_logger::Extension;
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::RwLock; use tokio::sync::RwLock;
use casual_logger::{Extension, Level, Log};
use bot_lib::core::botinstance::{BotInstance,botlog};
use bot_lib::core::botmodules;
pub type BotAR = Arc<RwLock<BotInstance>>; pub type BotAR = Arc<RwLock<BotInstance>>;
use casual_logger::{Level, Log}; // God I love anime girls
// Cweamcat can cweam on me - Forcen
#[tokio::main] #[tokio::main]
pub async fn main() { pub async fn main() {
@ -27,59 +18,37 @@ pub async fn main() {
let bot = BotInstance::init().await; let bot = BotInstance::init().await;
// Log::debug("Checking bot actions"); {
botinstance::botlog::debug("Checking bot actions", Some("main()".to_string()), None); botlog::debug("Reading bot actions", Some("main()".to_string()), None);
let a = Arc::clone(&bot.botmodules.botactions);
let a = a.read().await;
// let a = *a;
// for (_, acts) in &*a { let actsdb = Arc::clone(&bot.botmodules.botactions);
for acts in (*a).values() { let actsdb_lock = actsdb.read().await;
for acts in (*actsdb_lock).values() {
for act in acts { for act in acts {
match act { let outstr = match act {
bot_lib::core::botmodules::BotAction::C(b) => { botmodules::BotAction::C(b) => {
// println!("bot actiions: {}",b.command) 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,
);
} }
bot_lib::core::botmodules::BotAction::L(l) => { botmodules::BotAction::L(l) => {
// println!("bot actiions: {}",l.name) 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,
);
}
_ => {
// println!("Not a valid match??")
// Log::info("Not a valid match??");
botinstance::botlog::info(
"Not a valid match??",
Some("main()".to_string()),
None,
);
} }
_ => "Not a valid match??".to_string(),
};
botlog::info(outstr.as_str(), Some("main()".to_string()), None);
} }
} }
} }
// println!("Starting runner.."); botlog::notice("Starting Bot Runner", Some("main()".to_string()), None);
// Log::notice("Starting Bot Runner");
botinstance::botlog::notice("Starting Bot Runner", Some("main()".to_string()), None);
println!("Starting Bot Runner"); println!("Starting Bot Runner");
Log::flush(); Log::flush();
bot.runner().await; bot.runner().await;
// println!("ERROR : EXIT Game loop"); let pstr =
// let msg = Log::fatal("ERROR : EXIT Game loop"); botlog::fatal("ERROR : EXIT Game loop", Some("main()".to_string()), None);
// panic!("{}",Log::fatal("ERROR : EXIT Game loop")); panic!("{}", pstr);
let a = botinstance::botlog::fatal("ERROR : EXIT Game loop", Some("main()".to_string()), None);
panic!("{}", a);
} }

View file

@ -4,15 +4,11 @@
*/ */
//mod crate::core::botmodules;
// use crate::core::botmodules;
pub use crate::core::botmodules::ModulesManager;
// use crate::core::botinstance;
pub use crate::core::botinstance::BotInstance;
// use futures::lock::Mutex;
use std::sync::Arc; use std::sync::Arc;
pub use crate::core::botinstance::BotInstance;
pub use crate::core::botmodules::ModulesManager;
// [ ] Load submodules // [ ] Load submodules
mod experiments; mod experiments;
@ -25,5 +21,4 @@ pub async fn init(mgr: Arc<ModulesManager>) {
experiments::init(mgr).await experiments::init(mgr).await
//();
} }

View file

@ -1,48 +1,32 @@
/* /*
Submodules - Custom Modules -
- should have definitions of BotAction that will be added to a bit Usage :
- therefore, will be defined in modules.rs file [ ] within the file's init(), define BotActions & Load them into the ModulesManager
- will define one init(&BotInstance) take within the module that will contain : [ ] Define Execution Bodies for these BotActions
- BotAction definitions that each call &BotInstance module manager to add itself [ ] Afterwards, add the following to parent modules.rs file
- mod <modulename>;
- within init(), <modulename>::init(mgr).await
*/ */
// mod crate::modules;
//use crate::modules;
// use std::future::Future; use std::sync::Arc;
use rand::Rng;
use twitch_irc::message::PrivmsgMessage;
use crate::core::botinstance::botlog;
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::botmodules::{BotActionTrait, BotCommand, BotModule, Listener, ModulesManager};
// use crate::core::botinstance::{self, BotInstance, ChType};
use crate::core::botinstance;
// use futures::lock::Mutex;
use twitch_irc::message::PrivmsgMessage;
use crate::core::identity; use crate::core::identity;
use rand::Rng;
// use std::rc::Rc;
use std::sync::Arc;
// pub fn init(mgr:&mut ModulesManager)
pub async fn init(mgr: Arc<ModulesManager>) { pub async fn init(mgr: Arc<ModulesManager>) {
// BotCommand {
// module : BotModule(String::from("experiments 004")),
// command : String::from("test1"), // command call name
// alias : vec![String::from("tester1"),String::from("testy1")], // String of alternative names
// exec_body : actions_util::asyncbox(testy) ,
// help : String::from("DUPCMD4 tester"),
// required_roles : vec![
// //identity::UserRole::Mod(ChType::Channel(String::new())),
// identity::UserRole::SupMod(ChType::Channel(String::new()))
// ],
// }.add_to_modmgr(mgr);
// 1. Define the BotAction
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
@ -52,8 +36,11 @@ pub async fn init(mgr: Arc<ModulesManager>) {
required_roles: vec![identity::UserRole::BotAdmin], required_roles: vec![identity::UserRole::BotAdmin],
}; };
// 2. Add the BotAction to ModulesManager
botc1.add_to_modmgr(Arc::clone(&mgr)).await; botc1.add_to_modmgr(Arc::clone(&mgr)).await;
// 1. Define the BotAction
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"),
@ -61,19 +48,12 @@ pub async fn init(mgr: Arc<ModulesManager>) {
help: String::from(""), help: String::from(""),
}; };
// 2. Add the BotAction to ModulesManager
list1.add_to_modmgr(Arc::clone(&mgr)).await; list1.add_to_modmgr(Arc::clone(&mgr)).await;
} }
async fn good_girl(bot: BotAR, msg: PrivmsgMessage) { async fn good_girl(bot: BotAR, msg: PrivmsgMessage) {
// println!("In GoodGirl() Listener");
// Change below from debug to trace if required later
botinstance::botlog::debug(
"In GoodGirl() Listener",
Some("experiments > goodgirl()".to_string()),
Some(&msg),
);
//println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text);
// [ ] Uses gen_ratio() to output bool based on a ratio probability . // [ ] Uses gen_ratio() to output bool based on a ratio probability .
// - 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)
@ -81,38 +61,43 @@ async fn good_girl(bot: BotAR, msg: PrivmsgMessage) {
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.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) { botlog::debug(
// println!("In GoodGirl() > Pausechamp"); "Good Girl Detected > 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");
botinstance::botlog::debug( botlog::debug(
"In GoodGirl() > Win", "Oh that's a good girl!",
Some("experiments > goodgirl()".to_string()), Some("experiments > goodgirl()".to_string()),
Some(&msg), Some(&msg),
); );
let a = Arc::clone(&bot);
let botlock = a.read().await; let bot = Arc::clone(&bot);
let botlock = bot.read().await;
// uses chat.say_in_reply_to() for the bot controls for messages
botlock botlock
.botmgrs .botmgrs
.chat .chat
.say_in_reply_to(&msg, String::from("GoodGirl xdd ")) .say_in_reply_to(&msg, String::from("GoodGirl xdd "))
.await; .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( botlog::debug(
"testy triggered!", "testy triggered!",
Some("experiments > testy()".to_string()), Some("experiments > testy()".to_string()),
Some(&msg), Some(&msg),