Merge branch 'master' into haru_test

This commit is contained in:
ModulatingForce 2024-04-09 12:56:21 -04:00
commit 35247ac5ba
22 changed files with 4665 additions and 883 deletions

4
.cargo/config.toml Normal file
View file

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

6
.gitignore vendored
View file

@ -23,3 +23,9 @@ target/
# debug
.vscode/
# nix
result/
# pre-commit
/.pre-commit-config.yaml

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,9 +12,13 @@ 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"
path = "src/lib.rs"

View file

@ -14,3 +14,10 @@ bot_channels = <chnl1>,<chnl2>
prefix = <prefix>
bot_admins = <admins>
```
2. If required, adjust the following additional `.cargo\config.toml` configurations :
```
[env]
OtherBots = # Other Bots for special handling (e.g., bot commands cant be ran by bots)
```

View file

@ -6,11 +6,11 @@
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
"lastModified": 1706768574,
"narHash": "sha256-4o6TMpzBHO659EiJTzd/EGQGUDdbgwKwhqf3u6b23U8=",
"lastModified": 1711952616,
"narHash": "sha256-WJvDdOph001fA1Ap3AyaQtz/afJAe7meSG5uJAdSE+A=",
"owner": "nix-community",
"repo": "fenix",
"rev": "668102037129923cd0fc239d864fce71eabdc6a3",
"rev": "209048d7c545905c470f6f8c05c5061f391031a8",
"type": "github"
},
"original": {
@ -20,13 +20,68 @@
"type": "github"
}
},
"flake-compat": {
"flake": false,
"locked": {
"lastModified": 1696426674,
"narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=",
"owner": "edolstra",
"repo": "flake-compat",
"rev": "0f9255e01c2351cc7d116c072cb317785dd33b33",
"type": "github"
},
"original": {
"owner": "edolstra",
"repo": "flake-compat",
"type": "github"
}
},
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1710146030,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"gitignore": {
"inputs": {
"nixpkgs": [
"pre-commit-hooks",
"nixpkgs"
]
},
"locked": {
"lastModified": 1709087332,
"narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=",
"owner": "hercules-ci",
"repo": "gitignore.nix",
"rev": "637db329424fd7e46cf4185293b9cc8c88c95394",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "gitignore.nix",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1706550542,
"narHash": "sha256-UcsnCG6wx++23yeER4Hg18CXWbgNpqNXcHIo5/1Y+hc=",
"lastModified": 1711703276,
"narHash": "sha256-iMUFArF0WCatKK6RzfUJknjem0H9m4KgorO/p3Dopkk=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "97b17f32362e475016f942bbdfda4a4a72a8a652",
"rev": "d8fe5e6c92d0d190646fb9f1056741a229980089",
"type": "github"
},
"original": {
@ -36,36 +91,92 @@
"type": "github"
}
},
"nixpkgs-stable": {
"locked": {
"lastModified": 1710695816,
"narHash": "sha256-3Eh7fhEID17pv9ZxrPwCLfqXnYP006RKzSs0JptsN84=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "614b4613980a522ba49f0d194531beddbb7220d3",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-23.11",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1708296515,
"narHash": "sha256-FyF489fYNAUy7b6dkYV6rGPyzp+4tThhr80KNAaF/yY=",
"owner": "nixos",
"lastModified": 1712573573,
"narHash": "sha256-xxon7WwNm4/EadMKg1eF40/5s0O78nXUy2ILZt6vT7E=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "b98a4e1746acceb92c509bc496ef3d0e5ad8d4aa",
"rev": "0d28066770464d19d637f6e8e42e8688420b6ac6",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_3": {
"locked": {
"lastModified": 1710765496,
"narHash": "sha256-p7ryWEeQfMwTB6E0wIUd5V2cFTgq+DRRBz2hYGnJZyA=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "e367f7a1fb93137af22a3908f00b9a35e2d286a7",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"pre-commit-hooks": {
"inputs": {
"flake-compat": "flake-compat",
"flake-utils": "flake-utils",
"gitignore": "gitignore",
"nixpkgs": "nixpkgs_3",
"nixpkgs-stable": "nixpkgs-stable"
},
"locked": {
"lastModified": 1712579741,
"narHash": "sha256-igpsH+pa6yFwYOdah3cFciCk8gw+ytniG9quf5f/q84=",
"owner": "cachix",
"repo": "pre-commit-hooks.nix",
"rev": "70f504012f0a132ac33e56988e1028d88a48855c",
"type": "github"
},
"original": {
"owner": "cachix",
"repo": "pre-commit-hooks.nix",
"type": "github"
}
},
"root": {
"inputs": {
"fenix": "fenix",
"nixpkgs": "nixpkgs_2"
"nixpkgs": "nixpkgs_2",
"pre-commit-hooks": "pre-commit-hooks",
"systems": "systems_2"
}
},
"rust-analyzer-src": {
"flake": false,
"locked": {
"lastModified": 1706735270,
"narHash": "sha256-IJk+UitcJsxzMQWm9pa1ZbJBriQ4ginXOlPyVq+Cu40=",
"lastModified": 1711885694,
"narHash": "sha256-dyezzeSbWMpflma+E9USmvSxuLgGcNGcGw3cOnX36ko=",
"owner": "rust-lang",
"repo": "rust-analyzer",
"rev": "42cb1a2bd79af321b0cc503d2960b73f34e2f92b",
"rev": "e4a405f877efd820bef9c0e77a02494e47c17512",
"type": "github"
},
"original": {
@ -74,6 +185,36 @@
"repo": "rust-analyzer",
"type": "github"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"systems_2": {
"locked": {
"lastModified": 1689347949,
"narHash": "sha256-12tWmuL2zgBgZkdoB6qXZsgJEH9LR3oUgpaQq2RbI80=",
"owner": "nix-systems",
"repo": "default-linux",
"rev": "31732fcf5e8fea42e59c2488ad31a0e651500f68",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default-linux",
"type": "github"
}
}
},
"root": "root",

View file

@ -1,39 +1,80 @@
{
description = "forcebot_rs flake";
description = "A basic flake";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
systems.url = "github:nix-systems/default-linux";
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
fenix.url = "github:nix-community/fenix/monthly";
pre-commit-hooks.url = "github:cachix/pre-commit-hooks.nix";
};
outputs = {
self,
systems,
nixpkgs,
fenix,
...
} @ inputs: let
system = "x86_64-linux";
overlays = [fenix.overlays.default];
pkgs = import nixpkgs {
inherit system overlays;
};
pre-commit-hooks,
}: let
eachSystem = nixpkgs.lib.genAttrs (import systems);
pkgsFor = eachSystem (system:
import nixpkgs {
localSystem.system = system;
overlays = [fenix.overlays.default];
});
in {
devShells.${system}.default = pkgs.mkShell {
name = "forcebot_rs-devenv";
nativeBuildInputs = [pkgs.pkg-config];
buildInputs = with pkgs; [openssl libiconv];
packages = with pkgs; [
nil
alejandra
rust-analyzer-nightly
(fenix.packages.${system}.complete.withComponents [
"cargo"
"clippy"
"rust-src"
"rustc"
"rustfmt"
])
];
RUST_BACKTRACE = 1;
RUST_SRC_PATH = "${fenix.packages.${system}.complete.rust-src}/lib/rustlib/src/rust/library";
};
packages = eachSystem (system: let
pkgs = nixpkgs.legacyPackages.${system};
inherit ((builtins.fromTOML (builtins.readFile ./Cargo.toml)).package) version;
in {
default = pkgsFor.${system}.rustPlatform.buildRustPackage {
pname = "forcebot_rs";
version = "${version}";
src = self;
cargoLock = {
lockFile = ./Cargo.lock;
};
nativeBuildInputs = with pkgs; [pkg-config];
buildInputs = with pkgs; [openssl];
doCheck = false;
};
});
checks = eachSystem (system: {
pre-commit-check = pre-commit-hooks.lib.${system}.run {
src = ./.;
hooks = {
# rust
rustfmt.enable = true;
clippy.enable = true;
# nix
statix.enable = true;
alejandra.enable = true;
deadnix.enable = true;
};
};
});
devShells = eachSystem (system: {
default = pkgsFor.${system}.mkShell {
inherit (self.checks.${system}.pre-commit-check) shellHook;
packages = with pkgsFor.${system}; [
nil
alejandra
rust-analyzer-nightly
(fenix.packages.${system}.complete.withComponents [
"cargo"
"clippy"
"rust-src"
"rustc"
"rustfmt"
])
];
RUST_BACKTRACE = 1;
RUST_SRC_PATH = "${fenix.packages.${system}.complete.rust-src}/lib/rustlib/src/rust/library";
};
});
nixosModules.default = import ./nix/module.nix {inherit self;};
};
}

30
nix/module.nix Normal file
View file

@ -0,0 +1,30 @@
{self}: {
pkgs,
config,
lib,
...
}: let
inherit (lib) types;
inherit (lib.modules) mkIf;
inherit (lib.options) mkOption mkEnableOption;
inherit (pkgs.stdenv.hostPlatform) system;
cfg = config.services.forcebot_rs;
in {
options.services.forcebot_rs = {
enable = mkEnableOption ''
Enable forcebot
'';
package = mkOption {
type = types.package;
inherit (self.packages.${system}) default;
};
};
config = mkIf cfg.enable {
systemd.services.forcebot_rs = {
wantedBy = ["multi-user.target"];
serviceConfig.ExecStart = "${cfg.package}/bin/forcebot_rs";
};
};
}

View file

@ -1,27 +1,141 @@
use twitch_irc::message::{PrivmsgMessage, TwitchUserBasics};
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
}
/// Returns some information about the message that was replied to by the `PrivmsgMessage` contained
/// in the `msg` field of this struct.
///
/// If that message replied to message return that information in form of `Some<ReplyParent>`.
/// Otherwise, return `None`.
pub fn get_parent_reply(&self) -> Option<ReplyParent> {
let map = &self.msg.source.tags.0;
let tags = [
"reply-parent-user-id",
"reply-parent-user-login",
"reply-parent-display-name",
"reply-parent-msg-id",
"reply-parent-msg-body"
];
// filter out all tags that do not have content.
let tag_contents: Vec<String> = tags.iter().filter_map(|tag| {
// if let Some(&Some(ref t)) = map.get(*tag) {
if let Some(Some(t)) = map.get(*tag) {
Some(t.clone())
} else {
None
}
}).collect();
// if no tags got filtered out return the struct.
// else return `None`.
if tag_contents.len() == 5 {
Some(ReplyParent {
sender: TwitchUserBasics {
id: tag_contents[0].clone(),
login: tag_contents[1].clone(),
name: tag_contents[2].clone(),
},
message_id: tag_contents[3].clone(),
message_text: tag_contents[4].clone(),
channel_login: self.msg.channel_login.clone(),
channel_id: self.msg.channel_id.clone(),
})
} else {
None
}
}
}
/// Represents the message a `PrivmsgMessage` replies to.
/// Similar to a less detailed `PrivmsgMessage`.
///
/// This should not be constructed manually but only from calling `get_parent_reply()` on
/// `ExecBodyParams`.
///
/// Fields that will be the same as the `PrivmsgMessage` this was generated from:
/// - `channel_login`
/// - `channel_id`
#[derive(Debug, Clone, PartialEq)]
pub struct ReplyParent {
pub sender: TwitchUserBasics,
pub message_id: String,
pub message_text: String,
pub channel_login: String,
pub channel_id: String,
}
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

@ -4,6 +4,7 @@ use std::sync::Arc;
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::{Mutex, RwLock};
use tokio::time::{sleep, Duration};
use twitch_irc::login::StaticLoginCredentials;
use twitch_irc::message::{PrivmsgMessage, ServerMessage};
@ -16,19 +17,28 @@ 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::{ChangeResult, IdentityManager, Permissible};
use crate::core::identity::{IdentityManager, Permissible};
use crate::core::botlog;
use crate::core::chat::Chat;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum ChType {
Channel(String),
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ChangeResult {
Success(String),
Failed(String),
NoChange(String),
}
pub use ChType::Channel;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct Channel(pub String);
use super::bot_actions::ExecBodyParams;
use super::botmodules::StatusType;
#[derive(Clone)]
pub struct BotManagers {
@ -38,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 {
@ -62,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
}
@ -109,6 +119,19 @@ impl BotInstance {
ratelimiters.insert(Channel(String::from(chnl)), n);
}
tokio::spawn(async {
loop {
let routine_mins = 60 * 24 ; // Every 1 Day
// let routine_mins = 1; // Every 1 Minute
Log::remove_old_logs();
Log::info(&format!("Internal Purge Routine Triggered - running every {} mins",routine_mins));
Log::flush();
sleep(Duration::from_secs(60 * routine_mins)).await
}
});
BotInstance {
prefix,
bot_channel: Channel(login_name),
@ -130,6 +153,19 @@ impl BotInstance {
let mut msglock = botlock.incoming_messages.write().await;
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(
@ -138,8 +174,10 @@ impl BotInstance {
Some("BotInstance > runner()".to_string()),
None,
);
Log::flush();
}
ServerMessage::Privmsg(msg) => {
botlog::debug(
format!(
"[Twitch Chat > {}] > {}: {}",
@ -150,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) => {
@ -158,6 +208,7 @@ impl BotInstance {
Some("BotInstance > runner()".to_string()),
None,
);
Log::flush();
}
ServerMessage::Join(msg) => {
botlog::notice(
@ -165,6 +216,7 @@ impl BotInstance {
Some("BotInstance > runner()".to_string()),
None,
);
Log::flush();
}
ServerMessage::Part(msg) => {
botlog::notice(
@ -172,6 +224,7 @@ impl BotInstance {
Some("BotInstance > runner()".to_string()),
None,
);
Log::flush();
}
_ => {}
};
@ -202,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;
@ -212,14 +301,20 @@ 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 -
- [x] Checks if the input message is a prefix with command name or alias
- [ ] Validate User can run based on identityModule(From_Bot)::can_user_run(
- [x] Validate User can run based on identityModule(From_Bot)::can_user_run(
_usr:String,
_channelname:ChType,
_chat_badge:ChatBadge,
@ -232,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
@ -268,6 +359,72 @@ impl BotInstance {
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(
c.module.clone(),
Channel(msg.channel_login.to_string())).await;
if let StatusType::Disabled(a) = modstatus {
// [x] Should only respond if a BotAdmin , Mod , SupMod , BroadCaster
// - Specifically it should respond only to those who may be able to enable the module
botlog::trace(
&format!("Identified cmd is associated with Disabled Module : StatusLvl = {:?}", a),
Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(msg),
);
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;
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),
};
// 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 = {
let mut idlock = id.write().await;
let (permissability, chngrslt) = idlock
@ -299,25 +456,72 @@ 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;
}
}
match eval {
Permissible::Allow => {
botlog::debug(
"Executed as permissible",
"Executing as permissible",
Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(msg),
);
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),
);
}
@ -334,8 +538,36 @@ impl BotInstance {
}
crate::core::botmodules::BotAction::L(l) => {
let a = Arc::clone(&bot);
l.execute(a, msg.clone()).await;
let botlock = bot.read().await;
// [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(),
Channel(msg.channel_login.to_string())).await;
if let StatusType::Disabled(a) = modstatus {
// [x] Should only respond if a BotAdmin , Mod , SupMod , BroadCaster
// - Specifically it should respond only to those who may be able to enable the module
botlog::trace(
&format!("Identified listener is associated with Disabled Module : StatusLvl = {:?}", a),
Some("BotInstance > listener_main_prvmsg()".to_string()),
Some(msg),
);
} else {
let a = Arc::clone(&bot);
l.execute(ExecBodyParams {
bot : a,
msg : msg.clone() ,
parent_act : Arc::clone(&act_clone),
} ).await;
}
}
_ => (),

View file

@ -24,11 +24,10 @@ debug = "Checking bot actions",
pub fn trace(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgMessage>) {
let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(
Some(prvmsg.channel_login.clone()),
Some(prvmsg.sender.name.clone()),
) // <-- Clone fine atm while we're just working with Strings
)
}
None => (None, None),
};
@ -45,11 +44,10 @@ pub fn trace(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&Privmsg
pub fn debug(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgMessage>) {
let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(
Some(prvmsg.channel_login.clone()),
Some(prvmsg.sender.name.clone()),
) // <-- Clone fine atm while we're just working with Strings
)
}
None => (None, None),
};
@ -66,11 +64,10 @@ pub fn debug(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&Privmsg
pub fn info(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgMessage>) {
let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(
Some(prvmsg.channel_login.clone()),
Some(prvmsg.sender.name.clone()),
) // <-- Clone fine atm while we're just working with Strings
)
}
None => (None, None),
};
@ -87,11 +84,10 @@ pub fn info(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgM
pub fn notice(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgMessage>) {
let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(
Some(prvmsg.channel_login.clone()),
Some(prvmsg.sender.name.clone()),
) // <-- Clone fine atm while we're just working with Strings
)
}
None => (None, None),
};
@ -108,11 +104,10 @@ pub fn notice(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&Privms
pub fn warn(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgMessage>) {
let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(
Some(prvmsg.channel_login.clone()),
Some(prvmsg.sender.name.clone()),
) // <-- Clone fine atm while we're just working with Strings
)
}
None => (None, None),
};
@ -129,11 +124,10 @@ pub fn warn(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgM
pub fn error(in_msg: &str, in_module: Option<String>, in_prvmsg: Option<&PrivmsgMessage>) {
let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(
Some(prvmsg.channel_login.clone()),
Some(prvmsg.sender.name.clone()),
) // <-- Clone fine atm while we're just working with Strings
)
}
None => (None, None),
};
@ -154,11 +148,10 @@ pub fn fatal<'a>(
) -> &'a str {
let (chnl, chatter) = match in_prvmsg {
Some(prvmsg) => {
//Log::trace(&format!("(#{}) {}: {}", prvmsg.channel_login, prvmsg.sender.name, prvmsg.message_text));
(
Some(prvmsg.channel_login.clone()),
Some(prvmsg.sender.name.clone()),
) // <-- Clone fine atm while we're just working with Strings
)
}
None => (None, None),
};

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@ use std::sync::Arc;
use tokio::sync::Mutex;
use twitch_irc::login::StaticLoginCredentials;
use twitch_irc::message::PrivmsgMessage;
use twitch_irc::message::ReplyToMessage;
use twitch_irc::transport::tcp::{TCPTransport, TLS};
use twitch_irc::TwitchIRCClient;
@ -15,19 +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 {
SayInReplyTo(Channel,String,String), // ( Destination Channel , Message ID to reply to , OutMessage ) // https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say_in_reply_to
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 {
@ -36,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, params : ExecBodyParams) {
/*
formats message before sending to TwitchIRC
@ -51,14 +72,265 @@ 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(chnl, _, outmsg) => {
(chnl.0.to_lowercase(), // Desintation Channel
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())) {
dbg!("ISSUE : NONJOINED CHANNEL",&params.bot.read().await.bot_channels,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(_chnl,_msgid, _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;
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
while let ratelimiter::LimiterResp::Sleep(sleeptime) = contextratelimiter.check_limiter() {
sleep(Duration::from_secs_f64(sleeptime)).await;
}
match contextratelimiter.check_limiter() {
ratelimiter::LimiterResp::Allow => {
let maxblanks = rand::thread_rng().gen_range(1..=20);
@ -68,34 +340,106 @@ impl Chat {
outmsg.push_str(blankspace);
}
self.client.say_in_reply_to(msg, outmsg).await.unwrap();
match msginput.clone() {
BotMsgType::SayInReplyTo(chnl,msgid, _) => {
dbg!(chnl.clone(),msgid.clone(),outmsg.clone());
self.client.say_in_reply_to(&(
chnl.0,
msgid),
outmsg).await.unwrap();
},
BotMsgType::Say(a, _) => {
self.client.say(a, outmsg).await.unwrap();
}
BotMsgType::Notif(outmsg) => {
dbg!(params.msg.channel_login(),params.msg.message_id());
self.client.say_in_reply_to(&params.msg, outmsg).await.unwrap();
}
}
contextratelimiter.increment_counter();
let logstr = format!(
"(#{}) > {} ; Ratelimiers : {:?}",
msg.channel_login, "rate limit counter increase", self.ratelimiters
"(#{}) > {} ; 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(_,_,_ ) = msginput {
botlog::trace(
logstr.as_str(),
Some("Chat > send_botmsg".to_string()),
None,
);
} else {
botlog::trace(
logstr.as_str(),
Some("Chat > send_botmsg".to_string()),
None,
);
}
}
ratelimiter::LimiterResp::Skip => {
// (); // do nothing otherwise
}
ratelimiter::LimiterResp::Sleep(_) => {
panic!("ISSUE : sleep was already awaited - Should not happen?");
}
}
Log::flush();
Log::flush();
}
async fn _say(&self, _: String, _: String) {
pub async fn say_in_reply(
&self,
destination_channel : Channel ,
outmsg: String ,
params : ExecBodyParams)
{
self.send_botmsg(BotMsgType::SayInReplyTo(
destination_channel,
params.msg.message_id().to_string(),
outmsg) , params).await;
}
pub async fn say_in_reply_to(
&self,
destination_channel : Channel ,
reply_message_id : String ,
outmsg: String ,
params : ExecBodyParams)
{
self.send_botmsg(BotMsgType::SayInReplyTo(
destination_channel,
reply_message_id,
outmsg) , params).await;
}
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) {
// more info https://docs.rs/twitch-irc/latest/twitch_irc/client/struct.TwitchIRCClient.html#method.say

File diff suppressed because it is too large Load diff

View file

@ -1,18 +1,23 @@
const TIME_THRESHOLD_S: u64 = 30;
const TIME_MIN_S_F64: f64 = 1.0;
const MSG_THRESHOLD: u32 = 20;
use std::time::Instant;
use crate::core::botlog;
#[derive(Debug, Clone)]
pub struct RateLimiter {
timer: Instant,
msgcounter: u32,
lastmsgtimer : Instant,
}
#[derive(Debug)]
pub enum LimiterResp {
Allow, // when it's evaluated to be within limits
Skip, // as outside of rate limits
// Enqueue, // [FUTURE]
Sleep(f64), // Sleep for x seconds
}
impl Default for RateLimiter {
@ -26,23 +31,50 @@ impl RateLimiter {
Self {
timer: Instant::now(),
msgcounter: 0,
lastmsgtimer: Instant::now(),
}
}
pub fn check_limiter(&mut self) -> LimiterResp {
if self.timer.elapsed().as_secs() >= TIME_THRESHOLD_S {
let logstr = format!(
">> RateLimiter > {:?}",self
);
botlog::trace(
logstr.as_str(),
Some("Rate Limiter Inner".to_string()),
None,
);
let rsp = if self.timer.elapsed().as_secs() >= TIME_THRESHOLD_S {
self.timer = Instant::now();
self.msgcounter = 0;
LimiterResp::Allow
} else if self.msgcounter < MSG_THRESHOLD {
} else if self.msgcounter < MSG_THRESHOLD &&
self.lastmsgtimer.elapsed().as_secs_f64() >= TIME_MIN_S_F64 {
LimiterResp::Allow
} else {
// when elapsed() < TIME_THRESHOLD_S && msgcounter >= MSG_THRESHOLD
LimiterResp::Skip
}
// LimiterResp::Skip
LimiterResp::Sleep(TIME_MIN_S_F64 - self.lastmsgtimer.elapsed().as_secs_f64() + 0.1)
};
botlog::trace(
&format!("Limiter Response : {:?} ; Elapsed (as_sec_f64) : {}",
rsp, self.lastmsgtimer.elapsed().as_secs_f64()),
Some("Rate Limiter Inner".to_string()),
None,
);
rsp
}
pub fn increment_counter(&mut self) {
self.msgcounter += 1;
self.lastmsgtimer = Instant::now();
}
}

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

@ -0,0 +1,288 @@
/*
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 rand::Rng;
use twitch_irc::message::ReplyToMessage;
use std::sync::Arc;
use crate::core::bot_actions::ExecBodyParams;
use crate::core::botinstance::Channel;
use crate::core::botlog;
use crate::core::bot_actions::actions_util;
use crate::core::botmodules::{BotActionTrait, BotCommand, BotModule, Listener, ModulesManager};
use crate::core::identity::UserRole::*;
use tokio::time::{sleep, Duration};
pub async fn init(mgr: Arc<ModulesManager>) {
// 1. Define the BotAction
let botc1 = BotCommand {
module: BotModule(String::from("experiments001")),
command: String::from("test1"), // command call name
alias: vec![
String::from("tester1"),
String::from("testy1")], // String of alternative names
exec_body: actions_util::asyncbox(testy),
help: String::from("Test Command tester"),
required_roles: vec![
BotAdmin,
Mod(OF_CMD_CHANNEL),
],
};
// 2. Add the BotAction to ModulesManager
botc1.add_to_modmgr(Arc::clone(&mgr)).await;
// 1. Define the BotAction
let list1 = Listener {
module: BotModule(String::from("experiments001")),
name: String::from("GoodGirl Listener"),
exec_body: actions_util::asyncbox(good_girl),
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")),
command: String::from("babygirl"), // command call name
alias: vec![], // String of alternative names
exec_body: actions_util::asyncbox(babygirl),
help: String::from("Babygirl"),
required_roles: vec![
BotAdmin,
// Mod(OF_CMD_CHANNEL),
Broadcaster,
],
};
// 2. Add the BotAction to ModulesManager
botc1.add_to_modmgr(Arc::clone(&mgr)).await;
// 1. Define the BotAction
let botc1 = BotCommand {
module: BotModule(String::from("experiments001")),
command: String::from("rtest"), // command call name
alias: vec![], // String of alternative names
exec_body: actions_util::asyncbox(routinelike),
help: String::from("routinelike"),
required_roles: vec![
BotAdmin,
// Mod(OF_CMD_CHANNEL),
//Broadcaster,
],
};
// 2. Add the BotAction to ModulesManager
botc1.add_to_modmgr(Arc::clone(&mgr)).await;
let bc1 = BotCommand {
module: BotModule(String::from("experiments001")),
command: String::from("rp1"), // command call name
alias: vec![
String::from("rp2"),
String::from("rp3")], // String of alternative names
exec_body: actions_util::asyncbox(rp),
help: String::from("Test Command tester"),
required_roles: vec![
BotAdmin,
Mod(OF_CMD_CHANNEL),
],
};
bc1.add_core_to_modmgr(Arc::clone(&mgr)).await;
}
async fn rp(params : ExecBodyParams)
{
//triggers if the message is a reply
if params.get_parent_reply().is_some(){
//getting the channel id where the message was sent
let channel_id = params.get_parent_reply().unwrap().channel_login;
//getting the first message id that was sent
let message_id = params.get_parent_reply().unwrap().message_id;
//just for testing purposes
//print!("{} , {}",channel_id, message_id);
//creating a tuple with the channel id and message id
let answear =
(
channel_id.clone(),
message_id.clone()
);
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(
//using the tuple as param to the message being replied
Channel(answear.0),
answear.1,
String::from("hey there"),
params.clone()
).await;
}
else
{
println!("no reply")
}
}
async fn good_girl(params : ExecBodyParams) {
// [ ] Uses gen_ratio() to output bool based on a ratio probability .
// - For example gen_ratio(2,3) is 2 out of 3 or 0.67% (numerator,denomitator)
// - More Info : https://rust-random.github.io/rand/rand/trait.Rng.html#method.gen_ratio
if params.msg.sender.name.to_lowercase() == "ModulatingForce".to_lowercase()
|| params.msg.sender.name.to_lowercase() == "mzNToRi".to_lowercase()
{
botlog::debug(
"Good Girl Detected > Pausechamp",
Some("experiments > goodgirl()".to_string()),
Some(&params.msg),
);
let rollwin = rand::thread_rng().gen_ratio(1, 10);
if rollwin {
botlog::debug(
"Oh that's a good girl!",
Some("experiments > goodgirl()".to_string()),
Some(&params.msg),
);
let bot = Arc::clone(&params.bot);
let botlock = bot.read().await;
// uses chat.say_in_reply_to() for the bot controls for messages
botlock
.botmgrs
.chat
.say_in_reply_to(
Channel(params.clone().msg.channel_login().to_string()),
params.clone().msg.message_id().to_string(),
String::from("GoodGirl xdd "),
params.clone()
).await;
}
}
}
async fn testy(params : ExecBodyParams) {
println!("testy triggered!"); // NOTE : This test function intends to print (e.g., to stdout) at fn call
botlog::debug(
"testy triggered!",
Some("experiments > testy()".to_string()),
Some(&params.msg),
);
}
async fn babygirl(params : ExecBodyParams) {
println!("babygirl triggered!"); // NOTE : This test function intends to print (e.g., to stdout) at fn call
botlog::debug(
"babygirl triggered!",
Some("experiments > babygirl()".to_string()),
Some(&params.msg),
);
let bot = Arc::clone(&params.bot);
let botlock = bot.read().await;
botlock
.botmgrs
.chat
.say_in_reply(
Channel(params.clone().msg.channel_login().to_string()),
String::from("16:13 notohh: cafdk"),
params.clone()
).await;
sleep(Duration::from_secs_f64(0.5)).await;
botlock
.botmgrs
.chat
.say_in_reply(
Channel(params.clone().msg.channel_login().to_string()),
String::from("16:13 notohh: have fun eating princess"),
params.clone()
).await;
sleep(Duration::from_secs_f64(2.0)).await;
botlock
.botmgrs
.chat
.say_in_reply(
Channel(params.clone().msg.channel_login().to_string()),
String::from("16:13 notohh: baby girl"),
params.clone()
).await;
}
async fn routinelike(params : ExecBodyParams) {
println!("routinelike triggered!"); // NOTE : This test function intends to print (e.g., to stdout) at fn call
botlog::debug(
"routinelike triggered!",
Some("experiments > routinelike()".to_string()),
Some(&params.msg),
);
// spawn an async block that runs independently from others
tokio::spawn( async {
for _ in 0..5 {
println!(">> Innterroutine triggered!");
sleep(Duration::from_secs_f64(5.0)).await;
}
}
);
// lines are executed after in conjunction to the spawn
}

View file

@ -0,0 +1,196 @@
/*
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 twitch_irc::message::ReplyToMessage;
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(
Channel(params.clone().msg.channel_login().to_string()),
params.clone().msg.message_id().to_string(),
String::from("Invalid arguments"),
params.clone()
).await;
},
}
Log::flush();
}

View file

@ -1,106 +0,0 @@
/*
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
*/
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::botlog;
use crate::core::bot_actions::actions_util::{self, BotAR};
use crate::core::botmodules::{BotActionTrait, BotCommand, BotModule, Listener, ModulesManager};
use crate::core::identity::UserRole::*;
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")),
command: String::from("test1"), // command call name
alias: vec![
String::from("tester1"),
String::from("testy1")], // String of alternative names
exec_body: actions_util::asyncbox(testy),
help: String::from("Test Command tester"),
required_roles: vec![
BotAdmin,
Mod(OF_CMD_CHANNEL),
],
};
// 2. Add the BotAction to ModulesManager
botc1.add_to_modmgr(Arc::clone(&mgr)).await;
// 1. Define the BotAction
let list1 = Listener {
module: BotModule(String::from("experiments001")),
name: String::from("GoodGirl Listener"),
exec_body: actions_util::asyncbox(good_girl),
help: String::from(""),
};
// 2. Add the BotAction to ModulesManager
list1.add_to_modmgr(Arc::clone(&mgr)).await;
}
async fn good_girl(bot: BotAR, msg: PrivmsgMessage) {
// [ ] 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()
{
botlog::debug(
"Good Girl Detected > Pausechamp",
Some("experiments > goodgirl()".to_string()),
Some(&msg),
);
let rollwin = rand::thread_rng().gen_ratio(1, 8);
if rollwin {
botlog::debug(
"Oh that's a good girl!",
Some("experiments > goodgirl()".to_string()),
Some(&msg),
);
let bot = Arc::clone(&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;
}
}
}
async fn testy(mut _chat: BotAR, msg: PrivmsgMessage) {
println!("testy triggered!"); // NOTE : This test function intends to print (e.g., to stdout) at fn call
botlog::debug(
"testy triggered!",
Some("experiments > testy()".to_string()),
Some(&msg),
);
}

View file

@ -10,13 +10,19 @@ use bot_lib::core::botmodules;
pub type BotAR = Arc<RwLock<BotInstance>>;
// God I love anime girls
// fr fr
#[tokio::main]
pub async fn main() {
Log::set_file_ext(Extension::Log);
Log::set_level(Level::Trace);
Log::set_retention_days(2);
// Log::set_level(Level::Notice);
let bot = BotInstance::init().await;
{
@ -27,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)
}
@ -52,3 +62,6 @@ pub async fn main() {
let pstr = botlog::fatal("ERROR : EXIT Game loop", Some("main()".to_string()), None);
panic!("{}", pstr);
}

3
statix.toml Normal file
View file

@ -0,0 +1,3 @@
disabled = []
nix_version = '2.4'
ignore = ['.direnv']