Merge branch '2024.02.04---LATEST-PROBLEM' into dev

This commit is contained in:
ModulatingForce 2024-02-12 06:30:42 -05:00
commit 8f48c3cf59
8 changed files with 1280 additions and 215 deletions

62
Cargo.lock generated
View file

@ -151,7 +151,9 @@ checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5"
name = "forcebot_rs" name = "forcebot_rs"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"async-trait",
"dotenv", "dotenv",
"futures",
"rand", "rand",
"tokio", "tokio",
"twitch-irc", "twitch-irc",
@ -198,7 +200,67 @@ checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48"
dependencies = [ dependencies = [
"futures-core", "futures-core",
"futures-sink", "futures-sink",
]
[[package]]
name = "futures-core"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d"
[[package]]
name = "futures-executor"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d"
dependencies = [
"futures-core",
"futures-task", "futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1"
[[package]]
name = "futures-macro"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "futures-sink"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5"
[[package]]
name = "futures-task"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004"
[[package]]
name = "futures-util"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"memchr",
"pin-project-lite", "pin-project-lite",
"pin-utils", "pin-utils",
"slab", "slab",

View file

@ -10,3 +10,5 @@ dotenv = "0.15.0"
tokio = { version = "1.33.0", features = ["full"] } tokio = { version = "1.33.0", features = ["full"] }
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"
async-trait = "0.1.77"

View file

@ -1,5 +1,7 @@
// use futures::lock::Mutex;
use tokio::sync::mpsc::UnboundedReceiver; use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::RwLock;
use twitch_irc::login::StaticLoginCredentials; use twitch_irc::login::StaticLoginCredentials;
use twitch_irc::ClientConfig; use twitch_irc::ClientConfig;
use twitch_irc::SecureTCPTransport; use twitch_irc::SecureTCPTransport;
@ -8,6 +10,10 @@ 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 std::borrow::Borrow;
use std::borrow::BorrowMut;
use std::boxed;
use std::cell::Ref;
use std::env; use std::env;
use dotenv::dotenv; use dotenv::dotenv;
@ -15,16 +21,33 @@ use std::collections::HashMap;
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::botmodules::BotAction; use crate::core::botmodules::BotAction;
use crate::core::ratelimiter::RateLimiter; use crate::core::ratelimiter::RateLimiter;
use crate::core::ratelimiter; use crate::core::ratelimiter;
use crate::core::botmodules; use crate::core::botmodules;
use crate::core::botmodules::ModulesManager; use crate::core::botmodules::{ModulesManager,BotAction};
use crate::core::identity::{IdentityManager,Permissible}; use crate::core::identity::{IdentityManager,Permissible};
use std::rc::Rc;
use std::cell::RefCell;
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;
#[derive(Debug, PartialEq, Eq, Hash, Clone)] #[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum ChType { pub enum ChType {
@ -34,15 +57,19 @@ pub enum ChType {
pub use ChType::Channel; pub use ChType::Channel;
pub enum ModType {
BotModule(String),
}
pub use ModType::BotModule;
// pub enum ModType {
// BotModule(String),
// }
// pub use ModType::BotModule;
#[derive(Clone)] #[derive(Clone)]
pub struct Chat { pub struct Chat {
pub ratelimiters : HashMap<ChType,RateLimiter>, // used to limit messages sent per channel // pub ratelimiters : HashMap<ChType,RateLimiter>, // used to limit messages sent per channel
pub ratelimiters : Arc<Mutex<HashMap<ChType,RateLimiter>>>, // used to limit messages sent per channel
pub client : TwitchIRCClient<TCPTransport<TLS>,StaticLoginCredentials>, pub client : TwitchIRCClient<TCPTransport<TLS>,StaticLoginCredentials>,
} }
@ -52,19 +79,21 @@ impl Chat {
pub fn init(ratelimiters:HashMap<ChType, RateLimiter>, pub fn init(ratelimiters:HashMap<ChType, RateLimiter>,
client:TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>) -> Chat { client:TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>) -> Chat {
Chat{ Chat{
ratelimiters : ratelimiters, ratelimiters : Arc::new(Mutex::new(ratelimiters)),
client : client, client : client,
} }
} }
pub fn init_channel(&mut self, chnl:ChType) -> () { // pub fn init_channel(&mut self, chnl:ChType) -> () {
pub async fn init_channel(&mut self, chnl:ChType) -> () {
let n = RateLimiter::new(); let n = RateLimiter::new();
self.ratelimiters.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) -> () {
/* /*
formats message before sending to TwitchIRC formats message before sending to TwitchIRC
@ -77,7 +106,12 @@ impl Chat {
// self.client.say_in_reply_to(msg,outmsg).await.unwrap(); // self.client.say_in_reply_to(msg,outmsg).await.unwrap();
// // let contextratelimiter = ratelimiters.get_mut(&msg.channel_login).expect("ERROR: Issue with Rate limiters"); // // let contextratelimiter = ratelimiters.get_mut(&msg.channel_login).expect("ERROR: Issue with Rate limiters");
let contextratelimiter = self.ratelimiters let a = Arc::clone(&self.ratelimiters);
let mut a = a.lock().await;
// let contextratelimiter = self.ratelimiters
let contextratelimiter = a
// .get_mut()
.get_mut(&Channel(String::from(&msg.channel_login))) .get_mut(&Channel(String::from(&msg.channel_login)))
.expect("ERROR: Issue with Rate limiters"); .expect("ERROR: Issue with Rate limiters");
// let contextratelimiter = self.ratelimiters.get(&msg.channel_login).expect("ERROR: Issue with Rate limiters"); // let contextratelimiter = self.ratelimiters.get(&msg.channel_login).expect("ERROR: Issue with Rate limiters");
@ -141,7 +175,7 @@ impl Chat {
#[derive(Clone)] #[derive(Clone)]
pub struct BotManagers { pub struct BotManagers {
// pub botmodules : ModulesManager, // pub botmodules : ModulesManager,
pub identity : IdentityManager, pub identity : Arc<RwLock<IdentityManager>>,
pub chat : Chat, pub chat : Chat,
} }
@ -150,27 +184,53 @@ impl BotManagers {
pub fn init(ratelimiters:HashMap<ChType, RateLimiter>, pub fn init(ratelimiters:HashMap<ChType, RateLimiter>,
client:TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>) client:TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>)
-> BotManagers { -> BotManagers {
// let a = Arc::new(Mutex::new(BotManagers {
// // botmodules : ModulesManager::init(),
// identity : Arc::new(Mutex::new(IdentityManager::init())),
// chat : Chat::init(ratelimiters,client),
// }));
// a
BotManagers { BotManagers {
// botmodules : ModulesManager::init(), // botmodules : ModulesManager::init(),
identity : IdentityManager::init(), identity : Arc::new(RwLock::new(IdentityManager::init())),
chat : Chat::init(ratelimiters,client), chat : Chat::init(ratelimiters,client),
} }
} }
pub fn rIdentity(self) -> Arc<RwLock<IdentityManager>> {
self.identity
}
// pub fn rChat(&self) -> Arc<Mutex<Chat>> {
// Arc::new(Mutex::new(self.chat))
// }
} }
pub struct ArcBox<T: Clone>(pub Arc<Mutex<T>>);
impl<T: Clone> ArcBox<T>{
pub fn inst(&self) -> &Mutex<T> {
&self.0
}
}
//#[derive(Clone)]
// #[derive(Copy)] // <-- Cannot be derived
pub struct BotInstance pub struct BotInstance
{ {
prefix : char, pub prefix : char,
bot_channel : ChType, pub bot_channel : ChType,
pub incoming_messages : UnboundedReceiver<ServerMessage>, // pub incoming_messages : UnboundedReceiver<ServerMessage>,
pub incoming_messages : Arc<RwLock<UnboundedReceiver<ServerMessage>>>,
// pub incoming_messages : RefCell<UnboundedReceiver<ServerMessage>>,
// pub chat : Chat, // pub chat : Chat,
pub botmodules : ModulesManager, pub botmodules : Arc<ModulesManager>,
twitch_oauth : String, pub twitch_oauth : String,
pub bot_channels : Vec<ChType>, pub bot_channels : Vec<ChType>,
// pub identity : IdentityManager, // pub identity : IdentityManager,
// pub botmgrs : Arc<Mutex<BotManagers>>,
pub botmgrs : BotManagers, pub botmgrs : BotManagers,
} }
@ -180,7 +240,9 @@ impl BotInstance
{ {
pub fn init() -> BotInstance // pub fn init() -> BotInstance
// pub fn init() -> Arc<BotInstance>
pub async fn init() -> BotInstance
{ {
dotenv().ok(); dotenv().ok();
@ -229,13 +291,13 @@ impl BotInstance
let b = BotInstance { let b = BotInstance {
prefix : prefix, prefix : prefix,
bot_channel : Channel(login_name) , bot_channel : Channel(login_name) ,
incoming_messages : incoming_messages, incoming_messages : Arc::new(RwLock::new(incoming_messages)),
//client : client, //client : client,
// chat : Chat { // chat : Chat {
// ratelimiters : ratelimiters, // ratelimiters : ratelimiters,
// client : client, // client : client,
// } , // } ,
botmodules : ModulesManager::init(), botmodules : ModulesManager::init().await,
twitch_oauth : oauth_token, twitch_oauth : oauth_token,
bot_channels : botchannels, bot_channels : botchannels,
// identity : IdentityManager::init(), // identity : IdentityManager::init(),
@ -243,19 +305,127 @@ impl BotInstance
}; };
println!("{:?}",b.botmgrs.chat.ratelimiters); //println!("{:?}",b.botmgrs.chat.ratelimiters);
// Arc::new(b)
//Arc::new(RwLock::new(b))
b b
} }
pub async fn runner(mut self) -> () { // async fn rcv_helper(self) -> Option<ServerMessage> {
// // self.incoming_messages.get_mut().recv().await
// let mut a = self.incoming_messages;
// a.get_mut().recv().await
// }
// pub async fn runner(mut self) -> () {
// pub async fn runner(&'static mut self) -> () {
pub async fn runner(self) -> () {
// let bot_am = Arc::new(Mutex::new(self));
// let mut boxed_bot = Arc::new(RefCell::new(self)); // <-- [ERROR] Future cannot be handled safely
let bot = Arc::new(RwLock::new(self));
let join_handle = tokio::spawn(async move { let join_handle = tokio::spawn(async move {
while let Some(message) = &self.incoming_messages.recv().await { // let boxed_bot = Arc::new(Mutex::new(self));
// Below can be used to debug if I want to capture all messages // let mut boxed_bot = Arc::new(self);
// let bot = Rc::new(RefCell::new(self));
// let mut bot = Rc::new(RefCell::new(&self));
//let bot = Arc::new(Mutex::new(&self));
// let mut boxed_bot = Arc::new(RefCell::new(self));
// let mut boxed_bot = Arc::new(Mutex::new(self));
// while let Some(message) = bot.borrow_mut().incoming_messages.recv().await {
// let bot = Arc::clone(&botinit);
// while let Some(message) = bot.lock().unwrap().incoming_messages.recv().await {
//let b = Arc::clone(&bot);
// let mut bot = RefCell::new(&self);
// let mut bota = bot.clone().borrow();
// let boxed_bot = Rc::new(RefCell::new(self));
// let boxed_bot = Rc::new(self);
// let boxed_bot = Pin::new(Rc::new(self));
//let mut boxed_bot = Rc::new(RefCell::new(self));
// let mut a = (*boxed_bot).clone().into_inner();
// let mut a = Rc::clone(&boxed_bot).borrow_mut();
//let mut a = Rc::<Rc<RefCell<BotInstance>>>::Borrow(Rc::clone(&boxed_bot));
// while let Some(message) = Rc::clone(&boxed_bot).into_inner().incoming_messages.recv().await {
// while let Some(message) = Rc::<BotInstance>::borrow(Rc::<BotInstance>::as_ref(boxed_bot)) {
// let a = boxed_bot.borrow();
// let boxed_bota = boxed_bot.borrow_mut();
// let a = Rc::try_unwrap(boxed_bot).ok().unwrap().into_inner();
// let boxed_bot = RefCell::new(Rc::new(self));
//let boxed_bot = Rc::new(RefCell::new(self));
// Rc::try_unwrap(boxed_bot).ok().unwrap().into_inner().incoming_messages.recv().await;
// let a:Borrowed = boxed_bot.borrow();
// while let Some(message) = Rc::try_unwrap(boxed_bot).ok().unwrap().into_inner().incoming_messages.recv().await {
// while let Some(message) = RefCell::new(self).borrow_mut().incoming_messages.recv().await {
// while let Some(message) = Rc::try_unwrap(boxed_bot).ok().unwrap().into_inner().incoming_messages.recv().await {
// while let Some(message) = Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().rcv_helper().await {
// while let Some(message) = Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().incoming_messages.recv().await {
// let mut a = Arc::try_unwrap(boxed_bot.clone())
// .ok().unwrap()
// .into_inner()
// .ok().unwrap();
// let a = Arc::clone(&boxed_bot).into_inner().unwrap().incoming_messages;
// .into_inner()
// .try_into().
// .ok().unwrap();
// while let Some(message) = a.lock().unwrap().incoming_messages.recv().await {
// while let Some(message) = a.recv().await {
// let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap();
// let mut a = Arc::try_unwrap(boxed_bot.clone())
// .ok()
// .unwrap();
// .into_inner()
// .get_mut()
// .ok();
// .unwrap();
//let mut a = a.lock().unwrap();
// let a = *a;
// while let Some(message) = a.lock().ok().unwrap().incoming_messages.recv().await {
// while let Some(message) = a.get_mut().expect("Error").incoming_messages.recv().await {
//let tempbot = boxed_bot.clone();
// while let Some(message) = Arc::try_unwrap(tempbot.clone()).ok().unwrap().into_inner().ok().unwrap().incoming_messages.recv().await {
// while let Some(message) = Arc::try_unwrap(tempbot.clone()).ok().unwrap().incoming_messages.recv().await {
// while let Some(message) = boxed_bot.to_owned().incoming_messages.recv().await {
// while let Some(message) = self.incoming_messages.recv().await {
// let a:Arc<RefCell<BotInstance>> = Arc::clone(&boxed_bot);
// while let Some(message) = a.incoming_messages.recv().await {
// let a = Arc::clone(&boxed_bot).into_inner();
// while let Some(message) = a.incoming_messages.recv().await {
// let tempbot = boxed_bot.clone();
// while let Some(message) = Arc::try_unwrap(tempbot.clone()).ok().unwrap().into_inner().incoming_messages.recv().await {
// let tempbot = Arc::clone(&boxed_bot);
// while let Some(message) = tempbot.lock().await.incoming_messages.recv().await {
let a = bot.read().await;
let mut a = a.incoming_messages.write().await;
while let Some(message) = a.recv().await {
// while let Some(message) = tempbot.into_inner().incoming_messages.recv().await {
//while let Some(message) = boxed_bot.borrow().incoming_messages.recv().await {
// // Below can be used to debug if I want to capture all messages
// println!("Received message: {:?}", message); // println!("Received message: {:?}", message);
// let boxed_bot = Arc::new(self);
match message { match message {
ServerMessage::Notice(msg) => { ServerMessage::Notice(msg) => {
@ -273,7 +443,55 @@ impl BotInstance
println!("Privmsg section"); println!("Privmsg section");
// b.listener_main_prvmsg(&msg); // b.listener_main_prvmsg(&msg);
self.listener_main_prvmsg(&msg).await; // self.listener_main_prvmsg(&msg).await;
// bot.into_inner().listener_main_prvmsg(&msg).await;
//let bot = Rc::<RefCell<&BotInstance>>::clone(&bot);
// bot.borrow().listener_main_prvmsg(&msg).await;
// let mut a = Rc::Clone(&bot);
// a.borrow_mut().listener_main_prvmsg(&msg).await;
// bot.borrow_mut().into_inner().listener_main_prvmsg(&msg).await;
// bot.listener_main_prvmsg(&msg).await;
// bot.lock().unwrap().listener_main_prvmsg(&msg).await;
// bot.borrow_mut().listener_main_prvmsg(&msg).await;
// Rc::clone(&boxed_bot).into_inner().listener_main_prvmsg(&msg).await;
// boxed_bot.borrow().listener_main_prvmsg(&msg).await;
// let bottemp = boxed_bot.borrow_mut();
// let a = **bottemp;
// Rc::try_unwrap(boxed_bot).ok().unwrap().into_inner().listener_main_prvmsg(&msg).await;
// Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().listener_main_prvmsg(&msg).await;
// Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().ok().unwrap().listener_main_prvmsg(&msg).await;
// let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap();
// let mut a = a.lock().unwrap();
// let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap();
// a.listener_main_prvmsg(&msg).await;
// (*a).listener_main_prvmsg(&msg).await;
// let a:Arc<RefCell<BotInstance>> = Arc::clone(&boxed_bot);
// a.into_inner().listener_main_prvmsg(&msg).await;
// let tempbot = boxed_bot.clone();
// Arc::try_unwrap(tempbot.clone()).ok().unwrap().into_inner().listener_main_prvmsg(&msg).await ;
// let tempbot = Arc::clone(&tempbot);
// // let a = tempbot.lock().await;
// tempbot.lock().await.listener_main_prvmsg(&msg).await;
// self.listener_main_prvmsg(&msg).await;
// bot.read().await.listener_main_prvmsg(&msg).await;
// let a = bot.read().await;
// a.listener_main_prvmsg(&msg).await;
// a.listener_main_prvmsg(&msg).await;
// let a = bot.read().await;
BotInstance::listener_main_prvmsg(Arc::clone(&bot), &msg).await;
// let a = bot.read().await;
// a.lis
//self.listener_main_prvmsg(&msg).await;
// - BotCommand listener should likely need to be called within the above // - BotCommand listener should likely need to be called within the above
@ -297,27 +515,187 @@ impl BotInstance
join_handle.await.unwrap(); join_handle.await.unwrap();
} }
pub fn get_botmodules(self) -> Arc<ModulesManager> {
// let a = self.botmodules;
// Arc::clone(&Arc::new(Mutex::new(self.botmodules)))
// *self.botmodules
self.botmodules
}
// pub fn get_botactions(self:&Self) -> (Self,HashMap<botmodules::ModType,Vec<BotAction>>) {
// // self.get_botactions()
// // (*self,(*self).botmodules.rbotactions())
// (Self { bot_channel},(*self).botmodules.rbotactions())
// }
// pub fn get_botactions(&self) -> (Self,HashMap<botmodules::ModType,Vec<BotAction>>) {
// pub fn get_botactions(&self) -> HashMap<botmodules::ModType,Vec<BotAction>> {
// // self.get_botactions()
// // (*self,(*self).botmodules.rbotactions())
// // (self,self.botmodules.rbotactions())
// // (*self).botmodules.rbotactions()
// // let a = (*self).botmodules.rbotactions();
// let a =
// a
// }
pub async fn get_botmgrs(self) -> BotManagers {
// Arc::new(self.botmgrs)
// Arc::clone(&Arc::new(Mutex::new(self.botmgrs)))
let a = self.botmgrs;
// let a = *a.lock().await;
// let a = a.rIdentity();
a
}
// pub fn get_identity(self:&Self) -> (Self,IdentityManager) {
pub fn get_identity(&self) -> Arc<RwLock<IdentityManager>> {
// // let a = self.botmgrs;
// // Arc::clone(&Arc::new(Mutex::new(a.rIdentity())))
// // let a = self.botmgrs;
// // Arc::clone(&Arc::new(Mutex::new(a.rIdentity())))
// let a = self.get_botmgrs().await;
// let a = a.lock().await;
// // let a = a.rIdentity();
// let a = a.clone().identity;
// a.clone()
// let id = (*self).botmgrs.identity;
// id
Arc::clone(&self.botmgrs.identity)
}
// pub fn get_prefix(self) -> (Self,char) {
pub fn get_prefix(&self) -> char {
// self.prefix.to_string()
// let a = self.prefix;
// a.clone().to_string()
// (self,self.prefix)
(*self).prefix
}
// pub fn get_prefix(self:&Self) -> (Self,String) {
// (*self,(*self).prefix.to_string())
// }
// pub fn get_prefix(self:Self) -> (Self,String) {
// let str1 = self.prefix.to_string();
// (self,str1)
// }
// pub fn get_prefix(&self) -> String {
// // self.prefix.to_string()
// let a = self.prefix;
// a.clone().to_string()
// }
// pub fn get_prefix(self) -> (Self,String) {
// // self.prefix.to_string()
// // let a = self.prefix;
// // a.clone().to_string()
// (Self {
// prefix : self.prefix ,
// bot_channel : self.bot_channel ,
// incoming_messages : self.incoming_messages ,
// botmodules : self.botmodules,
// twitch_oauth : self.twitch_oauth,
// bot_channels : self.bot_channels ,
// // identity : IdentityManager::init(),
// botmgrs: self.botmgrs ,
// },
// self.prefix.to_string())
// }
// ----------------- // -----------------
// PRIVATE FUNCTIONS // PRIVATE FUNCTIONS
// async fn listener_main_prvmsg(&mut self,msg:PrivmsgMessage) -> () { // async fn listener_main_prvmsg(&mut self,msg:PrivmsgMessage) -> () {
async fn listener_main_prvmsg(&mut self,msg:&PrivmsgMessage) -> () { // async fn listener_main_prvmsg(&mut self,msg:&PrivmsgMessage) -> () {
// async fn listener_main_prvmsg(self,msg:&PrivmsgMessage) -> () {
// async fn listener_main_prvmsg(self:Arc<Self>,msg:&PrivmsgMessage) -> () {
pub async fn listener_main_prvmsg(bot:BotAR,msg:&PrivmsgMessage) -> () {
println!(">> Inner listenermain_prvmsg()");
// let a = a;
// println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text);
// // [ ] Need to run through all Listener Bodies for Enabled Modules for the context of the message (e.g., ModStatus is Enabled in the context for the channel) // // [ ] Need to run through all Listener Bodies for Enabled Modules for the context of the message (e.g., ModStatus is Enabled in the context for the channel)
for (_m,acts) in &self.botmodules.botactions { // let botmgr = Rc::new(&self.botmgrs);
// let mut boxedbot = Rc::new(RefCell::new(self));
// let boxed_bot = Rc::new(RefCell::new(self));
// let boxed_bot = Arc::new(Mutex::new(self));
// let boxed_bot = Arc::new(self);
//let boxed_bot = Arc::clone(self);
// let mut boxed_bot = Arc::new(RefCell::new(self));
// let mut boxed_bot = Arc::new(RwLock::new(self));
// let boxed_bot = Arc::new(RwLock::new(self));
// let boxed_bot = Arc::new(Mutex::new(self));
//let boxed_bot = Arc::new(Mutex::new(self));
// let bot = Arc::new(RwLock::new(self));
// for (_m,acts) in &self.botmodules.botactions {
// for (_m,acts) in &self.botmodules.botactions {
// for (_m,acts) in bot.into_inner().botmodules.botactions {
// let mut bot = Rc::clone(&bot);
// for (_m,acts) in bot.into_inner().botmodules.botactions {
// for (_m,acts) in bot.into_inner().botmodules.botactions {
// for (_m,acts) in Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().botmodules.botactions {
// for (_m,acts) in Arc::try_unwrap(boxed_bot.clone()).ok() .unwrap().into_inner().ok().unwrap().botmodules.botactions {
// for (_m,acts) in Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().botmodules.botactions {
// for (_m,acts) in Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().botmodules.botactions {
// let a = Arc::try_unwrap(boxed_bot).ok().unwrap().read().unwrap().botmodules.botactions
// let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap();
// let b = a.read().unwrap();
// for (_m,acts) in a.read().unwrap().botmodules.botactions {
// for (_m,acts) in b.rbotmodules().botactions {
// for (_m,acts) in b.rbotactions() {
// for (_m,acts) in (*Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().read().unwrap()).rbotactions() {
// let a = boxed_bot.clone().into_inner();
// let a = boxed_bot.lock().await;
//let a = a.lock().in
// for (_m,acts) in self.rbotactions() {
// for (_m,acts) in a.read().ok().unwrap().rbotactions() {
// for (_m,acts) in a.into_inner().ok().unwrap().rbotactions() {
// let bot = self;
// let mut instr:char;
// let hacts = self.get_botactions();
// let hacts = boxed_bot.clone().lock().await.get_botactions();
// let hacts = bot.read().await.get_botactions();
let botlock = bot.read().await;
let hacts = Arc::clone(&botlock.botmodules.botactions);
// let hacts = hacts.read().await;
let a = hacts.read().await;
println!("hacts size : {}",(*a).len());
println!(">> Inner listenermain_prvmsg() >> before for loop of bot actions");
// println!(">> Inner listenermain_prvmsg() >> before for loop of bot actions : {:?}",*hacts);
// let hacts = hacts
// let l = *hacts;
for (_m,acts) in &*hacts.read().await {
println!(">> Inner listenermain_prvmsg() >> checking bot actions");
// let bot = bot;
for a in acts { for a in acts {
// match a { println!(">> Inner listenermain_prvmsg() >> checking bot actions >> 2");
// let Some((b,msg)) = match a {
let b = match a {
let _act = match a {
crate::core::botmodules::BotAction::C(c) => { crate::core::botmodules::BotAction::C(c) => {
/* /*
@ -334,6 +712,8 @@ impl BotInstance
// println!("args : {v}"); // println!("args : {v}");
// } // }
println!("Reviewing internal commands");
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");
@ -344,19 +724,61 @@ impl BotInstance
// [x] prefix + command // [x] prefix + command
let mut confirmed_bot_command = false; let mut confirmed_bot_command = false;
if inpt == self.prefix.to_string() + c.command.as_str() {
// if inpt == self.prefix.to_string() + c.command.as_str() {
// if inpt == Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().prefix.to_string() + c.command.as_str() {
// let a = Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().prefix.to_string();
// let a = Arc::try_unwrap(boxed_bot.clone()).ok() .unwrap().into_inner().ok().unwrap().prefix.to_string();
// let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().prefix.to_string();
// let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().prefix.to_string();
// let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap();
// let a = (*Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().read().unwrap());
// let a = (*Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().read().unwrap()).prefix.to_string();
// let a = self.prefix.to_string();
// let a = boxed_bot.clone();
// if inpt == a.into_inner().ok().unwrap().prefix.to_string() + c.command.as_str() {
// if inpt == a.into_inner().ok().unwrap().prefix.to_string() + c.command.as_str()
// let a = boxed_bot.lock().await;
//
// if inpt == a.into_inner().prefix.to_string() + c.command.as_str() {
// if inpt == a.get_prefix() + c.command.as_str() {
// if inpt == self.get_prefix() + c.command.as_str() {
// let instr = self.get_prefix();
// let instr = boxed_bot.clone().lock().await.get_prefix();
// let instr = bot.read().await.get_prefix();
let instr = bot.read().await.get_prefix();
if inpt == String::from(instr) + c.command.as_str() {
confirmed_bot_command = true; confirmed_bot_command = true;
} }
// [x] prefix + alias // [x] prefix + alias
for alias in &c.alias { for alias in &c.alias {
if inpt == self.prefix.to_string() + alias.as_str() { // if inpt == self.prefix.to_string() + alias.as_str() {
// if inpt == Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().prefix.to_string() + alias.as_str() {
//
// if inpt == Arc::try_unwrap(boxed_bot.clone()).ok() .unwrap().into_inner().ok().unwrap().prefix.to_string() + alias.as_str() {
// Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner()
// if inpt == Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().prefix.to_string() + alias.as_str() {
// if inpt == Arc::try_unwrap(boxed_bot).ok().unwrap().read().unwrap().prefix.to_string() + alias.as_str() {
// if inpt == self.prefix.to_string() + alias.as_str() {
// let a = boxed_bot.clone();
// let a = boxed_bot.lock().await;
// if inpt == a.into_inner().ok().unwrap().prefix.to_string() + alias.as_str() {
// if inpt == a.into_inner().prefix.to_string() + alias.as_str() {
// if inpt == a.get_prefix() + alias.as_str() {
// if inpt == self.get_prefix() + alias.as_str() {
// let instr = self.get_prefix();
// let instr = boxed_bot.clone().lock().await.get_prefix();
// let instr = bot.read().await.get_prefix();
let instr = bot.read().await.get_prefix();
if inpt == String::from(instr) + alias.as_str() {
confirmed_bot_command = true; confirmed_bot_command = true;
} }
} }
if confirmed_bot_command { if confirmed_bot_command {
println!("Confirmed bot command");
// self.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone()); // self.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone());
// [ ] Around here, validate if permissable before executing // [ ] Around here, validate if permissable before executing
@ -368,65 +790,117 @@ impl BotInstance
// match self.botmgrs.identity.to_owned().can_user_run_PRVMSG(&msg, c.required_roles.clone()) { // match self.botmgrs.identity.to_owned().can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// match self.botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) { // match self.botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// let a = match self.botmgrs.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// match self.botmgrs.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone()) { // match self.botmgrs.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
match self.botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// let botref = Rc::clone(&botmgr);
// if let Rc(botmgr) = botref {
// ()
// }
// match self.botmgrs.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// match boxed_bot.clone().into_inner().botmgrs.identity.clone().can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// match Rc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner().botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
//let boxed_bot1 = Arc::clone(&boxed_bot);
//let a = boxed_bot1.into_inner().ok().unwrap();
// match boxed_bot1.into_inner().ok().unwrap().botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// match Arc::try_unwrap(boxed_bot.clone())
// .ok()
// .unwrap().into_inner().ok().unwrap().botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// let a = Arc::try_unwrap(boxed_bot.clone()).ok() .unwrap().into_inner();
// let a = Arc::try_unwrap(boxed_bot.clone()).ok().unwrap();
// Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner()
// match a.botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// match Arc::try_unwrap(boxed_bot).ok().unwrap().read().unwrap().botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// match self.botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// match (boxed_bot.clone().into_inner().ok().unwrap()).botmgrs.identity.can_user_run_PRVMSG(&msg, c.required_roles.clone()) {
// let a = boxed_bot.clone();
// let a = boxed_bot.lock().await;
// // let a = a.read().ok().unwrap().botmgrs.identity;
// let a = a.get_identity();
// // let a = a.lock().await.can_user_run_PRVMSG(&msg, c.required_roles.clone()) ;
// match a.lock().await.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await {
// let le = boxed_bot.lock().await;
// // let le = le.lock().await;
// let le = le.get_identity().await;
// let le = *le;
// let le = le.lock().await;
// let le = le.clone();
// let le = le.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await;
// let le = self.get_identity().await.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await;
// let le = self.botmgrs;
// let le = le.identity;
// let (bot,id) = self.get_identity();
// let id = boxed_bot.clone().lock().await.get_identity();
// let id = bot.read().await.get_identity();
// let id = Arc::clone(&self.botmgrs.identity);
// let id = id.write().await;
// let id = &(*self.get_identity());
println!("Going for botlock");
let botlock = bot.read().await;
println!("Going for identity");
let id = botlock.get_identity();
// let mut id = id.write().await;
// println!("Unlocking identity");
// let eval= id.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await;
let eval = {
let mut id = id.write().await;
println!("Unlocking identity");
id.can_user_run_PRVMSG(&msg, c.required_roles.clone()).await
};
println!("Checking if permissible");
match eval {
// Ok(Permissible::Allow) => (), // Ok(Permissible::Allow) => (),
Permissible::Allow => { Permissible::Allow => {
println!("Executed as permissible"); println!("Executed as permissible");
// c.execute(self.botmgrs.clone(), msg.clone()).await; // c.execute(bot, msg.clone()).await;
// c.execute(self.botmgrs, msg.clone()).await; // if let bot = Rc::<RefCell<BotInstance>>::clone(*bot) {
// Some((BotAction::C(c),msg.clone())) // c.execute(bot, msg.clone()).await;
// Some((msg,self)) // }
Some(msg) // let boxed_bot = Arc::new(RwLock::new(self));
//Some(BotAction::C(*c)) // c.execute(boxed_bot.clone(), msg.clone()).await;
//Some(String::from("Hello")) // c.execute(self, msg.clone()).await;
//let mut a = *self;
// c.execute(self, msg.clone());
// let a = self;
// let a = Arc::clone(&self);
let a = Arc::clone(&bot);
// let a = Arc::clone(&bot);
c.execute(a, msg.clone()).await;
println!("exit out of execution");
} }
Permissible::Block => { Permissible::Block => {
println!("User Not allowed to run command"); println!("User Not allowed to run command")
// None::<(BotAction,PrivmsgMessage)>
// None::<(&PrivmsgMessage,&mut BotInstance)>
None::<&PrivmsgMessage>
//None
//Some(String::from("Hello"))
}, },
// _ => (), // _ => (),
}; };
};
// c.execute(self.chat.clone(), msg.clone()).await; // c.execute(self.chat.clone(), msg.clone()).await;
} }
None::<&PrivmsgMessage> // [ ] Command not confirmed? None::<&PrivmsgMessage> // [ ] Command not confirmed?
None::<&PrivmsgMessage> // [ ] Command not confirmed?
}, },
// crate::core::botmodules::BotAction::L(l) => l.execute(self.botmgrs.clone(), msg.clone()).await, crate::core::botmodules::BotAction::L(l) => {
//crate::core::botmodules::BotAction::L(l) => l.execute(self.botmgrs, msg.clone()).await, // if let bot = Rc::clone(&bot) {
// l.into_inner().execute(bot, msg.clone()).await
// }
//let bot = Rc::clone(&bot).into_inner();
// l.execute(boxed_bot.clone(), msg.clone()).await
// let boxed_bot = Arc::new(RwLock::new(self));
// l.execute(boxed_bot.clone(), msg.clone()).await;
// let a = Arc::clone(&self);
let a = Arc::clone(&bot);
l.execute(a, msg.clone()).await;
},
_ => None::<&PrivmsgMessage> , // -- [ ] If not any known botaction _ => (),
}; };
// b = BotAction either found or not
match b {
Some(b) => {
// a.execute(self.botmgrs.clone(), b.clone()).await; // This compiles but issue - botmgrs aren't updating
// a.execute(self.botmgrs, b.clone()).await; // This throws the following
// /*
// error[E0507]: cannot move out of `self.botmgrs` which is behind a shared reference
// --> src\core\botinstance.rs:409:35
// |
// 409 | a.execute(self.botmgrs, b.clone()).await; // This throws
// | ^^^^^^^^^^^^ move occurs because `self.botmgrs` has type `BotManagers`, which does not implement the `Copy` trait
// */
let (msg) = b;
// a.execute(self.botmgrs.clone(), msg.clone()).await;
a.execute(self.botmgrs, msg.clone()).await;
}
None => (),
}
} }
}; };
@ -436,6 +910,9 @@ impl BotInstance
println!("End of Separate Listener Main prvmsg"); println!("End of Separate Listener Main prvmsg");
// self
// bot
} }

