Compare commits

..

138 commits

Author SHA1 Message Date
e1021c269d Merge pull request 'Custom this BotCommand' (#48) from say-this-guy into master
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
Reviewed-on: #48
2024-04-09 15:49:58 -04:00
e41f7b0524 warning changed
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-04-09 16:44:58 -03:00
55aeaa7fc1 changed reply message on thisguy
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-04-09 16:22:11 -03:00
93768de4dc Merge branch 'master' into say-this-guy
Some checks failed
ci/woodpecker/pr/cargo-checks Pipeline failed
2024-04-09 14:45:27 -04:00
b8c33d2339 Merge pull request 'Bot admins in env file' (#22) from haru_test into master
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
Reviewed-on: #22
2024-04-09 13:48:55 -04:00
7f49693a94 clippy
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-04-09 13:47:06 -04:00
b949c70fa8 Merge branch 'master' into haru_test
Some checks failed
ci/woodpecker/pr/cargo-checks Pipeline failed
2024-04-09 13:39:57 -04:00
018e8306e4 Merge pull request 'Cucked alt for promote' (#75) from cucked into master
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
Reviewed-on: #75
2024-04-09 13:39:35 -04:00
764a912122 Merge branch 'master' into cucked
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-04-09 13:37:20 -04:00
f86f48178d
ci: fix branch naming 2024-04-09 13:27:25 -04:00
35247ac5ba Merge branch 'master' into haru_test 2024-04-09 12:56:21 -04:00
4b849cfed6 comments cleanup 2024-04-09 12:51:53 -04:00
dfb37717b3 clippy 2024-04-09 12:36:46 -04:00
16c6b0eebb self-invoking identity methods 2024-04-09 12:32:02 -04:00
74d938751f cucked promote alt 2024-04-09 10:00:01 -04:00
2bf0e0e738 Merge pull request 'flake.lock: update' (#74) from flake-lock-update into master
Reviewed-on: #74
2024-04-09 08:47:36 -04:00
dd2670c766 flake.lock: update 2024-04-09 01:02:55 +00:00
200d2a86d3
nix: add pre-commit-hooks
Some checks failed
ci/woodpecker/pr/cargo-checks Pipeline was successful
ci/woodpecker/cron/flake-update Pipeline failed
2024-04-08 18:45:30 -04:00
926f213923 Merge pull request 'nix-rewrite' (#73) from nix-rewrite into main
good enough for now
2024-04-08 18:05:05 -04:00
604c26647e
nix: read version from cargo.toml
fix spelling error
2024-04-08 18:00:13 -04:00
087e76388d
nix: init rewrite
first pass of my nix rewrite

nix: rename module

nix: update module

nix: update module

nix: update module

nix: refactor

nix: remove package option

nix: fix serviceConfig

nix: add package back to module

nix: update module

nix: update module

nix: update module

nix: update module

remove default.nix
2024-04-08 17:46:08 -04:00
91d62bf0ff Merge pull request 'flake.lock: update' (#72) from flake-lock-update into main
Reviewed-on: #72
2024-04-08 10:00:55 -04:00
78634f3ffe flake.lock: update 2024-04-08 13:59:49 +00:00
e67c8582c1 Merge pull request 'Retrieve Reply information from ExecBodyParams' (#52) from retrieve-reply-details into main
Some checks failed
ci/woodpecker/push/cargo-checks Pipeline was successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
ci/woodpecker/cron/flake-update Pipeline failed
Reviewed-on: #52
2024-04-03 19:51:04 -04:00
fde96ac895 clippy cleanup
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-04-03 19:45:18 -04:00
8adab21761 comments cleanup 2024-04-03 19:40:18 -04:00
62b6399e69 chat.say_in_reply 2024-04-03 19:04:21 -04:00
6867cc7af8 adj sayinreply to use channel & msgid
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-04-03 18:33:15 -04:00
7199703766 reply-to-parent working
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-04-03 15:26:04 -03:00
345cf97922 enh chat.say_in_reply
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-04-03 13:47:59 -04:00
57725ee840 Merge branch 'retrieve-reply-details' of https://git.flake.sh/modulatingforce/forcebot_rs into retrieve-reply-details 2024-04-03 12:54:52 -04:00
b43d6f8159 Rewriten the code
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
working with command instead listener
2024-04-03 10:26:14 -03:00
7e04699b67 making changes 2024-04-03 10:25:24 -03:00
d972eb7726 Thisguy working partially
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
not fully implemented reply to the reply
2024-04-02 20:11:01 -03:00
72d4cf6d70 Small changes on thisguy.rs 2024-03-31 14:37:50 -03:00
a048003e93 oops forgot to add the use statement
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-30 01:47:32 +01:00
f2893791b9 add reply parent functionality
Some checks failed
ci/woodpecker/pr/cargo-checks Pipeline failed
2024-03-30 01:42:06 +01:00
a6ae5b3c47 Merge branch 'say-this-guy' of ssh://git.flake.sh:2222/modulatingforce/forcebot_rs into say-this-guy
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-28 19:35:25 -03:00
fda7afb191 custom module working 2024-03-28 19:33:06 -03:00
40aa836b24 Merge branch 'main' of https://git.flake.sh/modulatingforce/forcebot_rs 2024-03-28 17:56:56 -04:00
3ec51d66e5 Merge branch 'main' into say-this-guy
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-28 17:55:00 -04:00
f8de595290 custom module update
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-28 18:50:28 -03:00
d7634663fe Merge pull request 'Fix Logs Flushing only every 60 days' (#50) from fix-log-purge-timer into main
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
Reviewed-on: #50
2024-03-28 16:05:44 -04:00
mzntori
6a026b7791 reduce seconds to minutes
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-28 20:12:51 +01:00
95a9962721 new module test
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
trying to add a new module
2024-03-28 15:38:49 -03:00
34c3c8af7a Merge branch 'main' into routines-functionality
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-25 23:26:46 -04:00
b9227cc72b Merge pull request 'Recognize VIP badge as Special Roles' (#44) from vip-badge into main
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
Reviewed-on: #44
2024-03-25 22:38:02 -04:00
de2ef03661 clippy & comments cleanup
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-25 21:50:39 -04:00
feff709714 unit tests
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-25 21:40:35 -04:00
e66985814a promote/demote checks invalid arg flag
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-25 20:24:05 -04:00
df6fe8ccb7 refined promote/demote 2024-03-25 20:11:50 -04:00
acfcae975e moved demote promote
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-25 19:36:45 -04:00
a6628a62a4 demote/promote vip 2024-03-25 19:33:24 -04:00
38e7060d86 auto VIP 2024-03-25 17:46:57 -04:00
1129e0d28a recognizes VIP badge 2024-03-25 17:01:36 -04:00
847d790513 Merge branch 'main' into vip-badge
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-25 16:33:00 -04:00
befb742b81 Merge pull request 'Exec Body Fn should be passed Parent BotAction' (#43) from parent-botaction-to-child-fn into main
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
Reviewed-on: #43
2024-03-25 16:29:44 -04:00
6912708cfb comments cleanup
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-25 16:18:57 -04:00
f582c36f97 clippy 2024-03-25 15:46:37 -04:00
d746d0d073 custom does not req parent_module validation before say
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-25 14:15:14 -04:00
628db3c229 refactor core to use Notif msg 2024-03-25 14:11:21 -04:00
c0603739c9 Notifs only sent for BotAdmins 2024-03-25 11:55:16 -04:00
10d25bf34f notif BotMsgType
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-25 10:07:34 -04:00
246c3d98e6 smol 2024-03-25 09:30:15 -04:00
35db264b9e Merge pull request 'writelock_issue' (#45) from issue-chat-say-id-write-lock into parent-botaction-to-child-fn
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
Reviewed-on: #45
2024-03-24 23:44:24 -04:00
8b3395c19a smol 2024-03-24 23:42:59 -04:00
cfadd73096 readlock fix 2024-03-24 23:27:21 -04:00
ab5624c6fa (init) solution 2024-03-24 22:55:38 -04:00
afd7b7d387 writelock_issue 2024-03-24 21:50:28 -04:00
6deac8e6c7 chat.send validates target channel module status
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-24 18:51:34 -04:00
958aeea48e execbodyparams passed to chat() 2024-03-24 18:14:08 -04:00
0eb43c87f2 ExecBodyParams get_parent_module() 2024-03-24 17:40:57 -04:00
ee0b9ee196 (init) say require parent module 2024-03-24 16:59:50 -04:00
7e5e43fec3 parentact to ExecBodyParams 2024-03-24 15:46:08 -04:00
203f6af869 ExecBodyParams 2024-03-24 14:38:09 -04:00
616d1f564f reorg botactions.rs 2024-03-24 14:09:08 -04:00
c0e6bcc566 Merge pull request 'Chat say functionality' (#41) from chat-say into main
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
Reviewed-on: #41
2024-03-24 00:00:47 -04:00
97d76ea088 added ts to experiment
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-23 22:40:06 -04:00
e4a44894d7 clippy cleanup
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
clippy cleanup
2024-03-23 20:33:10 -04:00
d372d0dc79 comments cleanup 2024-03-23 20:14:42 -04:00
098f16ce87 say channel case insensitive
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-23 20:06:45 -04:00
30a3e2af00 comments cleanup 2024-03-23 19:39:36 -04:00
22b2ec746a smol adj 2024-03-23 19:37:43 -04:00
0e12cd1bff experiments module 2024-03-23 19:20:43 -04:00
7e59b8b251 say chnl must be valid 2024-03-23 18:33:33 -04:00
ff6046bb1f botcommands recognized in replies 2024-03-23 18:04:57 -04:00
4613d69e3f smol 2024-03-23 16:58:46 -04:00
bd4ae150bb Merge branch 'main' into chat-say 2024-03-23 16:54:23 -04:00
e104268f8e Merge pull request 'Simplify enum objects' (#39) from Simplify-objects into main
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
Reviewed-on: #39
2024-03-23 16:50:03 -04:00
3a0e00c323 comments cleanup
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-23 16:45:12 -04:00
9a3d0aacda adj off construct
adj off construct
2024-03-23 16:39:06 -04:00
0f1cb576a4 reworked broadcaster check in identity 2024-03-23 16:37:39 -04:00
bed61c2830 pub struct changes
look into error at identity:1333
2024-03-23 16:37:39 -04:00
960cd5724c Simplifying enums
I hope this doesn't explode everything Prayge
2024-03-23 16:36:25 -04:00
5802e9b755 experimental say functionality
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-23 13:32:22 -04:00
b8bf2e33f6 added say to Chat 2024-03-23 12:21:08 -04:00
2957f9462b reorg common say logic 2024-03-23 12:14:51 -04:00
45e3f02297 Merge pull request 'ModulesManager' (#37) from modulesmanager into main
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
Reviewed-on: #37
2024-03-22 21:34:07 -04:00
72ebd5193c comments cleanup
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-22 21:06:15 -04:00
06e182df55 clippy adj
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-22 20:18:02 -04:00
4b0d51a674 listener modules validated
Some checks failed
ci/woodpecker/pr/cargo-checks Pipeline failed
2024-03-22 19:50:25 -04:00
2c298663b1 rsp only to elevated users
Some checks failed
ci/woodpecker/pr/cargo-checks Pipeline failed
2024-03-22 19:07:19 -04:00
582702fab2 load botmodules module 2024-03-22 18:49:07 -04:00
ba6117d692 validate status 2024-03-22 18:32:03 -04:00
29c8f74531 (cont) disable cmd logic 2024-03-22 18:16:41 -04:00
7757dd1820 (cont) enable cmd logic 2024-03-22 18:02:31 -04:00
8b4c21ba58 unit tests 2024-03-22 17:35:23 -04:00
072903882d botmodule case insensitive 2024-03-22 08:40:09 -04:00
0d6cc132ea (cont) enable/disable logic 2024-03-22 08:21:10 -04:00
2cf44bb6ca (init) modulesmgr commands 2024-03-21 21:20:16 -04:00
68f9be4968 unit tests
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-21 14:01:54 -04:00
619cdd1923 complete helper fns 2024-03-21 12:21:00 -04:00
23f12b3956 smol
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-21 09:37:08 -04:00
5280d18702 cont helper fns 2024-03-21 02:13:23 -04:00
1b44ec4f4c reorg statusdb 2024-03-21 00:11:24 -04:00
a066329730 botmodules helper fns 2024-03-21 00:05:52 -04:00
b353589576 refactor statustype 2024-03-20 23:35:56 -04:00
ca3bca9ae6 modgroup default statuses 2024-03-20 23:32:05 -04:00
dda0050513 identity adds core modules 2024-03-20 23:26:05 -04:00
eb8877f0c1 ModGroup enum 2024-03-20 23:20:46 -04:00
b5873a6ac1 Merge pull request 'Log Size Review' (#35) from logsize_review into main
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
Reviewed-on: #35
2024-03-20 21:00:55 -04:00
9a95584588 smol
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-20 20:56:43 -04:00
05bd683c49 Merge branch 'logsize_review' of https://git.flake.sh/modulatingforce/forcebot_rs into logsize_review 2024-03-20 20:54:52 -04:00
7d8672913a log retention = 2 days
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-20 20:49:47 -04:00
a82b4f94ac log retention = 2 days
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-20 20:43:57 -04:00
7efb679b06 Merge pull request 'Prevent Bots from running BotCommands' (#36) from Cmds_Cannot_Be_Ran_by_Bots into main
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
Reviewed-on: #36
2024-03-20 19:58:26 -04:00
e86fa4884b otherbots unit test
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-20 19:26:04 -04:00
e22e755bf5 other bots cant run botcommands
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-20 19:08:01 -04:00
9b7650053e experiment routinelike tokio spawn
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-20 01:06:59 -04:00
46ecc15b67 custom - babygirl cmd 2024-03-19 18:02:13 -04:00
f54990a502 smol enh to ratelimiter 2024-03-19 18:01:34 -04:00
53c5780322 Merge pull request 'Enh RateLimiters with Async Sleep' (#25) from chat_async_sleep into main
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
Reviewed-on: #25
2024-03-18 22:35:07 -04:00
e16749e69a enh ratelimiters
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-18 22:26:58 -04:00
f7881fa07d adj adminvector()
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-17 19:29:22 -04:00
5fb373c522 bot admins change
Some checks failed
ci/woodpecker/pr/cargo-checks Pipeline failed
2024-03-17 19:12:33 -03:00
b30207d449 Merge pull request 'Tori test' (#23) from tori_test into main
All checks were successful
ci/woodpecker/push/cargo-checks Pipeline was successful
Reviewed-on: #23
2024-03-17 17:47:16 -04:00
mzntori
239ef90e35 I love anime girls
All checks were successful
ci/woodpecker/pr/cargo-checks Pipeline was successful
2024-03-17 22:40:15 +01:00
fb1617d6d9 minor spelling mistake 2024-03-17 18:40:12 -03:00
26 changed files with 4818 additions and 890 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

View file

@ -1,5 +1,5 @@
when:
branch: main
branch: master
event: [push, pull_request]
path:
include:

View file

@ -37,7 +37,7 @@ steps:
owner: ${CI_REPO_OWNER}
repo: ${CI_REPO_NAME}
branch: flake-lock-update
base_branch: main
base_branch: master
pr_title: "flake.lock: update"
pr_body: PR automatically created by Woodpecker CI
close_pr_if_empty: true

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

@ -9,7 +9,15 @@ test ModulatingForceBot
```
login_name = <botname>
access_token = <oath token>
access_token = <oauth token>
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,26 +1,65 @@
{
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";
pre-commit-hooks,
}: let
eachSystem = nixpkgs.lib.genAttrs (import systems);
pkgsFor = eachSystem (system:
import nixpkgs {
localSystem.system = system;
overlays = [fenix.overlays.default];
pkgs = import nixpkgs {
inherit system overlays;
};
});
in {
devShells.${system}.default = pkgs.mkShell {
name = "forcebot_rs-devenv";
nativeBuildInputs = [pkgs.pkg-config];
buildInputs = with pkgs; [openssl libiconv];
packages = with pkgs; [
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
@ -35,5 +74,7 @@
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 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(a, msg.clone()).await;
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
);
if let BotMsgType::SayInReplyTo(_,_,_ ) = msginput {
botlog::trace(
logstr.as_str(),
Some("Chat > say_in_reply_to".to_string()),
Some(msg),
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();
}
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,9 @@ pub use crate::core::botmodules::ModulesManager;
// [ ] Load submodules
mod experiments;
// mod experiments;
mod experimental;
mod thisguy;
// [ ] init() function that accepts bot instance - this is passed to init() on submodules
@ -19,5 +21,7 @@ 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.clone()).await;
thisguy::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,285 @@
/*
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()
|| params.msg.sender.name.to_lowercase() == "haruyuumei".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),
);
}

62
src/custom/thisguy.rs Normal file
View file

@ -0,0 +1,62 @@
use crate::core::bot_actions::*;
use crate::core::botinstance::Channel;
use crate::core::botlog;
use crate::core::botmodules::{BotActionTrait, BotCommand, BotModule, ModulesManager};
use crate::core::identity::UserRole::*;
use rand::Rng;
use twitch_irc::message::ReplyToMessage;
use std::sync::Arc;
use tokio::time::{sleep, Duration};
const OF_CMD_CHANNEL:Channel = Channel(String::new());
async fn tsg(params: ExecBodyParams) {
let phrases: [String; 6] = [
"Clueless ".to_string(),
"ICANT This guy....".to_string(),
"He is right tho".to_string(),
"KEKW true!".to_string(),
"OMEGALUL wth man...".to_string(),
"PepeLaugh El no sabe".to_string(),
];
let r = rand::thread_rng().gen_range(0..=4);
let a = phrases[r].clone();
botlog::debug(
"This guy works!",
Some("modules > thisguy()".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(
Channel(params.clone().msg.channel_login().to_string()),
a,
params.clone()
)
.await;
sleep(Duration::from_secs_f64(0.5)).await;
}
pub async fn init(mgr: &Arc<ModulesManager>) {
BotCommand {
module: BotModule(String::from("thisguy")),
command: String::from("thisguy"),
alias: vec![String::from("Thisguy")],
exec_body: actions_util::asyncbox(tsg),
help: String::from("test"),
required_roles: vec![
BotAdmin,
Mod(OF_CMD_CHANNEL),
Broadcaster
],
}
.add_to_modmgr(Arc::clone(mgr))
.await;
}

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']