Compare commits

...

33 commits

Author SHA1 Message Date
8ed672fb3a comment issue with fix 2024-03-31 20:13:02 -04:00
e711c6454d ExecBodyParams curr_act 2024-03-31 20:09:21 -04:00
fa5de03bae used blocking instead of async in some calls 2024-03-31 16:38:11 -04:00
000094e9c4 attempt blocking at getchannel failed 2024-03-31 14:13:20 -04:00
4719b93ce5 addl debug 2024-03-30 19:25:07 -04:00
745ac91522 addl debug 2024-03-30 14:26:39 -04:00
0625e7f091 adding tokio-console 2024-03-30 14:26:06 -04:00
a38c84b8f4 smol 2024-03-29 23:51:41 -04:00
fcf4f3f7cf add debug implementations that helped (kinda) 2024-03-29 21:06:48 +01:00
9d94328cd6 mark call that locks execbody from using that routine 2024-03-29 21:05:21 +01:00
b5e95668a5 ISSUE - potential lock issue
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-29 09:03:16 -04:00
66195138f8 corrected error with validate_attr 2024-03-28 20:21:49 -04:00
5c35ad114a ISSUE - commented out problem code? 2024-03-28 17:52:43 -04:00
26f67787d7 addl debugging 2024-03-28 15:07:24 -04:00
1b534ebeb7 fixed routine attr validation logic 2024-03-28 13:46:02 -04:00
c27dd3b86f custom countdown 2024-03-28 13:18:02 -04:00
6d3b5eee41 routine assigns self reference at construct 2024-03-28 11:50:08 -04:00
2a1a7f8503 ExecBody & routine addl references 2024-03-28 04:39:03 -04:00
ca9361cc93 routine methods 2024-03-28 03:18:41 -04:00
4637312da9 impl stop 2024-03-28 02:13:38 -04:00
6c3a151668 impl other routine attr 2024-03-27 23:56:34 -04:00
e963ae250d (cont) routine methods 2024-03-27 23:00:04 -04:00
60fae25419 comments 2024-03-27 20:47:56 -04:00
537c3565a2 custom start test fn 2024-03-27 17:28:47 -04:00
669b2da871 cleanup start impl 2024-03-27 17:03:58 -04:00
226da4362a comments cleanup 2024-03-27 16:04:15 -04:00
8da8460e47 proper join handling at custom
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-27 14:51:56 -04:00
b08d91af5d (cont) start runonce
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-27 10:18:13 -04:00
3f8e798050 (cont) routine start
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-27 02:35:31 -04:00
5249c3af25 smol debug in identity 2024-03-27 01:29:09 -04:00
4e9316ad49 (init) experiment test module
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-26 16:56:30 -04:00
2ba92388a2 runonce implementation 2024-03-26 14:30:13 -04:00
6c7290883f (init) routine methods 2024-03-26 11:29:47 -04:00
11 changed files with 3112 additions and 43 deletions

View file

@ -1,4 +1,7 @@
[build]
rustflags = ["--cfg", "tokio_unstable"]
[env] [env]
# Based on https://doc.rust-lang.org/cargo/reference/config.html # Based on https://doc.rust-lang.org/cargo/reference/config.html
OtherBots = "Supibot,buttsbot,PotatBotat,StreamElements,yuumeibot" OtherBots = "Supibot,buttsbot,PotatBotat,StreamElements,yuumeibot"

1122
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -7,7 +7,7 @@ edition = "2021"
[dependencies] [dependencies]
dotenv = "0.15.0" dotenv = "0.15.0"
tokio = { version = "1.33.0", features = ["full"] } tokio = { version = "1.33.0", features = ["full", "tracing"] }
twitch-irc = "5.0.1" twitch-irc = "5.0.1"
rand = { version = "0.8.5", features = [] } rand = { version = "0.8.5", features = [] }
futures = "0.3" futures = "0.3"
@ -15,6 +15,8 @@ async-trait = "0.1.77"
async-recursion = "1.1.0" async-recursion = "1.1.0"
casual_logger = "0.6.5" casual_logger = "0.6.5"
chrono = "0.4.35" chrono = "0.4.35"
tokio-console = "0.1.10"
console-subscriber = "0.2.0"
[lib] [lib]

View file