View file

@ -5,6 +5,26 @@ use std::collections::HashMap;
use crate::core::identity; use crate::core::identity;
use std::cell::RefCell;
use std::sync::Arc;
use tokio::sync::RwLock;
use std::future::Future;
// use futures::lock::Mutex;
// Important to use tokios Mutex here since std Mutex doesn't work with async functions
use tokio::sync::Mutex;
use crate::core::botinstance::{self, BotInstance};
use std::rc::Rc;
// use tokio::sync::RwLock;
use async_trait::async_trait;
/* /*
@ -43,7 +63,8 @@ pub enum ChType {
pub use ChType::Channel; pub use ChType::Channel;
use twitch_irc::message::PrivmsgMessage; use twitch_irc::message::PrivmsgMessage;
use crate::core::botinstance::{self, BotInstance}; use self::bot_actions::actions_util;
use self::bot_actions::actions_util::BotAR;
#[derive(Debug)] #[derive(Debug)]
@ -57,7 +78,8 @@ pub enum ModStatusType {
Enabled(StatusLvl), Enabled(StatusLvl),
Disabled(StatusLvl), Disabled(StatusLvl),
} }
// #[derive(Clone)]
pub enum BotAction pub enum BotAction
{ {
C(BotCommand), C(BotCommand),
@ -66,7 +88,9 @@ pub enum BotAction
} }
impl BotAction { impl BotAction {
pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){ // pub async fn execute(&self,m:botinstance::BotManagers,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,
@ -77,13 +101,15 @@ impl BotAction {
} }
} }
#[async_trait]
pub trait BotActionTrait pub trait BotActionTrait
{ {
fn add_to_bot(self, bot:BotInstance); async fn add_to_bot(self, bot:BotInstance);
fn add_to_modmgr(self,modmgr:&mut ModulesManager); // async fn add_to_modmgr(self,modmgr:&'static ModulesManager);
async fn add_to_modmgr(self,modmgr:Arc<ModulesManager>);
} }
// #[derive(Clone)]
pub struct BotCommand { pub struct BotCommand {
pub module : ModType, pub module : ModType,
pub command : String, // command call name pub command : String, // command call name
@ -96,21 +122,40 @@ pub struct BotCommand {
impl BotCommand impl BotCommand
{ {
pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){ // pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){
(self.exec_body)(m,n).await; // pub async fn execute(&self,m:Rc<&botinstance::BotManagers>,n:PrivmsgMessage){
// pub async fn execute(&self,m:BotInstance,n:PrivmsgMessage){
// (self.exec_body)(m,n).await;
// }
// pub fn execute(&self,m:&mut BotInstance,n:PrivmsgMessage) -> () {
// pub fn execute(&self,m:actions_util::BotAR,n:PrivmsgMessage) -> () {
pub async fn execute(&self,m:BotAR,n:PrivmsgMessage) -> () {
// ((*self).exec_body)(m,n);
// ((*self).exec_body)(*m,n);
// m
// ((*self).exec_body)(
((*self).exec_body)(m,n).await;
// m
} }
} }
#[async_trait]
impl BotActionTrait for BotCommand impl BotActionTrait for BotCommand
{ {
fn add_to_bot(self, mut bot:BotInstance) { async fn add_to_bot(self, bot:BotInstance) {
let mgr = &mut bot.botmodules; // let mgr = &mut bot.botmodules;
self.add_to_modmgr(mgr); // let mut mgr = *mgr.lock().await;
// let mut mgr = &mut mgr;
// (*self).add_to_modmgr(bot.botmodules);
self.add_to_modmgr(bot.botmodules).await;
} }
fn add_to_modmgr(self, modmgr:&mut ModulesManager) { // async fn add_to_modmgr(self, modmgr:Arc<Mutex<ModulesManager>>) {
modmgr.add_botaction(self.module.clone(), BotAction::C(self)) async fn add_to_modmgr(self, modmgr:Arc<ModulesManager>) {
// modmgr.add_botaction(self.module.clone(), BotAction::C(self))
// let modmgr = *modmgr.lock().await;
// modmgr.add_botaction(self.module.clone(), BotAction::C(self))
modmgr.add_botaction(self.module.clone(), BotAction::C(self)).await
} }
} }
@ -125,18 +170,69 @@ pub mod bot_actions {
use std::boxed::Box; use std::boxed::Box;
use std::pin::Pin; use std::pin::Pin;
use crate::core::botinstance::{BotManagers, Chat}; use std::rc::Rc;
use crate::core::botinstance::{BotInstance, BotManagers, Chat};
use twitch_irc::message::PrivmsgMessage; use twitch_irc::message::PrivmsgMessage;
use std::cell::RefCell;
use std::sync::{Arc};
// use futures::lock::Mutex;
// Important to use tokios Mutex here since std Mutex doesn't work with async functions
use tokio::sync::{Mutex,RwLock};
pub type BotAM = Arc<Mutex<BotInstance>>;
pub type BotAR = Arc<RwLock<BotInstance>>;
// pub type ExecBody = Box<dyn Fn(Chat,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>; // pub type ExecBody = Box<dyn Fn(Chat,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
//pub type ExecBody<F> = Box<dyn Fn(Chat,PrivmsgMessage) -> Pin<Box<dyn Future<Output=F> + Send>> + Send + Sync>; //pub type ExecBody<F> = Box<dyn Fn(Chat,PrivmsgMessage) -> Pin<Box<dyn Future<Output=F> + Send>> + Send + Sync>;
pub type ExecBody = Box<dyn Fn(BotManagers,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>; // pub type ExecBody = Box<dyn Fn(BotManagers,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Rc<&BotManagers>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Rc<&BotInstance>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Rc<RefCell<BotInstance>>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Rc<RefCell<BotInstance>>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Rc<RefCell<&BotInstance>>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Arc<&BotInstance>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Arc<RefCell<&BotInstance>>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(RefCell<&BotInstance>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Rc<RefCell<BotInstance>>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Arc<Mutex<BotInstance>>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Arc<BotInstance>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Arc<RefCell<BotInstance>>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Arc<RwLock<BotInstance>>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(Arc<Mutex<BotInstance>>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(BotInstance,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody<F> = Box<dyn Fn(&BotInstance,PrivmsgMessage) -> Pin<Box<dyn Future<Output=F> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(&'static BotInstance,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
// pub type ExecBody = Box<dyn Fn(&mut BotInstance,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 type ExecBody = Box<dyn Fn(Arc<BotInstance>,PrivmsgMessage) -> Pin<Box<dyn Future<Output=()> + Send>> + Send + Sync>;
//pub fn asyncbox<T,F>(f: fn(Chat,PrivmsgMessage) -> T) -> ExecBody<F> //pub fn asyncbox<T,F>(f: fn(Chat,PrivmsgMessage) -> T) -> ExecBody<F>
// pub fn asyncbox<T>(f: fn(Chat,PrivmsgMessage) -> T) -> ExecBody // pub fn asyncbox<T>(f: fn(Chat,PrivmsgMessage) -> T) -> ExecBody
pub fn asyncbox<T>(f: fn(BotManagers,PrivmsgMessage) -> T) -> ExecBody // pub fn asyncbox<T>(f: fn(BotManagers,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(Rc<&BotManagers>,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(Rc<RefCell<BotInstance>>,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(Rc<RefCell<&BotInstance>>,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(Arc<&BotInstance>,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(Arc<RefCell<&BotInstance>>,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(Rc<RefCell<BotInstance>>,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(Arc<Mutex<BotInstance>>,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(Arc<BotInstance>,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(Arc<RefCell<BotInstance>>,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(Arc<RwLock<BotInstance>>,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(Arc<Mutex<BotInstance>>,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(BotInstance,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(&'static BotInstance,PrivmsgMessage) -> T) -> ExecBody
// pub fn asyncbox<T>(f: fn(&mut BotInstance,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
// T: Future<Output=F> + 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)))
} }
@ -157,22 +253,43 @@ pub struct Listener
impl Listener impl Listener
{ {
pub async fn execute(&self,m:botinstance::BotManagers,n:PrivmsgMessage){ // pub async fn execute(&self,m:BotInstance,n:PrivmsgMessage){
(self.exec_body)(m,n).await; // (self.exec_body)(m,n).await;
// }
// pub fn execute(&self,m:BotInstance,n:PrivmsgMessage){
// (self.exec_body)(m,n);
// }
// pub fn execute(&self,m:&BotInstance,n:PrivmsgMessage) -> &BotInstance {
// pub fn execute(&self,m:actions_util::BotAR,n:PrivmsgMessage) -> () {
pub async fn execute(&self,m:BotAR,n:PrivmsgMessage) -> () {
// let mut m = Arc::*m;
((*self).exec_body)(m,n).await;
// *self
// &m
} }
} }
#[async_trait]
impl BotActionTrait for Listener impl BotActionTrait for Listener
{ {
fn add_to_bot(self, mut bot:BotInstance) { async fn add_to_bot(self, bot:BotInstance) {
let mgr = &mut bot.botmodules; // let mgr = &mut bot.botmodules;
// let mgr = bot.botmodules;
self.add_to_modmgr(mgr); // self.add_to_modmgr(Arc::new(*mgr));
println!("Adding action to bot");
self.add_to_modmgr(bot.botmodules).await;
} }
fn add_to_modmgr(self, modmgr:&mut ModulesManager) { // fn add_to_modmgr(self, modmgr:&mut ModulesManager) {
modmgr.add_botaction(self.module.clone(), BotAction::L(self)) // async fn add_to_modmgr(self, modmgr:Arc<Mutex<ModulesManager>>) {
// async fn add_to_modmgr(self, modmgr:&'static ModulesManager) {
// async fn add_to_modmgr(self, modmgr:&'static ModulesManager) {
async fn add_to_modmgr(self, modmgr:Arc<ModulesManager>) {
// let modmgr = *modmgr.lock().await;
println!("Adding action to module manager");
modmgr.add_botaction(self.module.clone(), BotAction::L(self)).await;
// modmgr.add_botaction(self.module.clone(), BotAction:L(self))
} }
} }
@ -182,16 +299,21 @@ impl BotActionTrait for Listener
#[derive(Debug)] #[derive(Debug)]
struct Routine {} struct Routine {}
// #[derive(Clone)]
pub struct ModulesManager pub struct ModulesManager
{ {
statusdb: HashMap<ModType,Vec<ModStatusType>>, // statusdb: HashMap<ModType,Vec<ModStatusType>>,
pub botactions: HashMap<ModType,Vec<BotAction>>, statusdb: Arc<RwLock<HashMap<ModType,Vec<ModStatusType>>>>,
// pub botactions: HashMap<ModType,Vec<BotAction>>,
pub botactions: Arc<RwLock<HashMap<ModType,Vec<BotAction>>>>,
} }
impl ModulesManager impl ModulesManager
{ {
pub fn init() -> ModulesManager // pub fn init() -> Arc<Mutex<ModulesManager>>
pub async fn init() -> Arc<ModulesManager>
{ {
@ -199,23 +321,43 @@ impl ModulesManager
let act = HashMap::new(); let act = HashMap::new();
let mut mgr = ModulesManager { let mut mgr = ModulesManager {
statusdb : m, statusdb : Arc::new(RwLock::new(m)),
botactions : act, botactions : Arc::new(RwLock::new(act)),
}; };
// initialize core modules // :: [x] initialize core modules
crate::core::identity::init(&mut mgr); // crate::core::identity::init(&mut mgr);
// let a = Arc::new(Mutex::new(mgr));
// // let a = a.clone();
// crate::core::identity::init(a.clone());
// crate::core::identity::init(&mgr);
println!("ModulesManager > init() > Adding modules");
let mgra = Arc::new(mgr);
crate::core::identity::init(Arc::clone(&mgra)).await;
// initialize custom crate modules // initialize custom crate modules
crate::modules::init(&mut mgr); // crate::modules::init(&mut mgr);
// let a = a.clone();
// crate::modules::init(a.clone());
crate::modules::init(Arc::clone(&mgra)).await;
println!(">> Modules Manager : End of Init"); println!(">> Modules Manager : End of Init");
mgr // mgr
mgra
} }
// pub async fn rbotactions(&self) -> HashMap<ModType,Vec<BotAction>> {
// // (*self).botactions
// let a = self.botactions.read().await;
// *a
// }
pub fn modstatus(&self, _:ModType, _:ChType) -> ModStatusType { pub fn modstatus(&self, _:ModType, _:ChType) -> ModStatusType {
// Example usage : botmanager.modstatus( // Example usage : botmanager.modstatus(
// BotModule("GambaCore"), // BotModule("GambaCore"),
@ -243,7 +385,8 @@ impl ModulesManager
//pub fn add_botaction(mut self, in_module:ModType, in_action:BotAction ) -> ModulesManager { //pub fn add_botaction(mut self, in_module:ModType, in_action:BotAction ) -> ModulesManager {
// pub fn add_botaction(mut self, in_module:ModType, in_action:BotAction<F> ) -> ModulesManager<F> { // pub fn add_botaction(mut self, in_module:ModType, in_action:BotAction<F> ) -> ModulesManager<F> {
//pub fn add_botaction(&mut self, in_module:ModType, in_action:BotAction ) -> () { //pub fn add_botaction(&mut self, in_module:ModType, in_action:BotAction ) -> () {
pub fn add_botaction(&mut self, in_module:ModType, in_action:BotAction ) { pub async fn add_botaction(&self, in_module:ModType, in_action:BotAction ) {
println!("Add botaction called");
/* /*
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
@ -271,7 +414,7 @@ impl ModulesManager
// - 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
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")))
@ -289,7 +432,8 @@ impl ModulesManager
// let n = & mgr.botactions; // let n = & mgr.botactions;
let d = &mgr.botactions; let d = mgr.botactions.read().await;
let d = &(*d);
for (module,moduleactions) in d { for (module,moduleactions) in d {
@ -360,20 +504,30 @@ impl ModulesManager
// // () // return because there was a conflict? // // () // return because there was a conflict?
// panic!("ERROR: Could not add {:?} ; there was a conflict with existing module {:?}", in_action , probmod ); // panic!("ERROR: Could not add {:?} ; there was a conflict with existing module {:?}", in_action , probmod );
// } // }
match find_conflict_module(&self, &in_action) { 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 => (),
} }
let statusvector = self.statusdb // {
// let mut lala = self;
// let statusvector = (*lala).statusdb
// // .entry(BotModule(String::from("experiments")))
// .entry(in_module.clone())
// .or_insert(Vec::new());
// }
let mut dbt = self.statusdb.write().await;
let statusvector = dbt
// .entry(BotModule(String::from("experiments"))) // .entry(BotModule(String::from("experiments")))
.entry(in_module.clone()) .entry(in_module.clone())
.or_insert(Vec::new()); .or_insert(Vec::new());
statusvector.push(ModStatusType::Enabled(StatusLvl::Instance)); // Pushes the Module as Enabled at Instance Level statusvector.push(ModStatusType::Enabled(StatusLvl::Instance)); // Pushes the Module as Enabled at Instance Level
let modactions = self.botactions let mut a = self.botactions.write().await;
let modactions = a
//.entry( BotModule(String::from("experiments"))) //.entry( BotModule(String::from("experiments")))
.entry( in_module.clone()) .entry( in_module.clone())
.or_insert(Vec::new()); .or_insert(Vec::new());
@ -382,6 +536,7 @@ impl ModulesManager
modactions.push(in_action); modactions.push(in_action);
println!(">> Modules Manager : Called Add bot Action"); println!(">> Modules Manager : Called Add bot Action");
println!("add_botaction - botactions size : {}",modactions.len());
//println!(">> Modules Manager : {:?}",&self); //println!(">> Modules Manager : {:?}",&self);
//(); //();

View file

@ -1,24 +1,44 @@
use std::borrow::Borrow;
use std::collections::HashMap; use std::collections::HashMap;
use std::error::Error; use std::error::Error;
use crate::core::botmodules::{ModulesManager,Listener,BotModule,BotActionTrait, BotCommand}; use crate::core::botmodules::{ModulesManager,Listener,BotModule,BotActionTrait, BotCommand};
use crate::core::botmodules::bot_actions::actions_util; use crate::core::botmodules::bot_actions::actions_util;
use crate::core::botinstance::{self}; use crate::core::botinstance::{self,BotInstance};
use futures::lock::Mutex;
use twitch_irc::message::{Badge, PrivmsgMessage}; use twitch_irc::message::{Badge, PrivmsgMessage};
use crate::core::botmodules::ChType; use crate::core::botmodules::ChType;
use crate::core::botinstance::ArcBox;
use std::rc::Rc;
use std::cell::RefCell;
use std::sync::{Arc};
use tokio::sync::RwLock;
use super::botmodules::bot_actions::actions_util::BotAR;
fn adminvector() -> Vec<String> { fn adminvector() -> Vec<String> {
vec![String::from("ModulatingForce")] vec![String::from("ModulatingForce")]
} }
pub fn init(mgr:&mut ModulesManager) // pub fn init(mgr:&mut ModulesManager)
pub async fn init(mgr:Arc<ModulesManager>)
{ {
BotCommand { println!("Went into Identiy Module init");
// let a = actions_util::asyncbox(cmd_promote) ;
let tempb = BotCommand {
module : BotModule(String::from("identity")), module : BotModule(String::from("identity")),
command : String::from("promote"), // command call name command : String::from("promote"), // command call name
alias : vec![], // String of alternative names alias : vec![], // String of alternative names
@ -30,9 +50,14 @@ pub fn init(mgr:&mut ModulesManager)
UserRole::Broadcaster, UserRole::Broadcaster,
UserRole::BotAdmin, UserRole::BotAdmin,
], ],
}.add_to_modmgr(mgr); };
tempb.add_to_modmgr(Arc::clone(&mgr)).await;
async fn cmd_promote(bot:botinstance::BotManagers,msg:PrivmsgMessage) { // async fn cmd_promote(mut bot:Arc<Mutex<BotInstance>>,msg:PrivmsgMessage)
// async fn cmd_promote(mut bot:&BotInstance,msg:PrivmsgMessage) -> &BotInstance
async fn cmd_promote(bot:BotAR,msg:PrivmsgMessage) -> ()
{
//println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); //println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text);
println!("Called cmd promote"); println!("Called cmd promote");
@ -63,6 +88,8 @@ pub fn init(mgr:&mut ModulesManager)
*/ */
//let bot = Rcbot;
println!("{}",msg.message_text); println!("{}",msg.message_text);
let mut argv = msg.message_text.split(" "); let mut argv = msg.message_text.split(" ");
@ -84,31 +111,125 @@ pub fn init(mgr:&mut ModulesManager)
match arg1 { match arg1 {
Some(a) if a == String::from("admin") => { Some(a1) if a1 == String::from("admin") => {
// - BotAdmins can promote admin to give BotAdmin UserRole // - BotAdmins can promote admin to give BotAdmin UserRole
let a = bot.identity.getspecialuserroles(msg.sender.name.to_lowercase(), Some(ChType::Channel(msg.channel_login.to_lowercase()))); //let mut bot = Rc::clone(&bot);
// let a = bot.botmgrs.identity.getspecialuserroles(msg.sender.name.to_lowercase(), Some(ChType::Channel(msg.channel_login.to_lowercase())));
// let a = Rc::try_unwrap(bot).ok().unwrap().into_inner().botmgrs.identity.getspecialuserroles(msg.sender.name.to_lowercase(), Some(ChType::Channel(msg.channel_login.to_lowercase())));
// let a = Rc::try_unwrap(bot.clone()).ok().unwrap().into_inner().botmgrs.identity.getspecialuserroles(msg.sender.name.to_lowercase(), Some(ChType::Channel(msg.channel_login.to_lowercase())));
// let a = Rc::try_unwrap(bot).ok().unwrap()
// // .borrow_mut()
// .into_inner()
// .botmgrs
// .identity
// .getspecialuserroles(msg.sender.name.to_lowercase(),
// Some(ChType::Channel(msg.channel_login.to_lowercase())));
// let p = Rc::try_unwrap(bot.clone())
// let p = Arc::try_unwrap(bot.clone())
// .ok()
// .unwrap()
// //.into_inner()
// //.to_owned()
// // .get_mut()
// .into_inner();
// // .ok()
// // .unwrap();
// // let p = p.ok().unwrap();
// let p = bot.lock().await.get_identity();
// let p = p.lock().await;
// let ta = p.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))).await;
// // let ta = *ta.await;
// let ta = *ta.lock().await;
// if let Some(a) = ta {
// let p = bot.lock().await.get_identity();
// let mut p = p.lock().await;
// let ta = p.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))).await;
let botlock = bot.read().await;
let ta = botlock.get_identity();
let ta = ta.read().await;
let ta = ta.getspecialuserroles(String::from("Hello"), Some(ChType::Channel(msg.channel_login.to_lowercase()))).await;
let ta = ta.unwrap();
let a = ta.read().await;
// let ta = *ta;
// let ta = *ta;
// if let Some(a) = *ta {
if let Some(a) = a {
if a.contains(&UserRole::BotAdmin) { if a.contains(&UserRole::BotAdmin) {
println!("BotAdmin allowed to promote admin"); println!("BotAdmin allowed to promote admin");
match bot.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) { // let bota = Rc::clone(&bot);
// Success(_) => { // let bota = Rc::get_mut(&bota);
// ; // match bota.botmgrs.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) {
// }, //let mut bot = Rc::clone(&bot);
ChangeResult::Success(a) => println!("Succesfully promoted : {a} ;"), // let bot = Rc::<&botinstance::BotInstance>::get_mut(&mut bot);
ChangeResult::Failed(a) => println!("Failed to promote : {a} ; "), // let mut bot = Rc::make_mut(&mut bot);
ChangeResult::NoChange(a) => println!("No Changes Made : {a} ; "), // let mut bot = Rc::make_mut(&bot);
// match Rc::<&botinstance::BotInstance>::get_mut(bot) {
// Some(bot) => {
// match bot.botmgrs.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) {
// // Success(_) => {
// // ;
// // },
// ChangeResult::Success(a) => println!("Succesfully promoted : {a} ;"),
// ChangeResult::Failed(a) => println!("Failed to promote : {a} ; "),
// ChangeResult::NoChange(a) => println!("No Changes Made : {a} ; "),
// }
// },
// None => (),
// }
//let bot = Rc::<botinstance::BotInstance>::make_mut(bot);
// match Rc::<IdentityManager>::make_mut(&mut Rc::new(bot.botmgrs.identity)).promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) {
// match Rc::try_unwrap(bot.clone()).ok().unwrap().into_inner().botmgrs.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) {
// match Arc::try_unwrap(bot.clone()).ok().unwrap().into_inner().ok().unwrap().botmgrs.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) {
// match Arc::try_unwrap(bot.clone()).ok().unwrap().into_inner().botmgrs.identity.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) {
// match bot.read().ok().unwrap().get_identity().promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) {
// let a = bot.get_mut();
// match a.get_identity().promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) {
// let a = (*bot).clone();
{
// let a = bot.lock().await.get_botmgrs().clone();
// let a = bot.lock().await;
// let mut mutex = Arc::clone(&bot);
// match mutex.get_mut().get_identity().promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)) {
// slet ee = ArcBox(bot);
// println!("tester: {:?}",(*bot).lock().await.get_prefix());
// let mutex = Arc::clone(&bot);
// let mut mutex2 = Arc::new(*mutex).into_inner().get_identity();
// let mut mutex2 = Arc::clone(&mutex).into_inner().get_identity();
// let a = (*bot).lock().await.get_identity();
// let mut a = a.lock().await;
// let p = bot.lock().await.get_identity();
// let mut p = p.lock().await;
// let ta = p.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)).await;
let botlock = Arc::clone(&bot.read().await.get_identity());
let idlock = botlock.write().await;
// let mut idlock = *idlock;
let ta = idlock.promote(msg.sender.name.to_lowercase(), None, Some(UserRole::BotAdmin)).await;
match ta {
// Success(_) => {
// ;
// },
ChangeResult::Success(a) => println!("Succesfully promoted : {a} ;"),
ChangeResult::Failed(a) => println!("Failed to promote : {a} ; "),
ChangeResult::NoChange(a) => println!("No Changes Made : {a} ; "),
}
} }
} }
} }
}, // },
Some(_) => { // Some(_) => {
// - // // -
}, // },
_ => (), _ => (),
} }
@ -130,13 +251,27 @@ pub fn init(mgr:&mut ModulesManager)
// bot
} }
BotCommand { // BotCommand {
// module : BotModule(String::from("identity")),
// command : String::from("demote"), // command call name
// alias : vec![], // String of alternative names
// exec_body : actions_util::asyncbox(cmd_demote) ,
// help : String::from("demote"),
// required_roles : vec![
// UserRole::Mod(ChType::Channel(String::new())),
// UserRole::SupMod(ChType::Channel(String::new())),
// UserRole::Broadcaster,
// UserRole::BotAdmin,
// ],
// }.add_to_modmgr(Arc::clone(&mgr));
let tempb = BotCommand {
module : BotModule(String::from("identity")), module : BotModule(String::from("identity")),
command : String::from("demote"), // command call name command : String::from("demote"), // command call name
alias : vec![], // String of alternative names alias : vec![], // String of alternative names
@ -148,16 +283,32 @@ pub fn init(mgr:&mut ModulesManager)
UserRole::Broadcaster, UserRole::Broadcaster,
UserRole::BotAdmin, UserRole::BotAdmin,
], ],
}.add_to_modmgr(mgr); };
tempb.add_to_modmgr(Arc::clone(&mgr)).await;
// async fn cmd_demote(mut _chat:Arc<Mutex<BotInstance>>,_msg:PrivmsgMessage) {
async fn cmd_demote(mut _chat:botinstance::BotManagers,_msg:PrivmsgMessage) { async fn cmd_demote(mut _chat:BotAR,_msg:PrivmsgMessage) {
println!("Called cmd demote"); println!("Called cmd demote");
} }
BotCommand { // BotCommand {
// module : BotModule(String::from("identity")),
// command : String::from("getroles"), // command call name
// alias : vec![], // String of alternative names
// exec_body : actions_util::asyncbox(getroles) ,
// help : String::from("getroles"),
// required_roles : vec![
// UserRole::Mod(ChType::Channel(String::new())),
// UserRole::SupMod(ChType::Channel(String::new())),
// UserRole::Broadcaster,
// UserRole::BotAdmin,
// ],
// }.add_to_modmgr(Arc::clone(&mgr));
let tempcomm = BotCommand {
module : BotModule(String::from("identity")), module : BotModule(String::from("identity")),
command : String::from("getroles"), // command call name command : String::from("getroles"), // command call name
alias : vec![], // String of alternative names alias : vec![], // String of alternative names
@ -169,10 +320,14 @@ pub fn init(mgr:&mut ModulesManager)
UserRole::Broadcaster, UserRole::Broadcaster,
UserRole::BotAdmin, UserRole::BotAdmin,
], ],
}.add_to_modmgr(mgr); };
tempcomm.add_to_modmgr(Arc::clone(&mgr)).await;
async fn getroles(bot:botinstance::BotManagers,msg:PrivmsgMessage) {
// async fn getroles(bot:Arc<Mutex<BotInstance>>,msg:PrivmsgMessage) {
async fn getroles(bot:BotAR,msg:PrivmsgMessage) {
println!("Called cmd getroles"); println!("Called cmd getroles");
/* /*
@ -224,17 +379,66 @@ pub fn init(mgr:&mut ModulesManager)
let targetchnl = arg2; let targetchnl = arg2;
match targetchnl { // // let a = bot.read().ok().unwrap().get_identity();
// let a = bot.lock().await;
// // let a = a.lock().await;
// // let a = a.get_identity().await;
// let a = a.botmgrs;
// // let a = *(*a).lock().await;
// let a = *a.lock().await;
// let a = a.identity;
// let a = *a.lock().await;
// let a = bot.clone();
// let a = a.into_inner();
// let a = a.botmgrs;
// let a = a.into_inner();
// let a = a.identity;
// let a = a.into_inner();
// let a = bot.clone();
// let a = a.lock().await;
// let a = a.get_identity();
// let a = a.lock().await;
// let a = bot.get_identity();
let botlock = bot.read().await;
println!("botlock read");
let idlock = botlock.get_identity();
println!("got identity");
let idlock = idlock.read().await; // <-- 02.12 - Latest where it gest stuck - before or at this point
println!("id lock");
let sproles = match targetchnl {
None => { None => {
let a = bot.identity.getspecialuserroles(String::from(targetuser),None); // let bot = Rc::clone(&bot);
println!("Retrieved User Roles >> {:?}",a); //let bot = Arc::clone(&bot);
// let a = bot.botmgrs.identity.getspecialuserroles(String::from(targetuser),None);
// let a = Arc::try_unwrap(bot).ok().unwrap().into_inner().ok().unwrap();
// let a = Arc::try_unwrap(bot.clone()).ok().unwrap().into_inner();
// let a = a.botmgrs.identity.getspecialuserroles(String::from(targetuser),None);
// let a = a.ok().getspecialuserroles(String::from(targetuser),None);
// let a = bot.read().ok().unwrap().rIdentity().getspecialuserroles(String::from(targetuser),None);
// println!("Retrieved User Roles >> {:?}",a);
// let a = idlock.read().await;
idlock.getspecialuserroles(String::from(targetuser),None).await
}, },
Some(targetchnl) => { Some(targetchnl) => {
let a = bot.identity.getspecialuserroles(String::from(targetuser), Some(ChType::Channel(String::from(targetchnl)))); // let bot = Rc::clone(&bot);
println!("Retrieved User Roles >> {:?}",a); // let bot = Arc::clone(&bot);
}, // let a = bot.botmgrs.identity.getspecialuserroles(String::from(targetuser), Some(ChType::Channel(String::from(targetchnl))));
} // Arc::try_unwrap(boxed_bot.clone()).ok().unwrap().into_inner()
// let a = Arc::try_unwrap(bot).ok().unwrap().into_inner().ok().unwrap();
// let a = Arc::try_unwrap(bot.clone()).ok().unwrap().into_inner();
// let a = a.botmgrs.identity.getspecialuserroles(String::from(targetuser), Some(ChType::Channel(String::from(targetchnl))));
// let a = bot.read().ok().unwrap().rIdentity().getspecialuserroles(String::from(targetuser),None);
// println!("Retrieved User Roles >> {:?}",a);
// bot.read().ok().unwrap().rIdentity().getspecialuserroles(String::from(targetuser),None)
// let a = a.read().await;
idlock.getspecialuserroles(String::from(targetuser),None).await
},
};
println!("Retrieved User Roles >> {:?}",sproles);
// let a = bot.identity.getuserroles(String::from("ModulatingForce"), Some(ChType::Channel(String::from("ModulatingForcebot")))); // let a = bot.identity.getuserroles(String::from("ModulatingForce"), Some(ChType::Channel(String::from("ModulatingForcebot"))));
// println!("{:?}",a); // println!("{:?}",a);
@ -243,7 +447,7 @@ pub fn init(mgr:&mut ModulesManager)
println!("End of Init MOdule add");
} }
@ -271,7 +475,10 @@ pub enum Permissible {
#[derive(Clone)] #[derive(Clone)]
pub struct IdentityManager { pub struct IdentityManager {
special_roles_users : HashMap<String,Vec<UserRole>>, // # <-- (!) This must be String instead of ChType because we're checking a User not a Channel // special_roles_users : HashMap<String,Vec<UserRole>>, // # <-- (!) This must be String instead of ChType because we're checking a User not a Channel
// special_roles_users : Arc<Mutex<HashMap<String,Vec<UserRole>>>>, // # <-- (!) This must be String instead of ChType because we're checking a User not a Channel
// special_roles_users : Arc<RwLock<HashMap<String,Vec<UserRole>>>>,
special_roles_users : Arc<RwLock<HashMap<String,Arc<RwLock<Vec<UserRole>>>>>>,
// parent_mgr : Box<crate::core::botinstance::BotManagers>, // parent_mgr : Box<crate::core::botinstance::BotManagers>,
//parent_mgr : Option<Box<crate::core::botinstance::BotManagers>>, //parent_mgr : Option<Box<crate::core::botinstance::BotManagers>>,
} }
@ -294,11 +501,11 @@ impl IdentityManager {
pub fn init() -> IdentityManager { pub fn init() -> IdentityManager {
let mut a = HashMap::new(); let mut a = HashMap::new();
for admn in adminvector() { for admn in adminvector() {
a.insert(admn.to_lowercase(),vec![UserRole::BotAdmin]); a.insert(admn.to_lowercase(),Arc::new(RwLock::new(vec![UserRole::BotAdmin])));
}; };
IdentityManager { IdentityManager {
special_roles_users : a, special_roles_users : Arc::new(RwLock::new(a)),
//parent_mgr : None, //parent_mgr : None,
} }
} }
@ -306,11 +513,14 @@ impl IdentityManager {
// [ ] Maybe I should create a can_user_run version that simply takes PrvMsg, but then calls can_user_run directly // [ ] Maybe I should create a can_user_run version that simply takes PrvMsg, but then calls can_user_run directly
// 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>) -> Result<Permissible,Box<dyn Error>>
pub fn can_user_run_PRVMSG(&mut self,msg:&PrivmsgMessage,cmdreqroles:Vec<UserRole>) -> Permissible // 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
{ {
// println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); // println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text);
// [ ] Check what Badges in PrivmsgMessage // [ ] Check what Badges in PrivmsgMessage
println!{"Checking within PRVMSG"};
let mut sender_badge:Option<ChatBadge> = None; let mut sender_badge:Option<ChatBadge> = None;
@ -331,26 +541,46 @@ impl IdentityManager {
// ChType::Channel(msg.channel_login.to_owned()), // ChType::Channel(msg.channel_login.to_owned()),
// sender_badge, // sender_badge,
// cmdreqroles // cmdreqroles
// return self.can_user_run(msg.sender.name.to_owned(),
// let a = Arc::new(Mutex::new(self));
// let mut a = a.lock().await;
// let a = **a;
// let a = a.can_user_run(msg.sender.name.to_owned(),
// ChType::Channel(msg.channel_login.to_owned()),
// sender_badge,
// cmdreqroles
// ) ;
// let a = *self;
// let a = Arc::new(Mutex::new(a));
// let a = a.lock().await.can_user_run(msg.sender.name.to_owned(),
// ChType::Channel(msg.channel_login.to_owned()),
// sender_badge,
// cmdreqroles
// ) ;
// return a;
return self.can_user_run(msg.sender.name.to_owned(), return self.can_user_run(msg.sender.name.to_owned(),
ChType::Channel(msg.channel_login.to_owned()), ChType::Channel(msg.channel_login.to_owned()),
sender_badge, sender_badge,
cmdreqroles cmdreqroles
) ; ).await
} }
// [ ] Call can_user_run() // [ ] Call can_user_run()
// (self,Permissible::Block)
Permissible::Block Permissible::Block
} }
pub fn can_user_run(&mut self,
pub async fn can_user_run(&mut self,
usr:String, usr:String,
channelname:ChType, channelname:ChType,
chat_badge:ChatBadge, chat_badge:ChatBadge,
cmdreqroles:Vec<UserRole> cmdreqroles:Vec<UserRole>
// ) -> Result<Permissible,Box<dyn Error>> { // ) -> Result<Permissible,Box<dyn Error>> {
) -> Permissible { ) -> Permissible {
println!{"Checking within can_user_run()"};
/* /*
canUserRun - canUserRun -
@ -389,6 +619,8 @@ impl IdentityManager {
// [x] If cmdreqroles is empty vector , automatically assume Ok(Permissible::Allow) // [x] If cmdreqroles is empty vector , automatically assume Ok(Permissible::Allow)
// let idar = Arc::new(RwLock::new(self));
if cmdreqroles.len() == 0 { if cmdreqroles.len() == 0 {
// return Ok(Permissible::Allow) // return Ok(Permissible::Allow)
return Permissible::Allow return Permissible::Allow
@ -417,33 +649,47 @@ impl IdentityManager {
ChatBadge::Mod => { ChatBadge::Mod => {
// println!("Mod Chatbadge detected"); println!("Mod Chatbadge detected");
// println!("debug special roles : {:?}",self.special_roles_users); // println!("debug special roles : {:?}",self.special_roles_users);
// println!("debug usr : {}",&usr.to_lowercase()); // println!("debug usr : {}",&usr.to_lowercase());
// let Some((k,v)) = self.special_roles_users.get_key_value(usr); // let Some((k,v)) = self.special_roles_users.get_key_value(usr);
// match self.special_roles_users.get_mut(&usr.to_lowercase()) { // match self.special_roles_users.get_mut(&usr.to_lowercase()) {
match self.special_roles_users.get(&usr.to_lowercase()) { // match self.special_roles_users.get(&usr.to_lowercase()) {
Some(usrroles) => { println!("Creating clone");
// println!("contains mod : {}", usrroles.contains(&UserRole::Mod(channelname.clone()))); let roleslock = Arc::clone(&(*self).special_roles_users);
// println!("contains supmod : {}", usrroles.contains(&UserRole::SupMod(channelname.clone()))); println!("Read lock on : Special_Roles_User"); // <-- after this is slightly different between working and problem
if usrroles.contains(&UserRole::Mod(channelname.clone())) || let mut roleslock = roleslock.write().await;
usrroles.contains(&UserRole::SupMod(channelname.clone())) { match (*roleslock).get(&usr.to_lowercase()) {
Some(usrroles) => { // <-- 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 - this is expected
println!("Already a mod in roles");
} else { } else {
// in this case, they have a ChatBadge::Mod but should have this for the channel // in this case, they have a ChatBadge::Mod but should have this for the channel
// let mut a = usrroles; // let mut a = usrroles;
// usrroles.push(UserRole::Mod(channelname.clone())); // usrroles.push(UserRole::Mod(channelname.clone()));
// a.push(UserRole::Mod(channelname.clone())); // a.push(UserRole::Mod(channelname.clone()));
self.special_roles_users println!("Was in the else loop");
.get_mut(&usr.to_lowercase())
.expect("ERROR") // let a = &*self;
.push(UserRole::Mod(channelname.clone())); // 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); // println!("debug special roles : {:?}",self.special_roles_users);
} }
}, },
_ => () _ => ( ) // <-- I'm assuming problem got to here
} }
}, },
@ -463,9 +709,11 @@ impl IdentityManager {
println!("Mod Role required"); println!("Mod Role required");
if let Some(a) = self.special_roles_users.get(&usr.to_lowercase()) { if let Some(a) = (&*self).special_roles_users.read().await.get(&usr.to_lowercase()) {
if a.contains(&UserRole::Mod(channelname.clone())) || a.contains(&UserRole::SupMod(channelname.clone())){ println!("Special roles found for user");
if a.read().await.contains(&UserRole::Mod(channelname.clone())) || a.read().await.contains(&UserRole::SupMod(channelname.clone())){
// return Ok(Permissible::Allow); // return Ok(Permissible::Allow);
println!("Special roles found for user : A mod idenfified ");
return Permissible::Allow return Permissible::Allow
} }
} }
@ -476,8 +724,8 @@ impl IdentityManager {
if cmdreqroles.contains(&UserRole::SupMod(ChType::Channel(String::new()))) { if cmdreqroles.contains(&UserRole::SupMod(ChType::Channel(String::new()))) {
if let Some(a) = self.special_roles_users.get(&usr.to_lowercase()) { if let Some(a) = (&*self).special_roles_users.read().await.get(&usr.to_lowercase()) {
if a.contains(&UserRole::SupMod(channelname.clone())) { if a.read().await.contains(&UserRole::SupMod(channelname.clone())) {
// return Ok(Permissible::Allow); // return Ok(Permissible::Allow);
return Permissible::Allow return Permissible::Allow
} }
@ -490,10 +738,10 @@ impl IdentityManager {
println!("Eval cmdreqroles with botadmin : {}",cmdreqroles.contains(&UserRole::BotAdmin)); println!("Eval cmdreqroles with botadmin : {}",cmdreqroles.contains(&UserRole::BotAdmin));
if cmdreqroles.contains(&UserRole::BotAdmin) { if cmdreqroles.contains(&UserRole::BotAdmin) {
println!("special roles get : {:?}",self.special_roles_users.get(&usr.to_lowercase())); println!("special roles get : {:?}",(&*self).special_roles_users.read().await.get(&usr.to_lowercase()));
if let Some(a) = self.special_roles_users.get(&usr.to_lowercase()) { if let Some(a) = (&*self).special_roles_users.read().await.get(&usr.to_lowercase()) {
println!("special roles contains BotAdmin: {}",a.contains(&UserRole::BotAdmin)); println!("special roles contains BotAdmin: {}",a.read().await.contains(&UserRole::BotAdmin));
if a.contains(&UserRole::BotAdmin) { if a.read().await.contains(&UserRole::BotAdmin) {
// return Ok(Permissible::Allow); // return Ok(Permissible::Allow);
return Permissible::Allow return Permissible::Allow
} }
@ -503,33 +751,53 @@ impl IdentityManager {
Permissible::Block Permissible::Block
} }
pub fn promote(mut self,trgchatter:String,channel:Option<ChType>,trg_role:Option<UserRole>) -> ChangeResult { // pub async fn promote(&mut self,trgchatter:String,channel:Option<ChType>,trg_role:Option<UserRole>) -> ChangeResult {
pub async fn promote(&self,trgchatter:String,channel:Option<ChType>,trg_role:Option<UserRole>) -> ChangeResult {
// Note : If channel is none, getspecialuserroles() returns all roles for the user // Note : If channel is none, getspecialuserroles() returns all roles for the user
// let chatterroles = self.getspecialuserroles(trgchatter, channel); // let chatterroles = self.getspecialuserroles(trgchatter, channel);
let chatterroles = self.getspecialuserroles(trgchatter.clone(), channel.clone()); // let chatterroles = self.getspecialuserroles(trgchatter.clone(), channel.clone());
// let chatterroles = *self.getspecialuserroles(trgchatter.clone(), channel.clone()).await;
// let chatterroles = chatterroles.lock().await;
// // let chatterroles = *chatterroles;
// let chatterroles = chatterroles.unwrap();
let emptyvec = vec![];
let chatterroles = match chatterroles { let chatterroles = self.getspecialuserroles(trgchatter.clone(), channel.clone()).await;
Some(a) => a, // let chatterroles = chatterroles.lock().await;
_ => &(emptyvec), // let chatterroles = *chatterroles;
}; // let chatterroles = chatterroles.unwrap();
// let emptyvec = vec![];
// let chatterroles = match chatterroles {
// Some(a) => a,
// _ => &(emptyvec),
// };
let chatterroles = chatterroles.unwrap();
let chatterroles = chatterroles.read().await;
let rolemap = &(*chatterroles);
match trg_role { match trg_role {
Some(UserRole::Mod(a)) => { Some(UserRole::Mod(a)) => {
if let Some(trg_chnl) = channel { if let Some(trg_chnl) = channel {
if chatterroles.contains(&UserRole::Mod(trg_chnl.clone())) { // let rolemap = rolemap.unwrap();
if rolemap.contains(&UserRole::Mod(trg_chnl.clone())) {
return ChangeResult::NoChange(String::from("Target User already has Target Role")); return ChangeResult::NoChange(String::from("Target User already has Target Role"));
} }
// # otherwise, trg_role for the given chnl is not assigned to the trgchatter // # otherwise, trg_role for the given chnl is not assigned to the trgchatter
// chatterroles.push(UserRole::Mod(trg_chnl.clone())); // chatterroles.push(UserRole::Mod(trg_chnl.clone()));
self.special_roles_users self.special_roles_users
.write().await
.get_mut(&trgchatter) .get_mut(&trgchatter)
.expect("Error getting roles") .expect("Error getting roles")
.write().await
.push(UserRole::Mod(trg_chnl)); .push(UserRole::Mod(trg_chnl));
return ChangeResult::Success(String::from("Promotion Successful")); return ChangeResult::Success(String::from("Promotion Successful"));
@ -615,7 +883,10 @@ impl IdentityManager {
ChangeResult::Success(String::from("TEST > Promotion Successful")) ChangeResult::Success(String::from("TEST > Promotion Successful"))
} }
pub fn getspecialuserroles(&self,chattername:String,channel:Option<ChType>) -> Option<&Vec<UserRole>> { pub async fn getspecialuserroles(&self,chattername:String,channel:Option<ChType>) -> Option<Arc<RwLock<Vec<UserRole>>>> {
/*
Note : Ideally this be called for a given chatter name ?
*/
// let a = chattername.to_lowercase(); // let a = chattername.to_lowercase();
@ -633,11 +904,39 @@ impl IdentityManager {
// println!("> Roles : {:?}",v); // println!("> Roles : {:?}",v);
// } // }
let a = chattername.to_lowercase(); let chattername = chattername.to_lowercase();
// println!("{a}"); // println!("{a}");
self.special_roles_users.get(&a) // let b = self.special_roles_users.lock().await.get(&a);
// match b
// {
// Some(b) => Some(*b),
// None => None,
// }
// println!("Write Lock on Special Roles @ Getspecialuserroles()");
// let b = self.special_roles_users.write().await.remove(&a);
// let outp = b;
// // let b = Arc::new(Mutex::new(outp));
// outp
let rolesa = Arc::clone(&self.special_roles_users);
let a = rolesa.read().await;
// let a = Arc::clone(a)
let a = a;
let outr = &(*a);
let outr = outr.get(&chattername);
match outr {
Some(a) => Some(Arc::clone(a)),
None => None,
}
// Arc::new(RwLock::new(outr))
// let b = Arc::new(Mutex::new(b));
// b

View file

@ -4,13 +4,37 @@ pub mod core;
pub mod modules; pub mod modules;
use std::process::Output; use std::process::Output;
use crate::core::botinstance::ArcBox;
use crate::core::botinstance::BotInstance; use crate::core::botinstance::BotInstance;
use tokio::sync::RwLock;
use std::sync::Arc;
pub type BotAR = Arc<RwLock<BotInstance>>;
#[tokio::main] #[tokio::main]
pub async fn main() { pub async fn main() {
let bot = BotInstance::init(); let bot = BotInstance::init().await;
let a = Arc::clone(&bot.botmodules.botactions);
let a = a.read().await;
// let a = *a;
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??"),
}
}
};
println!("Starting runner..");
bot.runner().await; bot.runner().await;
println!("ERROR : EXIT Game loop");
} }

