Merge branch 'main' into routines-functionality
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful

This commit is contained in:
modulatingforce 2024-03-25 23:26:46 -04:00
commit 34c3c8af7a
13 changed files with 2093 additions and 810 deletions

View file

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

17
Cargo.lock generated
View file

@ -41,6 +41,17 @@ dependencies = [
"libc",
]
[[package]]
name = "async-recursion"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30c5ef0ede93efbf733c1a727f3b6b5a1060bbedd5600183e66f6e4be4af0ec5"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "async-trait"
version = "0.1.77"
@ -122,9 +133,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
version = "0.4.34"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bc015644b92d5890fab7489e49d21f879d5c990186827d42ec511919404f38b"
checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a"
dependencies = [
"android-tzdata",
"iana-time-zone",
@ -194,8 +205,10 @@ checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5"
name = "forcebot_rs"
version = "0.1.0"
dependencies = [
"async-recursion",
"async-trait",
"casual_logger",
"chrono",
"dotenv",
"futures",
"rand",

View file

@ -12,7 +12,10 @@ twitch-irc = "5.0.1"
rand = { version = "0.8.5", features = [] }
futures = "0.3"
async-trait = "0.1.77"
async-recursion = "1.1.0"
casual_logger = "0.6.5"
chrono = "0.4.35"
[lib]
name = "bot_lib"

View file

@ -1,27 +1,83 @@
use twitch_irc::message::PrivmsgMessage;
use std::sync::Arc;
use tokio::sync::RwLock;
use crate::core::botinstance::BotInstance;
use super::{botmodules::{BotAction, BotModule}, identity::ChatBadge};
pub type BotAR = Arc<RwLock<BotInstance>>;
pub type ActAR = Arc<RwLock<BotAction>>;
#[derive(Clone)]
pub struct ExecBodyParams {
pub bot : BotAR,
pub msg : PrivmsgMessage,
pub parent_act : ActAR ,
}
impl ExecBodyParams {
pub async fn get_parent_module(&self) -> Option<BotModule> {
let parent_act = Arc::clone(&self.parent_act);
let parent_act_lock = parent_act.read().await;
let act = &(*parent_act_lock);
match act {
BotAction::C(c) => {
let temp = c.module.clone();
Some(temp)
},
BotAction::L(l) => {
let temp = l.module.clone();
Some(temp)
},
_ => None
}
}
pub fn get_sender(&self) -> String {
self.msg.sender.name.clone()
}
pub fn get_sender_chatbadge(&self) -> Option<ChatBadge> {
let mut requestor_badge_mut: Option<ChatBadge> = None;
for b in &self.msg.badges {
if b.name == "moderator" {
requestor_badge_mut = Some(ChatBadge::Mod);
} else if b.name == "broadcaster" {
requestor_badge_mut = Some(ChatBadge::Broadcaster);
}
}
requestor_badge_mut
}
}
pub mod actions_util {
use super::*;
use std::boxed::Box;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock};
use twitch_irc::message::PrivmsgMessage;
use crate::core::botinstance::BotInstance;
pub type BotAM = Arc<Mutex<BotInstance>>;
pub type BotAR = Arc<RwLock<BotInstance>>;
pub type ExecBody = Box<
dyn Fn(BotAR, PrivmsgMessage) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,
dyn Fn(ExecBodyParams) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,
>;
pub fn asyncbox<T>(f: fn(BotAR, PrivmsgMessage) -> T) -> ExecBody
pub fn asyncbox<T>(f: fn(ExecBodyParams) -> T) -> ExecBody
where
T: Future<Output = ()> + Send + 'static,
{
Box::new(move |a, b| Box::pin(f(a, b)))
Box::new(move |a| Box::pin(f(a)))
}
}

View file

@ -17,9 +17,9 @@ use casual_logger::Log;
use crate::core::ratelimiter::RateLimiter;
use crate::core::bot_actions::actions_util::BotAR;
use crate::core::bot_actions::BotAR;
use crate::core::botmodules::ModulesManager;
use crate::core::identity::{IdentityManager, Permissible,self};
use crate::core::identity::{IdentityManager, Permissible};
use crate::core::botlog;
use crate::core::chat::Chat;
@ -33,14 +33,11 @@ pub enum ChangeResult {
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum ChType {
Channel(String),
}
pub use ChType::Channel;
pub struct Channel(pub String);
use super::bot_actions::ExecBodyParams;
use super::botmodules::StatusType;
#[derive(Clone)]
@ -51,7 +48,7 @@ pub struct BotManagers {
impl BotManagers {
pub fn init(
ratelimiters: HashMap<ChType, RateLimiter>,
ratelimiters: HashMap<Channel, RateLimiter>,
client: TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>,
) -> BotManagers {
BotManagers {
@ -75,11 +72,11 @@ impl<T: Clone> ArcBox<T> {
pub struct BotInstance {
pub prefix: char,
pub bot_channel: ChType,
pub bot_channel: Channel,
pub incoming_messages: Arc<RwLock<UnboundedReceiver<ServerMessage>>>,
pub botmodules: Arc<ModulesManager>,
pub twitch_oauth: String,
pub bot_channels: Vec<ChType>,
pub bot_channels: Vec<Channel>,
pub botmgrs: BotManagers,
//modesmgr : ModesManager, // [FUTURE] Silent/Quiet , uwu , frisky/horny
}
@ -157,6 +154,18 @@ impl BotInstance {
while let Some(message) = msglock.recv().await {
botlog::trace(
format!(
"[TRACE][ServerMessage] > {:?}",
message
)
.as_str(),
Some("BotInstance > runner()".to_string()),
None,
);
match message {
ServerMessage::Notice(msg) => {
botlog::notice(
@ -165,8 +174,10 @@ impl BotInstance {
Some("BotInstance > runner()".to_string()),
None,
);
Log::flush();
}
ServerMessage::Privmsg(msg) => {
botlog::debug(
format!(
"[Twitch Chat > {}] > {}: {}",
@ -177,6 +188,18 @@ impl BotInstance {
Some(&msg),
);
botlog::trace(
format!(
"[TRACE][Twitch Chat > {}] > {}: {:?}",
msg.channel_login, msg.sender.name, msg
)
.as_str(),
Some("BotInstance > runner()".to_string()),
Some(&msg),
);
Log::flush();
BotInstance::listener_main_prvmsg(Arc::clone(&bot), &msg).await;
}
ServerMessage::Whisper(msg) => {
@ -185,6 +208,7 @@ impl BotInstance {
Some("BotInstance > runner()".to_string()),
None,
);
Log::flush();
}
ServerMessage::Join(msg) => {
botlog::notice(
@ -192,6 +216,7 @@ impl BotInstance {
Some("BotInstance > runner()".to_string()),
None,
);
Log::flush();
}
ServerMessage::Part(msg) => {
botlog::notice(
@ -199,6 +224,7 @@ impl BotInstance {
Some("BotInstance > runner()".to_string()),
None,
);
Log::flush();
}
_ => {}
};
@ -229,6 +255,42 @@ impl BotInstance {
// // [ ] #todo 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)
/*
[ ] What we should do instead is :
1. Check if the message is related to a Reply (so we know how many arguments we should skip)
2. If a reply, skip the first argument
*/
let mut msgiter= msg
.message_text
.split(' ');
let arg1 = msgiter.next();
let arg2 = msgiter.next();
let reply = if let Some(Some(replyid)) = msg.source.tags.0.get("reply-thread-parent-msg-id") {
Some(replyid)
} else { None }
;
let inpt = match reply {
None => { // Regular message, use the first arg as the command
match arg1 {
None => return, // return if no argument found
Some(a) => a,
}
},
Some(_) => {
match arg2 { // A reply message, use the 2nd arg as the command
None => return, // return if no argument found
Some(a) => a,
}
},
};
let botlock = bot.read().await;
let actsdb = Arc::clone(&botlock.botmodules.botactions);
let actsdblock = actsdb.read().await;
@ -239,9 +301,15 @@ impl BotInstance {
Some(msg),
);
for acts in (*actsdblock).values() {
for a in acts {
match a {
let act_clone = Arc::clone(a);
match &(*act_clone.read().await) {
crate::core::botmodules::BotAction::C(c) => {
/*
BotCommand handling -
@ -259,11 +327,7 @@ impl BotInstance {
Some(msg),
);
let inpt = msg
.message_text
.split(' ')
.next()
.expect("ERROR during BotCommand");
// [x] Check if a bot command based on ...
// [x] prefix + command
@ -299,7 +363,7 @@ impl BotInstance {
let modmgr = Arc::clone(&botlock.botmodules);
let modstatus = modmgr.modstatus(
c.module.clone(),
ChType::Channel(msg.channel_login.to_string())).await;
Channel(msg.channel_login.to_string())).await;
if let StatusType::Disabled(a) = modstatus {
@ -314,33 +378,51 @@ impl BotInstance {
);
const OF_CMD_CHANNEL:ChType = Channel(String::new());
let botclone = Arc::clone(&bot);
let botlock = botclone.read().await;
let id = botlock.get_identity();
let id = Arc::clone(&id);
let idlock = id.read().await; // <-- [ ] 03.24 - seems to work
let user_roles = idlock.getspecialuserroles(
msg.sender.name.clone(),
Some(Channel(msg.channel_login.clone()))
).await;
let elevated_access = {
let mut idlock = id.write().await;
let (permissability, _) = idlock
.can_user_run_prvmsg(msg,
vec![
identity::UserRole::BotAdmin,
identity::UserRole::Mod(OF_CMD_CHANNEL),
identity::UserRole::SupMod(OF_CMD_CHANNEL),
identity::UserRole::Broadcaster,
])
.await;
permissability
botlog::trace(
&format!("For Disabled Command Evaluating User Roles {:?}", user_roles),
Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(msg),
);
// Only respond to those with th ebelow User Roles
let outstr =
format!("sadg Module is disabled : {:?}",a);
let params = ExecBodyParams {
bot : Arc::clone(&bot),
msg : (*msg).clone(),
parent_act : Arc::clone(&act_clone),
};
if let Permissible::Allow = elevated_access {
let botlock = bot.read().await;
let outstr =
format!("sadg Module is disabled : {:?}",a);
botlock.botmgrs.chat.say_in_reply_to(msg, outstr).await;
}
// When sending a BotMsgTypeNotif, send_botmsg does Roles related validation as required
botlock.botmgrs.chat.send_botmsg(super::chat::BotMsgType::Notif(
outstr
),
params,
).await;
return;
};
botlog::trace(
"ACQUIRING WRITE LOCK : ID",
Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(msg),
);
let eval = {
@ -374,7 +456,51 @@ impl BotInstance {
let botlock = bot.read().await;
let outstr =
"o7 a Mod. I kneel to serve! pepeKneel ".to_string();
botlock.botmgrs.chat.say_in_reply_to(msg, outstr).await;
let params = ExecBodyParams {
bot : Arc::clone(&bot),
msg : (*msg).clone(),
parent_act : Arc::clone(&act_clone),
};
botlock.botmgrs.chat.send_botmsg(super::chat::BotMsgType::Notif(
outstr.to_string()
),
params.clone(),
).await;
}
if innerstr
.to_lowercase()
.contains(&"Auto Promoted VIP".to_lowercase())
{
botlog::notice(
"Assigning VIP UserRole to VIP",
Some("botinstance > listener_main_prvmsg()".to_string()),
Some(msg),
);
let botlock = bot.read().await;
let outstr =
"❤️ a VIP - love ya!".to_string();
let params = ExecBodyParams {
bot : Arc::clone(&bot),
msg : (*msg).clone(),
parent_act : Arc::clone(&act_clone),
};
botlock.botmgrs.chat.send_botmsg(super::chat::BotMsgType::Notif(
outstr.to_string()
),
params.clone(),
).await;
}
}
@ -387,12 +513,15 @@ impl BotInstance {
);
let a = Arc::clone(&bot);
c.execute(a, msg.clone()).await;
c.execute(ExecBodyParams {
bot : a,
msg : msg.clone() ,
parent_act : Arc::clone(&act_clone),
}).await;
botlog::trace(
"exit out of execution",
Some("BotInstance > listener_main_prvmsg()".to_string()),
// Some(&msg),
Some(msg),
);
}
@ -411,13 +540,12 @@ impl BotInstance {
crate::core::botmodules::BotAction::L(l) => {
let botlock = bot.read().await;
// let id = botlock.get_identity();
// [x] Check first if the Module for that Given Command is Enabled or Disabled on the given Channel
let modmgr = Arc::clone(&botlock.botmodules);
let modstatus = modmgr.modstatus(
l.module.clone(),
ChType::Channel(msg.channel_login.to_string())).await;
Channel(msg.channel_login.to_string())).await;
if let StatusType::Disabled(a) = modstatus {
@ -433,7 +561,11 @@ impl BotInstance {
} else {
let a = Arc::clone(&bot);
l.execute(a, msg.clone()).await;
l.execute(ExecBodyParams {
bot : a,
msg : msg.clone() ,
parent_act : Arc::clone(&act_clone),
} ).await;
}
}

View file

@ -3,12 +3,12 @@
ModulesManager is used to manage Modules and BotActions associated with those modules
pub struct ModulesManager {
statusdb: HashMap<ModType,Vec<ModStatusType>>,
botactions: HashMap<ModType,Vec<BotAction>>,
statusdb: HashMap<BotModule,Vec<ModStatusType>>,
botactions: HashMap<BotModule,Vec<BotAction>>,
}
- statusdb: HashMap<ModType,Vec<ModStatusType>> - Defines Modules and their ModStatusType (e.g., Enabled at an Instance level, Disabled at a Channel Level)
- botactions: HashMap<ModType,Vec<BotAction>> - Defines Modules and their BotActions (e.g., BotCommand , Listener, Routine)
- statusdb: HashMap<BotModule,Vec<ModStatusType>> - Defines Modules and their ModStatusType (e.g., Enabled at an Instance level, Disabled at a Channel Level)
- botactions: HashMap<BotModule,Vec<BotAction>> - Defines Modules and their BotActions (e.g., BotCommand , Listener, Routine)
Example
{
@ -19,28 +19,28 @@ Example
*/
const OF_CMD_CHANNEL:Channel = Channel(String::new());
use core::panic;
use std::collections::HashMap;
use std::sync::Arc;
use twitch_irc::message::PrivmsgMessage;
use casual_logger::Log;
use tokio::sync::RwLock;
use async_trait::async_trait;
use self::bot_actions::actions_util::BotAR;
use crate::core::bot_actions::actions_util;
use crate::core::botinstance::{BotInstance, ChType,ChangeResult};
use crate::core::bot_actions::ExecBodyParams;
use crate::core::botinstance::{BotInstance, Channel,ChangeResult};
use crate::core::botlog;
use crate::core::identity::{self, Permissible,IdentityManager};
use crate::core::bot_actions;
pub use ChType::Channel;
pub use ModType::BotModule;
use std::hash::{Hash, Hasher};
@ -49,8 +49,6 @@ use super::identity::ChatBadge;
pub async fn init(mgr: Arc<ModulesManager>) {
const OF_CMD_CHANNEL:ChType = Channel(String::new());
// 1. Define the BotAction
let botc1 = BotCommand {
module: BotModule(String::from("core")),
@ -71,7 +69,8 @@ pub async fn init(mgr: Arc<ModulesManager>) {
// 2. Add the BotAction to ModulesManager
botc1.add_core_to_modmgr(Arc::clone(&mgr)).await;
async fn cmd_enable(bot: BotAR, msg: PrivmsgMessage) {
// async fn cmd_enable(bot: BotAR, msg: PrivmsgMessage) {
async fn cmd_enable(params : ExecBodyParams) {
/*
There should be additional validation checks
- BotAdmins can only run instance level (-i) enables
@ -104,12 +103,11 @@ pub async fn init(mgr: Arc<ModulesManager>) {
*/
// [x] Unwraps arguments from message
let (arg1, arg2) = {
let mut argv = msg.message_text.split(' ');
let mut argv = params.msg.message_text.split(' ');
argv.next(); // Skip the command name
@ -126,8 +124,8 @@ pub async fn init(mgr: Arc<ModulesManager>) {
&self,
requestor: String,
requestor_badge: Option<ChatBadge>,
trg_module: ModType,
// channel: Option<ChType>,
trg_module: BotModule,
// channel: Option<Channel>,
trg_level: StatusLvl,
bot: BotAR,
) -> ChangeResult
@ -135,26 +133,28 @@ pub async fn init(mgr: Arc<ModulesManager>) {
// [x] requestor: String,
let requestor = msg.clone().sender.name;
let requestor = params.msg.clone().sender.name;
// [x] requestor_badge: Option<ChatBadge>,
let mut requestor_badge_mut: Option<ChatBadge> = None;
for b in &msg.badges {
for b in &params.msg.badges {
if b.name == "moderator" {
requestor_badge_mut = Some(ChatBadge::Mod);
} else if b.name == "broadcaster" {
requestor_badge_mut = Some(ChatBadge::Broadcaster);
} else if b.name == "vip" {
requestor_badge_mut = Some(ChatBadge::VIP);
}
}
let requestor_badge = requestor_badge_mut;
// [x] trg_module: ModType,
// - [x] Need to validate an actual ModType - otherwise, fail or exit the cmd
// [x] trg_module: BotModule,
// - [x] Need to validate an actual BotModule - otherwise, fail or exit the cmd
let trg_module = if (arg1 == Some("-i")) || (arg1 == Some("-f")) { arg2 } else { arg1 };
@ -162,21 +162,28 @@ pub async fn init(mgr: Arc<ModulesManager>) {
// if let None = trg_module {
if trg_module.is_none() {
let botlock = bot.read().await;
// let botlock = params.bot.read().await;
let outmsg = "uuh You need to pass a module";
botlog::debug(
outmsg,
Some("botmodules.rs > cmd_enable()".to_string()),
Some(&msg),
Some(&params.msg),
);
botlock
.botmgrs
.chat
.say_in_reply_to(&msg, outmsg.to_string())
.await;
// We should call a notification around here
let bot = params.clone().bot;
let botclone = Arc::clone(&bot);
let botlock = botclone.read().await;
botlock.botmgrs.chat.send_botmsg(super::chat::BotMsgType::Notif(
outmsg.to_string()
),
params.clone(),
).await;
return;
@ -185,29 +192,29 @@ pub async fn init(mgr: Arc<ModulesManager>) {
// [x] trg_level: StatusLvl,
let currchnl = msg.channel_login.to_lowercase();
let currchnl = params.msg.channel_login.to_lowercase();
let trg_level =
if arg1 == Some("-i") || arg1 == Some("-f") { StatusLvl::Instance }
// else if arg1 == Some("-f") { StatusLvl::Instance }
else { StatusLvl::Ch(ChType::Channel(currchnl)) }
else { StatusLvl::Ch(Channel(currchnl)) }
;
let botlock = bot.read().await;
let botlock = params.bot.read().await;
let modmgr = Arc::clone(&botlock.botmodules);
let id = botlock.get_identity();
// modmgr.exec_enable(requestor, requestor_badge, trg_module, trg_level, id)
let rslt = modmgr.exec_enable(
requestor,
requestor_badge,
ModType::BotModule(trg_module.unwrap().to_string()),
BotModule(trg_module.unwrap().to_string()),
trg_level,
id).await;
// We should call a notification around here
let outmsg = match rslt.clone() {
ChangeResult::Failed(a) => format!("Stare Failed : {}",a),
@ -215,12 +222,13 @@ pub async fn init(mgr: Arc<ModulesManager>) {
ChangeResult::Success(a) => format!("YAAY Success : {}",a),
};
botlock
.botmgrs
.chat
.say_in_reply_to(&msg, outmsg.to_string())
.await;
botlock.botmgrs.chat.send_botmsg(super::chat::BotMsgType::Notif(
outmsg.to_string()
),
params.clone(),
).await;
}
@ -245,7 +253,8 @@ pub async fn init(mgr: Arc<ModulesManager>) {
// 2. Add the BotAction to ModulesManager
botc1.add_core_to_modmgr(Arc::clone(&mgr)).await;
async fn cmd_disable(bot: BotAR, msg: PrivmsgMessage) {
// async fn cmd_disable(bot: BotAR, msg: PrivmsgMessage) {
async fn cmd_disable(params : ExecBodyParams) {
/*
There should be additional validation checks
- BotAdmins can only run instance level (-i) disables and (-f) force disable
@ -281,11 +290,11 @@ pub async fn init(mgr: Arc<ModulesManager>) {
*/
// [x] Unwraps arguments from message
// [x] Unwraps arguments from message
let (arg1, arg2) = {
let mut argv = msg.message_text.split(' ');
let mut argv = params.msg.message_text.split(' ');
argv.next(); // Skip the command name
@ -302,8 +311,8 @@ pub async fn init(mgr: Arc<ModulesManager>) {
&self,
requestor: String,
requestor_badge: Option<ChatBadge>,
trg_module: ModType,
// channel: Option<ChType>,
trg_module: BotModule,
// channel: Option<Channel>,
trg_level: StatusLvl,
force: bool,
// bot: BotAR,
@ -313,47 +322,50 @@ pub async fn init(mgr: Arc<ModulesManager>) {
// [x] requestor: String,
let requestor = msg.clone().sender.name;
let requestor = params.msg.clone().sender.name;
// [x] requestor_badge: Option<ChatBadge>,
let mut requestor_badge_mut: Option<ChatBadge> = None;
for b in &msg.badges {
for b in &params.msg.badges {
if b.name == "moderator" {
requestor_badge_mut = Some(ChatBadge::Mod);
} else if b.name == "broadcaster" {
requestor_badge_mut = Some(ChatBadge::Broadcaster);
} else if b.name == "vip" {
requestor_badge_mut = Some(ChatBadge::VIP);
}
}
let requestor_badge = requestor_badge_mut;
// [x] trg_module: ModType,
// - [x] Need to validate an actual ModType - otherwise, fail or exit the cmd
// [x] trg_module: BotModule,
// - [x] Need to validate an actual BotModule - otherwise, fail or exit the cmd
let trg_module = if (arg1 == Some("-i")) || (arg1 == Some("-f")) { arg2 } else { arg1 };
// if no trg_module was passed
// if let None = trg_module {
if trg_module.is_none() {
let botlock = bot.read().await;
let botlock = params.bot.read().await;
let outmsg = "uuh You need to pass a module";
botlog::debug(
outmsg,
Some("botmodules.rs > cmd_disable()".to_string()),
Some(&msg),
Some(&params.msg),
);
botlock
.botmgrs
.chat
.say_in_reply_to(&msg, outmsg.to_string())
.await;
// We should call a notification around here
botlock.botmgrs.chat.send_botmsg(super::chat::BotMsgType::Notif(
outmsg.to_string()
),
params.clone(),
).await;
return;
@ -363,27 +375,26 @@ pub async fn init(mgr: Arc<ModulesManager>) {
// [x] trg_level: StatusLvl,
let currchnl = msg.channel_login.to_lowercase();
let currchnl = params.msg.channel_login.to_lowercase();
let trg_level =
if arg1 == Some("-i") || arg1 == Some("-f") { StatusLvl::Instance }
// else if arg1 == Some("-f") { StatusLvl::Instance }
else { StatusLvl::Ch(ChType::Channel(currchnl)) }
else { StatusLvl::Ch(Channel(currchnl)) }
;
let botlock = bot.read().await;
let botlock = params.bot.read().await;
let modmgr = Arc::clone(&botlock.botmodules);
let id = botlock.get_identity();
let force = arg1 == Some("-f");
// modmgr.exec_enable(requestor, requestor_badge, trg_module, trg_level, id)
let rslt = modmgr.exec_disable(
requestor,
requestor_badge,
ModType::BotModule(trg_module.unwrap().to_string()),
BotModule(trg_module.unwrap().to_string()),
trg_level,
force,
id).await;
@ -395,13 +406,13 @@ pub async fn init(mgr: Arc<ModulesManager>) {
ChangeResult::Success(a) => format!("YAAY Success : {}",a),
};
botlock
.botmgrs
.chat
.say_in_reply_to(&msg, outmsg.to_string())
.await;
// We should call a notification around here
botlock.botmgrs.chat.send_botmsg(super::chat::BotMsgType::Notif(
outmsg.to_string()
),
params.clone(),
).await;
}
@ -411,23 +422,19 @@ pub async fn init(mgr: Arc<ModulesManager>) {
#[derive(Debug, Clone)]
pub enum ModType {
BotModule(String),
}
pub struct BotModule(pub String);
impl PartialEq for ModType {
impl PartialEq for BotModule {
fn eq(&self, other: &Self) -> bool {
let BotModule(name1) = self.clone();
let BotModule(name2) = other.clone();
name1.to_lowercase() == name2.to_lowercase()
}
}
impl Eq for ModType {}
impl Eq for BotModule {}
impl Hash for ModType{
impl Hash for BotModule{
fn hash<H: Hasher>(&self, state: &mut H) {
// self.id.hash(state);
// self.phone.hash(state);
let BotModule(name) = self.clone();
name.to_lowercase().hash(state);
}
@ -443,7 +450,7 @@ pub enum ModGroup {
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum StatusLvl {
Instance,
Ch(ChType),
Ch(Channel),
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
@ -459,10 +466,10 @@ pub enum BotAction {
}
impl BotAction {
pub async fn execute(&self, m: BotAR, n: PrivmsgMessage) {
pub async fn execute(&self, params : ExecBodyParams) {
match self {
BotAction::L(a) => a.execute(m, n).await,
BotAction::C(a) => a.execute(m, n).await,
BotAction::L(a) => a.execute(params).await,
BotAction::C(a) => a.execute(params).await,
_ => (),
}
}
@ -477,7 +484,7 @@ pub trait BotActionTrait {
}
pub struct BotCommand {
pub module: ModType,
pub module: BotModule,
pub command: String, // command call name
pub alias: Vec<String>, // String of alternative names
pub exec_body: bot_actions::actions_util::ExecBody,
@ -486,8 +493,8 @@ pub struct BotCommand {
}
impl BotCommand {
pub async fn execute(&self, m: BotAR, n: PrivmsgMessage) {
(*self.exec_body)(m, n).await;
pub async fn execute(&self, params : ExecBodyParams) {
(*self.exec_body)(params).await;
}
}
@ -515,15 +522,15 @@ impl BotActionTrait for BotCommand {
}
pub struct Listener {
pub module: ModType,
pub module: BotModule,
pub name: String,
pub exec_body: bot_actions::actions_util::ExecBody,
pub help: String,
}
impl Listener {
pub async fn execute(&self, m: BotAR, n: PrivmsgMessage) {
(self.exec_body)(m, n).await;
pub async fn execute(&self, params : ExecBodyParams) {
(self.exec_body)(params).await;
}
}
@ -565,22 +572,23 @@ impl BotActionTrait for Listener {
pub struct Routine {}
type StatusdbEntry = (ModGroup, Vec<StatusType>);
type ModuleActions = Vec<Arc<RwLock<BotAction>>>;
pub struct ModulesManager {
statusdb: Arc<RwLock<HashMap<ModType, StatusdbEntry>>>,
pub botactions: Arc<RwLock<HashMap<ModType, Vec<BotAction>>>>,
statusdb: Arc<RwLock<HashMap<BotModule, StatusdbEntry>>>,
pub botactions: Arc<RwLock<HashMap<BotModule, ModuleActions>>>,
}
/*
statusdb
<HashMap
<ModType, <-- e.g., BotModule(String::from("experiments001"))
<BotModule, <-- e.g., BotModule(String::from("experiments001"))
Vec<ModStatusType> <-- shows Enabled/Disabled per Status level
botactions
HashMap<
ModType, <-- e.g., BotModule(String::from("experiments001"))
BotModule, <-- e.g., BotModule(String::from("experiments001"))
Vec<BotAction>> BotCommand, Listener
*/
@ -618,7 +626,7 @@ impl ModulesManager {
}
pub async fn moduleslist(&self) -> HashMap<ModType,ModGroup>
pub async fn moduleslist(&self) -> HashMap<BotModule,ModGroup>
{
// let db = Arc::clone(&self.statusdb);
@ -635,7 +643,7 @@ impl ModulesManager {
outmap
}
pub async fn modstatus(&self, in_module: ModType, in_chnl: ChType) -> StatusType {
pub async fn modstatus(&self, in_module: BotModule, in_chnl: Channel) -> StatusType {
// Example usage : botmanager.modstatus(
// BotModule("GambaCore"),
// Channel("modulatingforce")
@ -646,7 +654,6 @@ impl ModulesManager {
let dbt = self.statusdb.read().await;
// let a = dbt.entry(in_module.clone()).;
let (mgrp,statusvector) = dbt.get(&in_module).unwrap();
match mgrp {
@ -714,7 +721,7 @@ impl ModulesManager {
&self,
requestor: String,
requestor_badge: Option<ChatBadge>,
trg_module: ModType,
trg_module: BotModule,
trg_level: StatusLvl,
id: Arc<RwLock<IdentityManager>>,
) -> ChangeResult
@ -758,17 +765,23 @@ impl ModulesManager {
return ChangeResult::Failed("Module doesn't exist".to_string());
}
botlog::trace(
"ACQUIRING WRITE LOCK : ID",
Some("ModulesManager > Exec_enable".to_string()),
None,
);
let mut idlock = id.write().await;
// if trg_level = StatusLvl::Instance , the temp_chnl = the broadcaster's or the chatter's
let arb_chnl = match trg_level.clone() {
StatusLvl::Instance => ChType::Channel(requestor.to_lowercase()),
StatusLvl::Instance => Channel(requestor.to_lowercase()),
StatusLvl::Ch(a) => a,
};
const OF_CMD_CHANNEL:ChType = Channel(String::new());
const OF_CMD_CHANNEL:Channel = Channel(String::new());
let (admin_level_access,_) = idlock.can_user_run(requestor.clone(), arb_chnl.clone(), requestor_badge.clone(),
vec![
@ -903,7 +916,7 @@ impl ModulesManager {
&self,
requestor: String,
requestor_badge: Option<ChatBadge>,
trg_module: ModType,
trg_module: BotModule,
trg_level: StatusLvl,
force: bool,
id: Arc<RwLock<IdentityManager>>,
@ -940,17 +953,24 @@ impl ModulesManager {
return ChangeResult::Failed("Module doesn't exist".to_string());
}
botlog::trace(
"ACQUIRING WRITE LOCK : ID",
Some("ModulesManager > Exec_disable".to_string()),
None,
);
let mut idlock = id.write().await;
// if trg_level = StatusLvl::Instance , the temp_chnl = the broadcaster's or the chatter's
let arb_chnl = match trg_level.clone() {
StatusLvl::Instance => ChType::Channel(requestor.to_lowercase()),
StatusLvl::Instance => Channel(requestor.to_lowercase()),
StatusLvl::Ch(a) => a,
};
const OF_CMD_CHANNEL:ChType = Channel(String::new());
const OF_CMD_CHANNEL:Channel = Channel(String::new());
let (admin_level_access,_) = idlock.can_user_run(requestor.clone(), arb_chnl.clone(), requestor_badge.clone(),
vec![
@ -1080,7 +1100,7 @@ impl ModulesManager {
ChangeResult::Failed("ERROR : Not implemented yet".to_string())
}
pub async fn set_instance_disabled(&self, in_module: ModType) -> (StatusType,ChangeResult) {
pub async fn set_instance_disabled(&self, in_module: BotModule) -> (StatusType,ChangeResult) {
// at Instance level
// - If core module, do nothing
@ -1112,10 +1132,9 @@ impl ModulesManager {
},
}
// (StatusType::Disabled(StatusLvl::Instance),ChangeResult::NoChange("Nothing needed".to_string()))
}
pub async fn force_disable(&self, in_module: ModType) -> (StatusType,ChangeResult) {
pub async fn force_disable(&self, in_module: BotModule) -> (StatusType,ChangeResult) {
// Disables the module at Instance level, and removes all Enabled at Channel level
// - Bot Moderators MUST Re-enable if they were enabled before
// - If core module, do nothing
@ -1156,10 +1175,9 @@ impl ModulesManager {
},
}
// (StatusType::Disabled(StatusLvl::Instance),ChangeResult::NoChange("Nothing needed".to_string()))
}
pub async fn set_instance_enabled(&self, in_module: ModType) -> (StatusType,ChangeResult) {
pub async fn set_instance_enabled(&self, in_module: BotModule) -> (StatusType,ChangeResult) {
// at Instance level
// - If core module, do nothing
@ -1191,10 +1209,9 @@ impl ModulesManager {
},
}
// (StatusType::Enabled(StatusLvl::Instance),ChangeResult::NoChange("Nothing needed".to_string()))
}
pub async fn set_ch_disabled(&self, in_module: ModType , in_chnl: ChType) -> (StatusType,ChangeResult) {
pub async fn set_ch_disabled(&self, in_module: BotModule , in_chnl: Channel) -> (StatusType,ChangeResult) {
// at Instance level
// - If core module, do nothing
@ -1229,10 +1246,9 @@ impl ModulesManager {
},
}
// (StatusType::Disabled(StatusLvl::Instance),ChangeResult::NoChange("Nothing needed".to_string()))
}
pub async fn set_ch_enabled(&self, in_module: ModType , in_chnl: ChType) -> (StatusType,ChangeResult) {
pub async fn set_ch_enabled(&self, in_module: BotModule , in_chnl: Channel) -> (StatusType,ChangeResult) {
// at Instance level
// - If core module, do nothing
@ -1267,21 +1283,20 @@ impl ModulesManager {
}
// (StatusType::Enabled(StatusLvl::Instance),ChangeResult::NoChange("Nothing needed".to_string()))
}
pub async fn add_botaction(&self, in_module: ModType, in_action: BotAction) {
pub async fn add_botaction(&self, in_module: BotModule, in_action: BotAction) {
self.int_add_botaction(in_module,ModGroup::Custom,in_action).await;
}
pub async fn add_core_act(&self, in_module: ModType, in_action: BotAction) {
pub async fn add_core_act(&self, in_module: BotModule, in_action: BotAction) {
self.int_add_botaction(in_module,ModGroup::Core,in_action).await;
}
pub async fn affirm_in_statusdb(&self,in_module:ModType,in_modgroup: ModGroup) {
pub async fn affirm_in_statusdb(&self,in_module:BotModule,in_modgroup: ModGroup) {
let mut dbt = self.statusdb.write().await;
@ -1297,7 +1312,7 @@ impl ModulesManager {
}
async fn int_add_botaction(&self, in_module: ModType, in_modgroup: ModGroup, in_action: BotAction) {
async fn int_add_botaction(&self, in_module: BotModule, in_modgroup: ModGroup, in_action: BotAction) {
botlog::trace(
"Add botaction called",
Some("ModulesManager > init()".to_string()),
@ -1320,13 +1335,21 @@ impl ModulesManager {
// - 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
async fn find_conflict_module(mgr: &ModulesManager, act: &BotAction) -> Option<ModType> {
async fn find_conflict_module(mgr: &ModulesManager, act: &BotAction) -> Option<BotModule> {
if let BotAction::C(incmd) = act {
let actdb = mgr.botactions.read().await;
for (module, moduleactions) in &(*actdb) {
for modact in moduleactions.iter() {
if let BotAction::C(dbcmd) = &modact {
// for modact in moduleactions.iter() {
for modact_prelock in moduleactions.iter() {
let modact = modact_prelock.read().await;
// if let BotAction::C(dbcmd) = &modact {
if let BotAction::C(dbcmd) = &(*modact) {
// At this point, there is an command incmd and looked up dbcmd
// [x] check if given botcommand c.command:String conflicts with any in botactions
@ -1382,7 +1405,7 @@ impl ModulesManager {
let mut a = self.botactions.write().await;
let modactions = a.entry(in_module.clone()).or_insert(Vec::new());
modactions.push(in_action);
modactions.push(Arc::new(RwLock::new(in_action)));
botlog::trace(
format!(
@ -1395,12 +1418,12 @@ impl ModulesManager {
);
}
fn _statuscleanup(&self, _: Option<ChType>) {
fn _statuscleanup(&self, _: Option<Channel>) {
// internal cleans up statusdb . For example :
// - remove redudancies . If we see several Enabled("m"), only keep 1x
// - Clarify Conflict. If we see Enabled("m") and Disabled("m") , we remove Enabled("m") and keep Disabled("m")
// the IDEAL is that this is ran before every read/update operation to ensure quality
// Option<ChType> can pass Some(Channel("m")) (as an example) so statuscleanup only works on the given channel
// Option<Channel> can pass Some(Channel("m")) (as an example) so statuscleanup only works on the given channel
// Passing None to chnl may be a heavy operation, as this will review and look at the whole table
}
}
@ -1467,10 +1490,10 @@ mod core_modulesmanager {
*/
async fn complex_workflow(
in_module: ModType ,
in_module: BotModule ,
in_modgroup : ModGroup ,
in_chnl1 : ChType,
in_chnl2 : ChType)
in_chnl1 : Channel,
in_chnl2 : Channel)
{
@ -1643,7 +1666,7 @@ mod core_modulesmanager {
let in_module = BotModule("Experiments01".to_string());
let in_modgroup = ModGroup::Custom;
let (in_chnl1,in_chnl2) =
(ChType::Channel("TestChannel01".to_string()),ChType::Channel("TestChannel02".to_string()));
(Channel("TestChannel01".to_string()),Channel("TestChannel02".to_string()));
complex_workflow(in_module, in_modgroup, in_chnl1, in_chnl2).await;
@ -1659,7 +1682,7 @@ mod core_modulesmanager {
let in_module = BotModule("CoreModule01".to_string());
let in_modgroup = ModGroup::Core;
let (in_chnl1,in_chnl2) =
(ChType::Channel("TestChannel01".to_string()),ChType::Channel("TestChannel02".to_string()));
(Channel("TestChannel01".to_string()),Channel("TestChannel02".to_string()));
complex_workflow(in_module, in_modgroup, in_chnl1, in_chnl2).await;
@ -1701,7 +1724,7 @@ mod core_modulesmanager {
async fn inner_enable_disable_complex(
requestor:String,
channel:ChType,
channel:Channel,
idmgr:IdentityManager,
modsmgr:Arc<ModulesManager>)
{
@ -1724,7 +1747,7 @@ mod core_modulesmanager {
let requestor_badge = None; // If they are a Mod on the Given Channel already, that can be evaluated without the current badge
const OF_CMD_CHANNEL:ChType = Channel(String::new());
const OF_CMD_CHANNEL:Channel = Channel(String::new());
let (admin_level_access,_) = idlock.can_user_run(requestor.clone(), channel.clone(), requestor_badge.clone(),
vec![
@ -1773,7 +1796,7 @@ mod core_modulesmanager {
// [-] requestor_badge: Option<ChatBadge>,
// [x] trg_module: ModType,
// [x] trg_module: BotModule,
let trg_module = in_module;
// [x] trg_level: StatusLvl,
@ -2020,7 +2043,7 @@ mod core_modulesmanager {
assert!(rslt.contains(&identity::UserRole::BotAdmin));
let channel = ChType::Channel("somechannel".to_string());
let channel = Channel("somechannel".to_string());
inner_enable_disable_complex(requestor, channel, idmgr, modsmgr).await;
@ -2058,7 +2081,7 @@ mod core_modulesmanager {
let requestor = "mod_user".to_string();
// let botadmin_badge = &None;
let channel = ChType::Channel("somechannel".to_string());
let channel = Channel("somechannel".to_string());
idmgr.affirm_chatter_in_db(requestor.clone()).await;
@ -2109,7 +2132,7 @@ mod core_modulesmanager {
let requestor = "regular_user".to_string();
let channel = ChType::Channel("somechannel".to_string());
let channel = Channel("somechannel".to_string());
idmgr.affirm_chatter_in_db(requestor.clone()).await;
@ -2142,7 +2165,7 @@ mod core_modulesmanager {
let requestor = "regular_user".to_string();
let channel = ChType::Channel("somechannel".to_string());
let channel = Channel("somechannel".to_string());
idmgr.affirm_chatter_in_db(requestor.clone()).await;

View file

@ -15,21 +15,36 @@ use rand::Rng;
use crate::core::ratelimiter;
use crate::core::ratelimiter::RateLimiter;
use crate::core::botinstance::ChType;
use crate::core::botinstance::Channel;
use crate::core::botlog;
pub use ChType::Channel;
use tokio::time::{sleep, Duration};
use super::bot_actions::ExecBodyParams;
use super::identity;
use async_recursion::async_recursion;
#[derive(Clone)]
pub struct Chat {
pub ratelimiters: Arc<Mutex<HashMap<ChType, 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>,
}
#[derive(Clone,Debug)]
pub enum BotMsgType<'a> {
SayInReplyTo(&'a PrivmsgMessage,String),
Say(String,String),
Notif(String), // For Bot Sent Notifications
}
impl Chat {
pub fn init(
ratelimiters: HashMap<ChType, RateLimiter>,
ratelimiters: HashMap<Channel, RateLimiter>,
client: TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>,
) -> Chat {
Chat {
@ -38,12 +53,16 @@ impl Chat {
}
}
pub async fn init_channel(&mut self, chnl: ChType) {
pub async fn init_channel(&mut self, chnl: Channel) {
let n = RateLimiter::new();
self.ratelimiters.lock().await.insert(chnl, n);
}
pub async fn say_in_reply_to(&self, msg: &PrivmsgMessage, mut outmsg: String) {
#[async_recursion]
pub async fn send_botmsg(&self, msginput: BotMsgType<'async_recursion>, params : ExecBodyParams) {
/*
formats message before sending to TwitchIRC
@ -53,12 +72,256 @@ impl Chat {
*/
botlog::trace(
format!("send_bot_msg params : {:?}",msginput).as_str(),
Some("chat.rs > send_botmsg ".to_string()),
Some(&params.msg),
);
Log::flush();
let (channel_login,mut outmsg) = match msginput.clone() {
BotMsgType::SayInReplyTo(msg, outmsg) => {
(msg.channel_login.clone(),outmsg)
},
BotMsgType::Say(a,b ) => {
(a.clone(),b.clone())
},
BotMsgType::Notif(outmsg) => {
(params.msg.channel_login.clone(),outmsg)
}
};
botlog::trace(
"BEFORE parent_module call",
Some("chat.rs > send_botmsg ".to_string()),
Some(&params.msg),
);
let parent_module = params.get_parent_module().await;
let params_clone = params.clone();
let botclone = Arc::clone(&params_clone.bot);
let botlock = botclone.read().await;
let modmgr = Arc::clone(&botlock.botmodules);
let modstatus = (*modmgr).modstatus(
parent_module.clone().expect("ERROR - Expected a module"),
Channel(channel_login.clone())
).await;
if !params.bot.read().await.bot_channels.contains(&Channel(channel_login.clone())) {
botlog::warn(
&format!("A message attempted to send for a Non-Joined Channel : {}",channel_login.clone()),
Some("Chat > send_botmsg".to_string()),
None,
);
if let BotMsgType::SayInReplyTo(_prvmsg,_outmsg) = msginput {
self.send_botmsg(BotMsgType::Notif(
"uuh Bot can't send to a channel it isn't joined".to_string(),
),
params).await;
}
return ;
}
/*
[x] !! => 03.24 - Somewhere around here, we should be validating module for target channel
*/
/*
- Use ModulesManager.modstatus
modstatus(&self, in_module: BotModule, in_chnl: Channel) -> StatusType
*/
botlog::trace(
format!("BEFORE modstatus check : modstatus = {:?}",modstatus).as_str(),
Some("chat.rs > send_botmsg ".to_string()),
Some(&params.msg),
);
if let super::botmodules::StatusType::Disabled(lvl) = modstatus {
// Note : At this point, chat was called in a channel where the parent module IS enabled
// - this type of validation is done outside of Chat()
// This though takes into account scenarios where we are targetting a different channel
botlog::trace(
"BEFORE msginput check",
Some("chat.rs > send_botmsg ".to_string()),
Some(&params.msg),
);
Log::flush();
match msginput {
BotMsgType::Notif(_) => (), // Do nothing with Notif > We'll validate the user later to handle
BotMsgType::SayInReplyTo(_, _) | BotMsgType::Say(_,_) => {
botlog::trace(
"BEFORE potential Async recursion",
Some("chat.rs > send_botmsg ".to_string()),
Some(&params.clone().msg),
);
Log::flush();
self.send_botmsg(BotMsgType::Notif(
format!("uuh {:?} is disabled on {} : {:?}",
parent_module.clone().unwrap(),
channel_login.clone(),
lvl
),
), params.clone()
).await;
botlog::trace(
"AFTER potential Async recursion",
Some("chat.rs > send_botmsg ".to_string()),
Some(&params.msg),
);
Log::flush();
return
},
}
}
/*
[x] !! => 03.24 - Would be nice if around here , validate the user has at least some special roles in target channel
- NOTE : If these need to be refined, they can be by the custom module developer at the parent calling function of say()
- This just prevents Chat from being triggered in a channel where the sending chatter does not have any special roles
*/
/*
Use
pub async fn getspecialuserroles(
&self,
chattername: String,
channel: Option<Channel>,
) -> Vec<UserRole> {
*/
// let params_clone = params.clone();
let botclone = Arc::clone(&params.bot);
let botlock = botclone.read().await;
let id = botlock.get_identity();
let id = Arc::clone(&id);
let idlock = id.read().await; // <-- [x] 03.24 - seems to work
let user_roles = idlock.getspecialuserroles(
params.get_sender(),
Some(Channel(channel_login.clone()))
).await;
botlog::trace(
format!("BEFORE user roles check check : userroles = {:?}",user_roles).as_str(),
Some("chat.rs > send_botmsg ".to_string()),
Some(&params.msg),
);
Log::flush();
// [x] If user has any of the following target roles, they will be allowed - otherwise, they will not be allowed to send
// - Otherwise if not (checked here) , this will not run
// - NOTE : For now, I've removed BotAdmin just for curiosity - BotAdmins can always elevate themselves if they want
// - Will be adding VIP to this as this should include Channel_Level Roles
if !(user_roles.contains(&identity::UserRole::Mod(Channel(channel_login.clone())))
|| user_roles.contains(&identity::UserRole::SupMod(Channel(channel_login.clone())))
|| user_roles.contains(&identity::UserRole::Broadcaster)
|| user_roles.contains(&identity::UserRole::VIP(Channel(channel_login.clone())))
)
{
match msginput {
BotMsgType::Notif(_) => {
// If Sender is Not a BotAdmin, don't do anything about the notification and return
if !user_roles.contains(&identity::UserRole::BotAdmin) {
return;
}
},
BotMsgType::SayInReplyTo(_,_ ) | BotMsgType::Say(_,_) => {
// If the BotMsg a Say/SayInReplyTo (from Developer or Chatter) , and the Sender does not have Specific Roles in the Source Channel Sent
self.send_botmsg(BotMsgType::Notif(
format!("uuh You do not have the right roles to send to {}",
channel_login.clone(),
),
), params.clone()
).await;
return;
},
};
}
/*
At this stage from the above Validations :
msginput would be :
a. BotMsgType::SayInReplyTo | BotMsgType::Say that is
- Towards a Destination Channel that the Sender has Elevated User Roles to Send to
b. BotMsgType::Notif that is
- Going to be sent to the Source Channel (rather than the original say/sayinreplyto was towards)
- A Sender that has Elevated User Roles in Source Channel will see a message ; otherwise, they will not
*/
/*
Use the following
pub async fn can_user_run(
&mut self,
usr: String,
channelname: Channel,
chat_badge: Option<ChatBadge>,
cmdreqroles: Vec<UserRole>, // ) -> Result<Permissible,Box<dyn Error>> {
) -> (Permissible, ChangeResult) {
*/
let rl = Arc::clone(&self.ratelimiters);
let mut rllock = rl.lock().await;
botlog::debug(
&format!("Ratelimiter being checked for channel : {}",channel_login.clone()),
Some("Chat > send_botmsg".to_string()),
None,
);
let contextratelimiter = rllock
// .get_mut()
.get_mut(&Channel(String::from(&msg.channel_login)))
.get_mut(&Channel(channel_login.to_lowercase().clone()))
.expect("ERROR: Issue with Rate limiters");
// Continue to check the limiter and sleep if required if the minimum is not reached
@ -75,20 +338,41 @@ impl Chat {
outmsg.push_str(blankspace);
}
self.client.say_in_reply_to(msg, outmsg).await.unwrap();
match msginput.clone() {
BotMsgType::SayInReplyTo(msg, _) => {
self.client.say_in_reply_to(msg, outmsg).await.unwrap();
},
BotMsgType::Say(a, _) => {
self.client.say(a, outmsg).await.unwrap();
}
BotMsgType::Notif(outmsg) => {
self.client.say_in_reply_to(&params.msg, outmsg).await.unwrap();
}
}
contextratelimiter.increment_counter();
let logstr = format!(
"(#{}) > {} ; contextratelimiter : {:?}",
msg.channel_login, "rate limit counter increase", contextratelimiter
channel_login.clone(), "rate limit counter increase", contextratelimiter
);
botlog::trace(
logstr.as_str(),
Some("Chat > say_in_reply_to".to_string()),
Some(msg),
);
if let BotMsgType::SayInReplyTo(msg,_ ) = msginput {
botlog::trace(
logstr.as_str(),
Some("Chat > send_botmsg".to_string()),
Some(msg),
);
} else {
botlog::trace(
logstr.as_str(),
Some("Chat > send_botmsg".to_string()),
None,
);
}
}
ratelimiter::LimiterResp::Skip => {
// (); // do nothing otherwise
@ -98,13 +382,76 @@ impl Chat {
}
}
Log::flush();
Log::flush();
}
async fn _say(&self, _: String, _: String) {
// pub async fn say_in_reply_to(&self, msg: &PrivmsgMessage, outmsg: String) {
// #[async_recursion]
pub async fn say_in_reply_to(&self, msg: &PrivmsgMessage, outmsg: String , params : ExecBodyParams) {
// let params_clone = params.clone();
// let botclone = Arc::clone(&params_clone.bot);
// let botlock = botclone.read().await;
// let id = botlock.get_identity();
// let id = Arc::clone(&id);
// // botlog::trace(
// // "ACQUIRING WRITE LOCK : ID",
// // Some("Chat > send_botmsg".to_string()),
// // Some(&params.msg),
// // );
// // Log::flush();
// botlog::trace(
// "ACQUIRING READ LOCK : ID",
// Some("Chat > send_botmsg".to_string()),
// Some(&params.msg),
// );
// Log::flush();
// // let idlock = id.write().await; // <-- [ ] 03.24 - This is definitely locking it
// let idlock = id.read().await; // <-- [ ] 03.24 - seems to work
// let a = idlock.getspecialuserroles(params.get_sender(), Some(Channel(msg.channel_login.clone()))).await;
// botlog::trace(
// format!("GETSPECIALUSERROLES RESULT : {:?}",a).as_str(),
// Some("Chat > send_botmsg".to_string()),
// Some(&params.msg),
// );
// Log::flush();
// // botlog::trace(
// // "ACQUIRED WRITE LOCK : ID",
// // Some("Chat > send_botmsg".to_string()),
// // Some(&params.msg),
// // );
// // Log::flush();
// botlog::trace(
// "ACQUIRED READ LOCK : ID",
// Some("Chat > send_botmsg".to_string()),
// Some(&params.msg),
// );
// Log::flush();
self.send_botmsg(BotMsgType::SayInReplyTo(msg, outmsg) , params).await;
}
// pub async fn say(&self, channel_login: String, message: String) {
pub async fn say(&self, channel_login: String, message: String , params : ExecBodyParams) {
// more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say
// self.client.say(msg,outmsg).await.unwrap();
self.send_botmsg(BotMsgType::Say(channel_login.to_lowercase(), message), params).await;
}
async fn _me(&self, _: String, _: String) {

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,5 @@
/*
`modules` will :
`custom` will :
- be a starting refrence point for the bot instance to pull module definitions for
*/
@ -11,7 +11,8 @@ pub use crate::core::botmodules::ModulesManager;
// [ ] Load submodules
mod experiments;
// mod experiments;
mod experimental;
// [ ] init() function that accepts bot instance - this is passed to init() on submodules
@ -19,5 +20,6 @@ pub async fn init(mgr: Arc<ModulesManager>) {
// Modules initializer loads modules into the bot
// this is achieved by calling submodules that also have fn init() defined
experiments::init(mgr).await
// experiments::init(mgr).await
experimental::init(mgr).await;
}

View file

@ -0,0 +1,24 @@
/*
`experimental` will :
- be for mostly experimental
*/
use std::sync::Arc;
// pub use crate::core::botinstance::BotInstance;
pub use crate::core::botmodules::ModulesManager;
// [ ] Load submodules
mod experiment001;
mod experiment002;
// [ ] init() function that accepts bot instance - this is passed to init() on submodules
pub async fn init(mgr: Arc<ModulesManager>) {
// Modules initializer loads modules into the bot
// this is achieved by calling submodules that also have fn init() defined
experiment001::init(Arc::clone(&mgr)).await;
experiment002::init(Arc::clone(&mgr)).await;
}

View file

@ -10,17 +10,18 @@
*/
const OF_CMD_CHANNEL:Channel = Channel(String::new());
use rand::Rng;
use std::sync::Arc;
use twitch_irc::message::PrivmsgMessage;
// use crate::core::botinstance::ChType::Channel;
use crate::core::botinstance::ChType;
use ChType::Channel;
use crate::core::bot_actions::ExecBodyParams;
use crate::core::botinstance::Channel;
use crate::core::botlog;
use crate::core::bot_actions::actions_util::{self, BotAR};
use crate::core::bot_actions::actions_util;
use crate::core::botmodules::{BotActionTrait, BotCommand, BotModule, Listener, ModulesManager};
use crate::core::identity::UserRole::*;
@ -29,8 +30,6 @@ use tokio::time::{sleep, Duration};
pub async fn init(mgr: Arc<ModulesManager>) {
const OF_CMD_CHANNEL:ChType = Channel(String::new());
// 1. Define the BotAction
let botc1 = BotCommand {
module: BotModule(String::from("experiments001")),
@ -60,18 +59,6 @@ pub async fn init(mgr: Arc<ModulesManager>) {
// 2. Add the BotAction to ModulesManager
list1.add_to_modmgr(Arc::clone(&mgr)).await;
// // 1. Define the BotAction
// let list1 = Listener {
// module: BotModule(String::from("experiments001")),
// name: String::from("babygirl Listener"),
// exec_body: actions_util::asyncbox(babygirl),
// help: String::from(""),
// };
// // 2. Add the BotAction to ModulesManager
// list1.add_to_modmgr(Arc::clone(&mgr)).await;
// 1. Define the BotAction
let botc1 = BotCommand {
module: BotModule(String::from("experiments001")),
@ -110,73 +97,84 @@ pub async fn init(mgr: Arc<ModulesManager>) {
}
async fn good_girl(bot: BotAR, msg: PrivmsgMessage) {
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 msg.sender.name.to_lowercase() == "ModulatingForce".to_lowercase()
|| msg.sender.name.to_lowercase() == "mzNToRi".to_lowercase()
// if msg.sender.name.to_lowercase() == "mzNToRi".to_lowercase()
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(&msg),
Some(&params.msg),
);
let rollwin = rand::thread_rng().gen_ratio(1, 1);
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(&msg),
Some(&params.msg),
);
let bot = Arc::clone(&bot);
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(&msg, String::from("GoodGirl xdd "))
.await;
.botmgrs
.chat
.say_in_reply_to(
&params.msg,
String::from("GoodGirl xdd "),
params.clone()
).await;
}
}
}
async fn testy(mut _chat: BotAR, msg: PrivmsgMessage) {
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(&msg),
Some(&params.msg),
);
}
async fn babygirl(bot: BotAR, msg: PrivmsgMessage) {
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(&msg),
Some(&params.msg),
);
let bot = Arc::clone(&bot);
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(&msg, String::from("16:13 notohh: cafdk"))
.await;
.say_in_reply_to(
&params.msg,
String::from("16:13 notohh: cafdk"),
params.clone()
).await;
sleep(Duration::from_secs_f64(0.5)).await;
@ -184,8 +182,11 @@ async fn babygirl(bot: BotAR, msg: PrivmsgMessage) {
botlock
.botmgrs
.chat
.say_in_reply_to(&msg, String::from("16:13 notohh: have fun eating princess"))
.await;
.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;
@ -193,21 +194,23 @@ async fn babygirl(bot: BotAR, msg: PrivmsgMessage) {
botlock
.botmgrs
.chat
.say_in_reply_to(&msg, String::from("16:13 notohh: baby girl"))
.await;
.say_in_reply_to(
&params.msg,
String::from("16:13 notohh: baby girl"),
params.clone()
).await;
}
async fn routinelike(_bot: BotAR, msg: PrivmsgMessage) {
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(&msg),
Some(&params.msg),
);
// spawn an async block that runs independently from others

View file

@ -0,0 +1,194 @@
/*
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 std::sync::Arc;
use chrono::{TimeZone,Local};
use crate::core::bot_actions::ExecBodyParams;
use crate::core::botinstance::Channel;
use crate::core::botlog;
use casual_logger::Log;
use crate::core::bot_actions::actions_util;
use crate::core::botmodules::{BotActionTrait, BotCommand, BotModule, ModulesManager};
use crate::core::identity::UserRole::*;
pub async fn init(mgr: Arc<ModulesManager>) {
// 1. Define the BotAction
let botc1 = BotCommand {
module: BotModule(String::from("experiments002")),
command: String::from("say"), // command call name
alias: vec![
"s".to_string(),
], // String of alternative names
exec_body: actions_util::asyncbox(sayout),
help: String::from("Test Command tester"),
required_roles: vec![
BotAdmin,
// Mod(OF_CMD_CHANNEL),
VIP(OF_CMD_CHANNEL),
],
};
// 2. Add the BotAction to ModulesManager
botc1.add_to_modmgr(Arc::clone(&mgr)).await;
// If enabling by defauling at instance level , uncomment the following
// mgr.set_instance_enabled(BotModule(String::from("experiments002"))).await;
}
async fn sayout(params : ExecBodyParams) {
/*
usage :
<target channel> <message>
*/
let reply_parent = if let Some(Some(reply)) = params.msg.source.tags.0.get("reply-parent-msg-body") {
Some(reply)
} else { None }
;
let reply_parent_ts = if let Some(Some(replyts)) = params.msg.source.tags.0.get("tmi-sent-ts") {
let a: i64 = replyts.parse().unwrap();
let b = Local.timestamp_millis_opt(a).unwrap();
Some(b.format("%m-%d %H:%M"))
} else { None }
;
// [x] Unwraps arguments from message
let argrslt =
if let Some((_,str1)) = params.msg.message_text.split_once(' ') {
if reply_parent.is_none() {
if let Some((channelstr,msgstr)) = str1.split_once(' ') {
Some((channelstr,msgstr))
}
else { None }
} else if let Some((_,str2)) = str1.split_once(' ') {
if let Some((channelstr,msgstr)) = str2.split_once(' ') {
Some((channelstr,msgstr))
}
else { None }
} else { None }
}
else { None };
match argrslt {
Some((trgchnl,outmsg)) => {
let bot = Arc::clone(&params.bot);
let botlock = bot.read().await;
// [x] Validate first if trgchnl exists
botlog::trace(
&format!("[TRACE] Evaluated status of {} : {:?}",
trgchnl.to_string().clone(),botlock.botmgrs.chat.client.get_channel_status(trgchnl.to_string().clone()).await),
Some("Chat > send_botmsg".to_string()),
None,
);
/*
1. If a Reply ,
[ ] Get Parent Content message - reply_parent
[ ] Get Parent Chatter - reply_parent_usr
[ ] Get Parent Channel - msg.channel_login
-> Share this first then
[ ] Get Reply Message (that triggered bot command) - msgstr
[ ] Get Reply Sender - msg.sender.name
[ ] Get Target Channel - trgchnl
2. If not a reply
[ ] Get Reply Message (that triggered bot command) - msgstr
[ ] Get Reply Sender - msg.sender.name
[ ] Get Target Channel - trgchnl
*/
// reply_parent_ts
let newoutmsg = if let Some(srcmsg) = reply_parent {
format!("{} {} @ {} : {}",
reply_parent_ts.unwrap(),
params.msg.sender.name,
params.msg.channel_login,
srcmsg)
} else {
format!("in {} - {} : {}",
params.msg.channel_login,
params.msg.sender.name,
outmsg)
};
botlock
.botmgrs
.chat
.say(
trgchnl.to_string(),
newoutmsg.to_string(),
params.clone(),
).await;
},
None => {
botlog::debug(
"sayout had issues trying to parse arguments",
Some("experiment002 > sayout".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("Invalid arguments"),
params.clone()
).await;
},
}
Log::flush();
}

View file

@ -33,7 +33,11 @@ pub async fn main() {
for acts in (*actsdb_lock).values() {
for act in acts {
let outstr = match act {
let act_prelock = act;
let act = act_prelock.read().await;
let outstr = match &(*act) {
botmodules::BotAction::C(b) => {
format!("bot actions > Command : {}", b.command)
}