@ -5,40 +5,143 @@ use tokio::sync::RwLock;
use crate::core::botinstance::BotInstance; use crate::core::botinstance::BotInstance;
use super::{botmodules::{BotAction, BotModule}, identity::ChatBadge}; use super::{botinstance::Channel, botmodules::{BotAction, BotModule, Routine}, identity::ChatBadge};
pub type BotAR = Arc<RwLock<BotInstance>>; pub type BotAR = Arc<RwLock<BotInstance>>;
pub type ActAR = Arc<RwLock<BotAction>>; pub type ActAR = Arc<RwLock<BotAction>>;
pub type RoutineAR = Arc<RwLock<Routine>>;
#[derive(Clone)] #[derive(Clone, Debug)]
pub struct ExecBodyParams { pub struct ExecBodyParams {
pub bot : BotAR, pub bot : BotAR,
pub msg : PrivmsgMessage, pub msg : PrivmsgMessage,
pub parent_act : ActAR , pub parent_act : Option<ActAR> ,
pub curr_act : Option<ActAR> ,
}
#[derive(Debug,Eq,PartialEq,Hash)]
pub enum ParamLevel {
Parent,
Current,
} }
impl ExecBodyParams { impl ExecBodyParams {
pub async fn get_parent_module(&self) -> Option<BotModule> { // pub async fn get_parent_module(&self) -> Option<BotModule> {
// pub async fn get_parent_module(&self) -> BotModule {
pub async fn get_module(&self) -> BotModule {
let parent_act = Arc::clone(&self.parent_act); let curr_acta = Arc::clone(&(self.curr_act.clone().unwrap()));
let parent_act_lock = parent_act.read().await; let parent_act_lock = curr_acta.read().await;
let act = &(*parent_act_lock); let act = &(*parent_act_lock);
match act { match act {
BotAction::C(c) => { BotAction::C(c) => {
let temp = c.module.clone(); // let temp = c.module.clone();
Some(temp) // Some(temp)
c.module.clone()
}, },
BotAction::L(l) => { BotAction::L(l) => {
let temp = l.module.clone(); // let temp = l.module.clone();
Some(temp) // Some(temp)
l.module.clone()
}, },
_ => None BotAction::R(r) => {
// let temp = r.module.clone();
// Some(temp)
r.read().await.module.clone()
}
// _ => None
} }
} }
// pub async fn get_channel(&self) -> Option<Channel> {
pub fn get_channel(&self) -> Option<Channel> {
dbg!("Core > ExecBodyParams > GetChannels START");
dbg!("!! [x] Document - After SUCCESS message was sent to chat");
dbg!(">> BotActionAR - RwLock from botmodules.rs::929:46 - current_readers = 1 ");
dbg!(">> RoutineAR - RwLock from botmodules.rs::1261:32 - current_readers = 1 ");
dbg!(">> join_handle - RwLock from botmodules.rs::1226:46 - current_readers = 0 ");
dbg!(">> BotInstanceAR - RwLock from botinstance.rs::150:28 - current_readers = 2");
let curr_act = Arc::clone(&self.curr_act.clone().unwrap());
// let curr_act_lock = curr_act.read().await;
// Note : The below `curr_act.blocking_read()` is not possible. I get the following
// during runtime in this areas
/*
thread 'tokio-runtime-worker' panicked at src\core\bot_actions.rs:66:38:
Cannot block the current thread from within a runtime. This happens because a function attempted to block the current thread while the thread is being used to drive asynchronous tasks.
*/
let curr_act_lock = curr_act.blocking_read();
dbg!("Core > ExecBodyParams > After Creating ExecBodyParams.current_act.read() Guard ");
dbg!("!! [x] Document - After SUCCESS message was sent to chat");
dbg!(">> BotActionAR - RwLock from botmodules.rs::929:46 - current_readers = 1 ");
dbg!(">> RoutineAR - RwLock from botmodules.rs::1261:32 - current_readers = 1 ");
dbg!(">> join_handle - RwLock from botmodules.rs::1226:46 - current_readers = 0 ");
dbg!(">> BotInstanceAR - RwLock from botinstance.rs::150:28 - current_readers = 2");
let act = &(*curr_act_lock);
dbg!("Core > ExecBodyParams > Using the Read Guard ");
dbg!("!! [x] Document - After SUCCESS message was sent to chat");
dbg!(">> BotActionAR - RwLock from botmodules.rs::929:46 - current_readers = 1 ");
dbg!(">> RoutineAR - RwLock from botmodules.rs::1261:32 - current_readers = 1");
dbg!(">> join_handle - RwLock from botmodules.rs::1226:46 - current_readers = Not Listed ");
dbg!(">> BotInstanceAR - RwLock from botinstance.rs::150:28 - current_readers = 2");
let out = match act {
BotAction::C(_) => {
// let temp = c.module.clone();
// Some(temp)
Some(Channel(self.msg.channel_login.clone()))
},
BotAction::L(_) => {
// let temp = l.module.clone();
// Some(temp)
// l.module.clone()
Some(Channel(self.msg.channel_login.clone()))
},
BotAction::R(r) => {
// let temp = r.module.clone();
// Some(temp)
dbg!("Core > ExecBodyParams > GetChannels - routine identified");
dbg!("!! [x] Document");
dbg!(">> BotActionAR - RwLock from botmodules.rs::930:46 - current_readers = 2");
dbg!(">> RoutineAR - RwLock from botmodules.rs::1262:32 - current_readers = 1");
dbg!(">> join_handle - RwLock from botmodules.rs::1226:46 - current_readers = 0");
dbg!(">> BotInstanceAR - RwLock from botinstance.rs::150:28 - current_readers = 1");
// => 03.30 - Just before deadlock
// dbg!("ISSUE : RoutineAR - RwLock from botmodules.rs::1261:32 - current_readers = 1");
// let out = Some(r.read().await.channel.clone());
dbg!("ISSUE > Never makes it after the following read guard");
// let guard = r.read().await;
let guard = r.blocking_read();
dbg!("ISSUE RESOLVED > If passed htis point");
let channel = guard.channel.clone();
drop(guard);
let out = Some(channel);
// => 03.30 - This isn't reached because of the Deadlock
dbg!(">> Just after Potential Deadlock Lock");
out
}
// _ => None
};
out
}
pub fn get_sender(&self) -> String { pub fn get_sender(&self) -> String {
self.msg.sender.name.clone() self.msg.sender.name.clone()
} }

View file

@ -40,7 +40,7 @@ pub struct Channel(pub String);
use super::bot_actions::ExecBodyParams; use super::bot_actions::ExecBodyParams;
use super::botmodules::StatusType; use super::botmodules::StatusType;
#[derive(Clone)] #[derive(Clone, Debug)]
pub struct BotManagers { pub struct BotManagers {
pub identity: Arc<RwLock<IdentityManager>>, pub identity: Arc<RwLock<IdentityManager>>,
pub chat: Chat, pub chat: Chat,
@ -70,6 +70,7 @@ impl<T: Clone> ArcBox<T> {
} }
} }
#[derive(Debug)]
pub struct BotInstance { pub struct BotInstance {
pub prefix: char, pub prefix: char,
pub bot_channel: Channel, pub bot_channel: Channel,
@ -404,7 +405,8 @@ impl BotInstance {
let params = ExecBodyParams { let params = ExecBodyParams {
bot : Arc::clone(&bot), bot : Arc::clone(&bot),
msg : (*msg).clone(), msg : (*msg).clone(),
parent_act : Arc::clone(&act_clone), parent_act : None,
curr_act : Some(Arc::clone(&act_clone)),
}; };
// When sending a BotMsgTypeNotif, send_botmsg does Roles related validation as required // When sending a BotMsgTypeNotif, send_botmsg does Roles related validation as required
@ -461,7 +463,8 @@ impl BotInstance {
let params = ExecBodyParams { let params = ExecBodyParams {
bot : Arc::clone(&bot), bot : Arc::clone(&bot),
msg : (*msg).clone(), msg : (*msg).clone(),
parent_act : Arc::clone(&act_clone), parent_act : None,
curr_act : Some(Arc::clone(&act_clone)),
}; };
@ -491,7 +494,8 @@ impl BotInstance {
let params = ExecBodyParams { let params = ExecBodyParams {
bot : Arc::clone(&bot), bot : Arc::clone(&bot),
msg : (*msg).clone(), msg : (*msg).clone(),
parent_act : Arc::clone(&act_clone), parent_act : None,
curr_act : Some(Arc::clone(&act_clone)),
}; };
@ -516,7 +520,8 @@ impl BotInstance {
c.execute(ExecBodyParams { c.execute(ExecBodyParams {
bot : a, bot : a,
msg : msg.clone() , msg : msg.clone() ,
parent_act : Arc::clone(&act_clone), parent_act : None,
curr_act : Some(Arc::clone(&act_clone)),
}).await; }).await;
botlog::trace( botlog::trace(
@ -564,7 +569,8 @@ impl BotInstance {
l.execute(ExecBodyParams { l.execute(ExecBodyParams {
bot : a, bot : a,
msg : msg.clone() , msg : msg.clone() ,
parent_act : Arc::clone(&act_clone), parent_act : None,
curr_act : Some(Arc::clone(&act_clone)),
} ).await; } ).await;
} }

File diff suppressed because it is too large Load diff

View file

@ -27,7 +27,7 @@ use super::identity;
use async_recursion::async_recursion; use async_recursion::async_recursion;
#[derive(Clone)] #[derive(Clone, Debug)]
pub struct Chat { pub struct Chat {
pub ratelimiters: Arc<Mutex<HashMap<Channel, RateLimiter>>>, // used to limit messages sent per channel pub ratelimiters: Arc<Mutex<HashMap<Channel, RateLimiter>>>, // used to limit messages sent per channel
pub client: TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>, pub client: TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>,
@ -101,14 +101,15 @@ impl Chat {
Some(&params.msg), Some(&params.msg),
); );
let parent_module = params.get_parent_module().await; let parent_module = params.get_module().await;
let params_clone = params.clone(); let params_clone = params.clone();
let botclone = Arc::clone(&params_clone.bot); let botclone = Arc::clone(&params_clone.bot);
let botlock = botclone.read().await; let botlock = botclone.read().await;
let modmgr = Arc::clone(&botlock.botmodules); let modmgr = Arc::clone(&botlock.botmodules);
let modstatus = (*modmgr).modstatus( let modstatus = (*modmgr).modstatus(
parent_module.clone().expect("ERROR - Expected a module"), // parent_module.clone().expect("ERROR - Expected a module"),
parent_module.clone(),
Channel(channel_login.clone()) Channel(channel_login.clone())
).await; ).await;
@ -180,7 +181,8 @@ impl Chat {
self.send_botmsg(BotMsgType::Notif( self.send_botmsg(BotMsgType::Notif(
format!("uuh {:?} is disabled on {} : {:?}", format!("uuh {:?} is disabled on {} : {:?}",
parent_module.clone().unwrap(), // parent_module.clone().unwrap(),
parent_module.clone(),
channel_login.clone(), channel_login.clone(),
lvl lvl
), ),

View file

@ -553,7 +553,16 @@ async fn getroles(params : ExecBodyParams) {
let arg1 = argv.next(); let arg1 = argv.next();
let targetuser = match arg1 { let targetuser = match arg1 {
None => return, // exit if no arguments None => {
botlog::debug(
"Exittingcmd getroles - Invalid arguments ",
Some("identity.rs > init > getroles()".to_string()),
Some(&params.msg),
);
return
}, // exit if no arguments
Some(arg) => arg, Some(arg) => arg,
}; };
@ -689,7 +698,7 @@ pub enum Permissible {
type UserRolesDB = HashMap<String, Arc<RwLock<Vec<UserRole>>>>; type UserRolesDB = HashMap<String, Arc<RwLock<Vec<UserRole>>>>;
#[derive(Clone)] #[derive(Clone, Debug)]
pub struct IdentityManager { pub struct IdentityManager {
special_roles_users: Arc<RwLock<UserRolesDB>>, special_roles_users: Arc<RwLock<UserRolesDB>>,
} }

View file

@ -12,6 +12,7 @@ pub use crate::core::botmodules::ModulesManager;
mod experiment001; mod experiment001;
mod experiment002; mod experiment002;
mod experiment003;
// [ ] 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
@ -21,4 +22,5 @@ pub async fn init(mgr: Arc<ModulesManager>) {
experiment001::init(Arc::clone(&mgr)).await; experiment001::init(Arc::clone(&mgr)).await;
experiment002::init(Arc::clone(&mgr)).await; experiment002::init(Arc::clone(&mgr)).await;
experiment003::init(Arc::clone(&mgr)).await;
} }

View file

@ -0,0 +1,768 @@
/*
Custom Modules -
Usage :
[ ] within the file's init(), define BotActions & Load them into the ModulesManager
[ ] Define Execution Bodies for these BotActions
[ ] Afterwards, add the following to parent modules.rs file
- mod <modulename>;
- within init(), <modulename>::init(mgr).await
*/
const OF_CMD_CHANNEL:Channel = Channel(String::new());
use casual_logger::Log;
use rand::Rng;
use rand::thread_rng;
use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use tokio::sync::RwLock;
use std::borrow::Borrow;
use std::borrow::BorrowMut;
use std::sync::Arc;
use crate::core::bot_actions::ExecBodyParams;
use crate::core::botinstance::Channel;
use crate::core::botlog;
use crate::core::bot_actions::actions_util;
use crate::core::botmodules::{BotAction, BotActionTrait, BotCommand, BotModule, Listener, ModulesManager, Routine, RoutineAttr};
use crate::core::identity::UserRole::*;
use tokio::time::{sleep, Duration};
pub async fn init(mgr: Arc<ModulesManager>) {
// 1. Define the BotAction
let botc1 = BotCommand {
module: BotModule(String::from("experiments003")),
command: String::from("test3"), // command call name
alias: vec![], // String of alternative names
exec_body: actions_util::asyncbox(test3_body),
help: String::from("Test Command tester"),
required_roles: vec![
BotAdmin,
Mod(OF_CMD_CHANNEL),
],
};
// 2. Add the BotAction to ModulesManager
botc1.add_to_modmgr(Arc::clone(&mgr)).await;
// 1. Define the BotAction
let botc1 = BotCommand {
module: BotModule(String::from("experiments003")),
command: String::from("countdown"), // command call name
alias: vec![], // String of alternative names
exec_body: actions_util::asyncbox(countdown_chnl_v1),
help: String::from("Test Command tester"),
required_roles: vec![
BotAdmin,
Mod(OF_CMD_CHANNEL),
],
};
// 2. Add the BotAction to ModulesManager
botc1.add_to_modmgr(Arc::clone(&mgr)).await;
}
async fn countdown_chnl_v1(params : ExecBodyParams) {
botlog::debug(
"[CHILDFN] countdown_chnl() triggered!",
Some("Experiments003 > countdown_chnl()".to_string()),
Some(&params.msg),
);
/*
create a fun countdown BotCommand that allows an Elevated Chatter to
-a add channels to target a routine message
-start to start the routine with an input String, that sends a number
of messages to the targeted channels with a countdown, until it
reaches 0 when it sends a cute or funny message
NOTE : At the moment, I don't have customizable persistence, so I would just use
counters from the Routine itself
*/
/*
Because of some bot core features are not available, v1.0 of this could be :
[x] 1. Create a Routine & start a routine
[x] 2. Have the routine go through each joined channel randomly and countdown
[x] 3. At the end, say "0, I love you uwu~" in the last chosen channel
*/
/*
Usage => 03.28 - skipping arguments as functinoality isn't enhanced
-a <channel> => 03.28 - Not sure if this is possible at the moment?
-start
-stop => 03.28 - Not sure if this is possible at the moment?
*/
/*
[ ] Functional Use Case
1. -a <channel> adds targetted channels
*/
// [-] Unwraps arguments from message
// let (arg1, arg2) = {
// let mut argv = params.msg.message_text.split(' ');
// argv.next(); // Skip the command name
// let arg1 = argv.next();
// let arg2 = argv.next();
// (arg1, arg2)
// };
// [ ] 1. Create a Routine & start a routine
let params_ar = Arc::new(RwLock::new(params));
// let parentmodule = params.get_parent_module().await;
let module = params_ar.read().await.get_module().await;
// let channel = params.get_channel().await;
// let channel = params.get_channel().await;
// let channel = params.get_channel();
let channel_task_grabber = tokio::task::spawn_blocking( move || {
let params_clone = params_ar.clone();
let channel = params_clone.blocking_read().get_channel();
drop(params_clone);
(channel,params_ar)
});
let (channel,params_ar) = channel_task_grabber.await.unwrap();
let routine_attr = vec![
// RoutineAttr::RunOnce
RoutineAttr::MaxIterations(5),
RoutineAttr::LoopDuration(Duration::from_secs(1))
];
// let exec_body = actions_util::asyncbox(rtestbody);
// let exec_body = actions_util::asyncbox(innertester); // <-- 03.27 - when below is uncommented, this is throwing an issue
let exec_body = innertester;
// async fn innertester(params : ExecBodyParams) {
fn innertester(params : Arc<RwLock<ExecBodyParams>>) {
{
// let curract_guard = params.curr_act.read().await;
let paramguard1 = params.blocking_read();
let curract = paramguard1.curr_act.clone().unwrap();
let curract_guard = curract.blocking_read();
// let logmsg_botact = match *params.curr_act.read().await {
let logmsg_botact = match *curract_guard {
BotAction::C(_) => "command",
BotAction::R(_) => "routine",
BotAction::L(_) => "listener",
} ;
botlog::trace(
format!("Params > Curr_act type : {:?}", logmsg_botact).as_str(),
Some("Experiments003 > countdown_chnl()".to_string()),
Some(&params.blocking_read().msg),
);
Log::flush();
}
{
let bot = Arc::clone(&params.blocking_read().bot);
// let botlock = bot.read().await;
let botlock = bot.blocking_read();
// let curract_guard = params.curr_act.write().await;
let paramguard1 = params.blocking_read();
let curract = paramguard1.curr_act.clone().unwrap();
let curract_guard = curract.blocking_write();
// let routine_lock = arr.write().await;
if let BotAction::R(arr) = &*curract_guard {
// if let BotAction::R(arr) = &*params.curr_act.read().await {
botlog::trace(
"Before loading remaining iterations",
Some("Experiments003 > countdown_chnl()".to_string()),
None,
);
Log::flush();
// let iterleft = arr.read().await.remaining_iterations.unwrap_or(0);
// // let iterleft = if arr.read().await.remaining_iterations.is_none() { 0i64 }
// // else { arr.read().await.remaining_iterations.unwrap() };
// let iterleft = match arr.read().await.remaining_iterations {
// None => 0,
// Some(a) => a,
// };
// let routine_lock = arr.read().await;
// if let Some(a) = routine_lock.remaining_iterations.clone() {
// println!("Remaining iterations > {}",a)
// }
let iterleft;
{
// let routine_lock = arr.write().await;
// let routine_lock = arr.blocking_write();
let routine_lock = arr.blocking_read();
iterleft = routine_lock.remaining_iterations.unwrap_or(0);
println!("remaining iterations : {:?}", iterleft);
}
botlog::trace(
"after loading remaining iterations",
Some("Experiments003 > countdown_chnl()".to_string()),
None,
);
Log::flush();
// [ ] get joined channels
let joinedchannels = botlock.bot_channels.clone();
fn pick_a_channel(chnlvec : Vec<Channel>) -> Channel {
botlog::trace(
"In Pick_a_Channel()",
Some("Experiments003 > countdown_chnl()".to_string()),
None,
);
Log::flush();
// More Information : https://docs.rs/rand/0.7.2/rand/seq/trait.SliceRandom.html#tymethod.choose
let mut rng = thread_rng();
// let joinedchannels = botlock.bot_channels.clone();
(*chnlvec.choose(&mut rng).unwrap()).clone()
}
let chosen_channel = pick_a_channel(joinedchannels);
dbg!("SUCCESS", chosen_channel.clone());
botlog::trace(
format!("Picked a channel: {:?}", chosen_channel).as_str(),
Some("Experiments003 > countdown_chnl()".to_string()),
Some(&params.blocking_read().msg),
);
Log::flush();
// [ ] !! ISSUE : With this fix though, the custom fn is no longer
// async. This is an issue because chat module is async
// - There should be no need to change chat , as async allows
// us to multitask with messages
// let a = || {
// let chosen_channel_ar = Arc::new(RwLock::new(chosen_channel));
// let params_clone = params.clone();
// let bot = Arc::clone(&params.blocking_read().bot);
// dbg!("in chat async function");
// let botlock = bot.blocking_read();
// let channel_ar_clone = chosen_channel_ar.clone();
// let outmsg = if iterleft <= 1 {
// format!("{} I love you uwu~",iterleft)
// } else { format!("{}",iterleft) };
// botlock.botmgrs.chat
// .say(
// channel_ar_clone.read().await.0.clone(),
// outmsg,
// params_clone.read().await.clone()
// ).await;
}
}
}
// [ ] setup the routine
if let Ok(newr) = Routine::from(
"Routine Test".to_string(),
module,
channel.unwrap(),
routine_attr,
// Arc::new(RwLock::new(exec_body)),
exec_body,
Arc::new(RwLock::new(params_ar.clone().read().await.clone())),
).await {
let newr_ar = newr.clone();
// [ ] start the routine
if let Ok(_) = Routine::start(newr_ar.clone()).await {
botlog::debug(
"Successfully started",
Some("experiment003 > countdown_chnl()".to_string()),
Some(&params_ar.read().await.msg),
);
Log::flush();
let bot = Arc::clone(&params_ar.read().await.bot);
let botlock = bot.read().await;
// uses chat.say_in_reply_to() for the bot controls for messages
botlock
.botmgrs
.chat
.say_in_reply_to(
&params_ar.read().await.msg,
"Started Routine!".to_string(),
params_ar.read().await.clone()
).await;
// let jhandle = newr.clone().read().await.join_handle.clone().unwrap();
// let a = jhandle.write().await;
// a.
// sleep(Duration::from_secs(300)).await;
}
}
// botlock
// .botmgrs
// .chat
// .say_in_reply_to(
// &params.msg,
// format!("{:?}",),
// params.clone()
// ).await;
}
async fn test3_body(params : ExecBodyParams) {
// println!("testy triggered!"); // NOTE : This test function intends to print (e.g., to stdout) at fn call
botlog::debug(
"testy triggered!",
Some("Experiments003 > test3 command body".to_string()),
Some(&params.msg),
);
/*
Test Routine Start() by :
1. In this single exec body , create a Routine
2. Create a Routine Execution Body
3. Pass the Execution Body & Routine Attributes to create the Routine
4. Start the Routine
5. For RunOnce , we should see it only trigger once, and then complete in the logs
*/
// [x] Get the module from params
let params_ar = Arc::new(RwLock::new(params));
// let parentmodule = params.get_parent_module().await;
let module = params_ar.read().await.get_module().await;
// let channel = params.get_channel().await;
// let channel = params.get_channel().await;
// let channel = params.get_channel();
let routine_attr = vec![
RoutineAttr::RunOnce
];
// let exec_body = actions_util::asyncbox(rtestbody);
// let exec_body = actions_util::asyncbox(rtestbody); // <-- 03.27 - when below is uncommented, this is throwing an issue
// let channel = params.get_channel();
let channel_task_grabber = tokio::task::spawn_blocking( move || {
let params_clone = params_ar.clone();
let channel = params_clone.blocking_read().get_channel();
drop(params_clone);
(channel,params_ar)
});
let (channel,params_ar) = channel_task_grabber.await.unwrap();
let exec_body = rtestbody;
// let parent_params = params.clone();
// let params_clone = params.clone();
// async fn rtestbody(params : ExecBodyParams) {
fn rtestbody(params : Arc<RwLock<ExecBodyParams>>) {
// let guard1 = params.curr_act.read().await;
let paramguard1 = params.blocking_read();
let curract = paramguard1.curr_act.clone().unwrap();
let guard1 = curract.blocking_read();
{
let logmsg_botact = match *guard1 {
BotAction::C(_) => "command",
BotAction::R(_) => "routine",
BotAction::L(_) => "listener",
} ;
botlog::trace(
format!("Params > Curr_act type : {:?}", logmsg_botact).as_str(),
Some("Experiments003 > test3 command body".to_string()),
Some(&params.blocking_read().msg),
);
Log::flush();
}
{
let logmsg_botact = match &*guard1 {
BotAction::C(_) => "command 2",
BotAction::R(_) => "routine 2",
BotAction::L(_) => "listener 2",
} ;
botlog::trace(
format!("Params > Curr_act type : {:?}", logmsg_botact).as_str(),
Some("Experiments003 > test3 command body".to_string()),
Some(&params.blocking_read().msg),
);
Log::flush();
}
// drop(guard1);
{
dbg!("Custom > within Child Custom fn - Before Critical area");
println!("Critical code area start"); // <= 03.29 - This is printed
// if let BotAction::R(c) = &*guard {
// println!("{:?}",c.read().await.channel);
// }
// let routine_channel = if let BotAction::R(c) = &*guard1 {
// dbg!("Custom > within Child Custom fn - During Critical area > Routine Guard ");
// let routineguard = c.read().await;
// Some(routineguard.channel.clone());
// } else {
// None
// };
// let chnl = match &*guard1 {
// BotAction::R(arr) => {
// dbg!("Custom > within Child Custom fn - During Critical area > Before Routine Guard ");
// let routineguard = arr.read().await;
// dbg!("Custom > within Child Custom fn - During Critical area > After Routine Guard ");
// Some(routineguard.channel.clone())
// },
// BotAction::C(_) | BotAction::L(_) => None ,
// } ;
// let chnl = params.get_channel().await;
// let chnl = params.get_channel().await;
let chnl = params.blocking_read().get_channel();
dbg!("Custom > within Child Custom fn - after GetChannel");
println!("{:?}",chnl);
println!("Critical code area end"); // <= 03.29 - ISSUE This is NOT printed
dbg!("Custom > within Child Custom fn - Before Critical area");
// if let BotAction::R(arr) = &*params.curr_act.read().await {
// for curriter in 0..5 {
// println!("tester - Routine - Completed Iterations : {}",
// arr.read().await.complete_iterations);
// println!("tester - Custom Loop - Completed Iterations : {}",
// curriter);
// sleep(Duration::from_secs_f64(0.5)).await;
// }
// }
}
}
let params_clone = params_ar.clone();
botlog::debug(
format!("RTESTBODY : module - {:?} ; channel - {:?}",
module,channel
).as_str(),
Some("experiment003 > test3_body".to_string()),
Some(&params_clone.read().await.msg),
);
let a = Routine::from(
"Routine Test".to_string(),
module,
channel.unwrap(),
routine_attr,
// Arc::new(RwLock::new(exec_body)),
exec_body,
Arc::new(RwLock::new(params_clone.read().await.clone()))
).await;
if let Ok(newr) = a {
// NOTE : The below is a "Playing aound" feature
// In the below, we're unnecessarily adjusting the ExecBodyParams of the parent
// To get the reference to the Routine or the BotAction there are now refernces to itself
// [ ] before execute , be sure to adjust curr_act
// let mut params_mut = params;
let newr_ar = newr.clone();
// params_mut.curr_act = Arc::new(RwLock::new(
// BotAction::R(newr_ar.clone())
// ));
// {
// newr_ar.write().await.parent_params = params_mut.clone();
// }
let rslt = Routine::start(newr_ar.clone()).await;
// let rslt = newr_ar.read().await.start().await;
let rsltstr = match rslt {
Ok(_) => "successful".to_string(),
Err(a) => a,
};
botlog::debug(
format!("TEST3_BODY RESULT : {:?}",
rsltstr
).as_str(),
Some("experiment003 > test3_body".to_string()),
Some(&(params_ar.clone()).read().await.msg),
);
Log::flush();
let bot = Arc::clone(&params_ar.read().await.bot);
let botlock = bot.read().await;
// uses chat.say_in_reply_to() for the bot controls for messages
botlock
.botmgrs
.chat
.say_in_reply_to(
&params_ar.read().await.msg,
format!("Routine Result : {:?}",rsltstr),
params_clone.read().await.clone()
).await;
// [x] Will not be handling JoinHandles here . If immediate abort() handling is required, below is an example that works
/*
let a = newr.clone().read().await.join_handle.clone();
match a {
Some(b) => {
b.read().await.borrow().abort(); // [x] <-- This aborts if wanting to abort immediately
//()
},
None => (),
}
*/
}
Log::flush();
}
async fn good_girl(params : ExecBodyParams) {
// [ ] 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)
// - More Info : https://rust-random.github.io/rand/rand/trait.Rng.html#method.gen_ratio
if params.msg.sender.name.to_lowercase() == "ModulatingForce".to_lowercase()
|| params.msg.sender.name.to_lowercase() == "mzNToRi".to_lowercase()
{
botlog::debug(
"Good Girl Detected > Pausechamp",
Some("experiments > goodgirl()".to_string()),
Some(&params.msg),
);
let rollwin = rand::thread_rng().gen_ratio(1, 10);
if rollwin {
botlog::debug(
"Oh that's a good girl!",
Some("experiments > goodgirl()".to_string()),
Some(&params.msg),
);
let bot = Arc::clone(&params.bot);
let botlock = bot.read().await;
// uses chat.say_in_reply_to() for the bot controls for messages
botlock
.botmgrs
.chat
.say_in_reply_to(
&params.msg,
String::from("GoodGirl xdd "),
params.clone()
).await;
}
}
}
async fn testy(params : ExecBodyParams) {
println!("testy triggered!"); // NOTE : This test function intends to print (e.g., to stdout) at fn call
botlog::debug(
"testy triggered!",
Some("experiments > testy()".to_string()),
Some(&params.msg),
);
}
async fn babygirl(params : ExecBodyParams) {
println!("babygirl triggered!"); // NOTE : This test function intends to print (e.g., to stdout) at fn call
botlog::debug(
"babygirl triggered!",
Some("experiments > babygirl()".to_string()),
Some(&params.msg),
);
let bot = Arc::clone(&params.bot);
let botlock = bot.read().await;
botlock
.botmgrs
.chat
.say_in_reply_to(
&params.msg,
String::from("16:13 notohh: cafdk"),
params.clone()
).await;
sleep(Duration::from_secs_f64(0.5)).await;
botlock
.botmgrs
.chat
.say_in_reply_to(
&params.msg,
String::from("16:13 notohh: have fun eating princess"),
params.clone()
).await;
sleep(Duration::from_secs_f64(2.0)).await;
botlock
.botmgrs
.chat
.say_in_reply_to(
&params.msg,
String::from("16:13 notohh: baby girl"),
params.clone()
).await;
}
async fn routinelike(params : ExecBodyParams) {
println!("routinelike triggered!"); // NOTE : This test function intends to print (e.g., to stdout) at fn call
botlog::debug(
"routinelike triggered!",
Some("experiments > routinelike()".to_string()),
Some(&params.msg),
);
// spawn an async block that runs independently from others
tokio::spawn( async {
for _ in 0..5 {
println!(">> Innterroutine triggered!");
sleep(Duration::from_secs_f64(5.0)).await;
}
}
);
// lines are executed after in conjunction to the spawn
}

View file

@ -14,12 +14,22 @@ pub type BotAR = Arc<RwLock<BotInstance>>;
#[tokio::main] #[tokio::main]
pub async fn main() { pub async fn main() {
console_subscriber::init();
Log::set_file_ext(Extension::Log); Log::set_file_ext(Extension::Log);
Log::set_level(Level::Trace); Log::set_level(Level::Trace);
Log::set_retention_days(2); Log::set_retention_days(2);
// Log::set_level(Level::Notice); // Log::set_level(Level::Notice);
// fn innerbody() -> i64 {
// println!("hello");
// 64
// }
// let exec_body:fn() -> i64 = innerbody;