View file

@ -10,7 +10,8 @@ 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;
// [ ] Load submodules // [ ] Load submodules
@ -25,12 +26,13 @@ mod experiments;
// // F: std::future::Future + Send, // // F: std::future::Future + Send,
// // F : Send, // // F : Send,
// F : Send + ?Sized, // F : Send + ?Sized,
pub fn init(mgr:&mut ModulesManager) // pub fn init(mgr:&mut 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
experiments::init(mgr) experiments::init(mgr).await
//(); //();
} }

View file

@ -15,9 +15,10 @@
use std::future::Future; use std::future::Future;
use crate::core::botmodules::{ModulesManager,Listener,BotModule,BotActionTrait, BotCommand,ChType}; use crate::core::botmodules::{ModulesManager,Listener,BotModule,BotActionTrait, BotCommand,ChType};
use crate::core::botmodules::bot_actions::actions_util; use crate::core::botmodules::bot_actions::actions_util::{self, BotAR};
use crate::core::botinstance::{self}; use crate::core::botinstance::{self,BotInstance};
use futures::lock::Mutex;
use twitch_irc::message::PrivmsgMessage; use twitch_irc::message::PrivmsgMessage;
use crate::core::identity; use crate::core::identity;
@ -25,8 +26,13 @@ use crate::core::identity;
use rand::Rng; use rand::Rng;
use std::rc::Rc;
pub fn init(mgr:&mut ModulesManager) use std::sync::{Arc, RwLock};
// pub fn init(mgr:&mut ModulesManager)
pub async fn init(mgr:Arc<ModulesManager>)
{ {
@ -43,7 +49,7 @@ pub fn init(mgr:&mut ModulesManager)
// }.add_to_modmgr(mgr); // }.add_to_modmgr(mgr);
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
@ -52,7 +58,9 @@ pub fn init(mgr:&mut ModulesManager)
required_roles : vec![ required_roles : vec![
identity::UserRole::BotAdmin identity::UserRole::BotAdmin
], ],
}.add_to_modmgr(mgr); };
botc1.add_to_modmgr(Arc::clone(&mgr)).await;
@ -63,13 +71,13 @@ pub fn init(mgr:&mut ModulesManager)
help : String::from("") help : String::from("")
}; };
list1.add_to_modmgr(mgr); list1.add_to_modmgr(Arc::clone(&mgr)).await;
} }
async fn good_girl(mut bot:botinstance::BotManagers,msg:PrivmsgMessage) async fn good_girl(mut bot:BotAR,msg:PrivmsgMessage)
{ {
println!("In GoodGirl() Listener"); println!("In GoodGirl() Listener");
//println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text); //println!("(#{}) {}: {}", msg.channel_login, msg.sender.name, msg.message_text);
@ -82,6 +90,13 @@ async fn good_girl(mut bot:botinstance::BotManagers,msg:PrivmsgMessage)
// let roll = rand::thread_rng().gen_range(1..=5); // let roll = rand::thread_rng().gen_range(1..=5);
// let mut bot = Rc::clone(&bot);
// let mut bot = Rc::get_mut(&mut bot);
// let bot = match bot {
// Some(bot) => bot,
// None => (),
// }
if msg.sender.name == "ModulatingForce" // && msg.message_text.contains("GoodGirl") if msg.sender.name == "ModulatingForce" // && msg.message_text.contains("GoodGirl")
@ -92,17 +107,46 @@ async fn good_girl(mut bot:botinstance::BotManagers,msg:PrivmsgMessage)
let rollwin = rand::thread_rng().gen_ratio(1,5); let rollwin = rand::thread_rng().gen_ratio(1,5);
if rollwin { if rollwin {
println!("In GoodGirl() > Win"); println!("In GoodGirl() > Win");
bot.chat.say_in_reply_to(&msg,String::from("GoodGirl xdd ")).await; // let bot = Rc::get_mut(&bot).expect("Error");
// bot.botmgrs.chat.say_in_reply_to(&msg,String::from("GoodGirl xdd ")).await;
// Rc::<botinstance::BotInstance>::get_mut(mut bot)
// if let Some(bot) = Rc::<&botinstance::BotInstance>::get_mut(bot) {
// match bot{
// Some(bot) => {
// bot
// .botmgrs
// .chat
// .say_in_reply_to(&msg,String::from("GoodGirl xdd ")).await;
// }
// None => (),
// }
// Arc::try_unwrap(bot).ok().unwrap().botmgrs.chat.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await;
// let a = bot.clone();
let a = Arc::clone(&bot);
// let a = a.read().ok().unwrap();
// let a = a.lock().await.get_botmgrs();
// let a = a.lock().await.rChat();
// let a = (*bot).lock().await.get_botmgrs();
// let a = a.lock().await.rChat();
// let mut a = (*a).lock().await;
// let a = a.botmgrs.chat.say_in_reply_to(&msg, outmsg)
// a.rbotmgrs().chat.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await;
// a.lock().await.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await;
// a.botmgrs.chat.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await;
let botlock = a.read().await;
botlock.botmgrs.chat.say_in_reply_to(&msg, String::from("GoodGirl xdd ")).await;
} }
} }
} }
async fn testy(mut _chat:botinstance::BotManagers,_msg:PrivmsgMessage)
async fn testy(mut _chat:BotAR,_msg:PrivmsgMessage)
{ {
println!("testy triggered!") println!("testy triggered!")