From d0a61f7b165d98790a4d277f06927fed9435f17f Mon Sep 17 00:00:00 2001 From: ByteDice Date: Wed, 5 Mar 2025 22:21:21 +0100 Subject: [PATCH] started on new help command --- bk_week_help_dc.md | 29 ----------- src/bk_week_cmds.rs | 44 +++------------- src/cmds.rs | 104 +++++++++++++++++++++++++++++++++++-- src/data.rs | 1 - src/main.rs | 2 +- src/python/bot.py | 6 +++ src/python/py_websocket.py | 2 +- 7 files changed, 116 insertions(+), 72 deletions(-) delete mode 100644 bk_week_help_dc.md diff --git a/bk_week_help_dc.md b/bk_week_help_dc.md deleted file mode 100644 index 46d9102..0000000 --- a/bk_week_help_dc.md +++ /dev/null @@ -1,29 +0,0 @@ -# Discord Commands -`[this means it's a required argument]` -`` - -## `/bk_week_get [url]` -Shows info about a single post. -## `/bk_week_add [url] ` -Adds a URL to the list of posts. This is done automatically by the bot for certain posts. -- **``**: `true` or `false`, determines whether to automatically approve the post when added. -## `/bk_week_remove [url]` -Removes an existing URL from the list of posts. -## `/bk_week_approve [url] ` -Flags the post as **human_approved**, confirming that the artwork is original. -- **``**: set to `true` if you want to undo an approval. -## `/bk_week_vote [url] ` -Adds a vote to a post. The intended use for votes is for a "moderator picks" and a "community picks" section of the weekly art. -You can vote on as many posts as you want, but only once per post. -## `/bk_week_update ` -Updates all data in the bound Discord channel. It's recommended to only run this if absolutely needed to. -- **``**: If it's `true`, the bot will only add new posts, not remove or update them. -- **``**: The bot will remove any post older than `max_age` days. (0 means infinite.) -## `/bk_week_top [category] ` -Shows you the top posts within a category, such as upvotes. (max 10 posts, default is 3) -## `/bk_admin_bind` -Binds the current channel as the channel where the bk_week data is sent and updated in. No binding means the only way to view the data is using `/bk_week_get`. -## `/bk_week_help [option]` -Shows a help text. -# Things to note -* This bot uses shortURLs when storing posts. If you want to access posts, you should use their shortURL. You can get a Reddit shortURL by running `/re_shorturl [url]`. \ No newline at end of file diff --git a/src/bk_week_cmds.rs b/src/bk_week_cmds.rs index ce24aae..d2329e9 100644 --- a/src/bk_week_cmds.rs +++ b/src/bk_week_cmds.rs @@ -4,7 +4,6 @@ use crate::messages::*; use crate::data::{self, dc_bind_bk, get_mutex_data}; use std::collections::HashMap; -use std::fs; use std::time::{SystemTime, UNIX_EPOCH}; use poise::serenity_prelude::{ChannelId, EditMessage, GetMessages, Http, Message, MessageId, UserId}; @@ -12,11 +11,6 @@ use poise::ReplyHandle; use serde_json::{json, Map, Value}; -#[derive(poise::ChoiceParameter, PartialEq)] -enum HelpOptions { - Discord, - Reddit -} #[derive(poise::ChoiceParameter, PartialEq)] enum TopCategory { Upvotes, @@ -36,41 +30,12 @@ async fn not_bk_mod_msg(ctx: Context<'_>) { } -#[poise::command( - slash_command, - prefix_command, - required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" -)] -/// Shows helpful information on how to use the bk_week section of the bot. -pub async fn bk_week_help( - ctx: Context<'_>, - #[description = "Discord or Reddit help."] option: HelpOptions -) -> Result<(), Error> -{ - let help: String; - - if option == HelpOptions::Discord { - help = fs::read_to_string("./bk_week_help_dc.md").unwrap(); - } - else if option == HelpOptions::Reddit { - help = fs::read_to_string("./bk_week_help_re.md").unwrap(); - } - else { - help = "Unknown error!\nError trace: `bk_week_cmds.rs -> bk_week_help() -> option is not valid`.".to_string(); - } - - send_msg(ctx, help, true, true).await; - data::read_dc_data(ctx.data(), false).await; - - return Ok(()); -} - - #[poise::command( slash_command, prefix_command, + category = "bk_week", required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL | EMBED_LINKS" )] /// Fetches the data of a single post, just for you. The data has to be within the database to work. @@ -160,6 +125,7 @@ async fn send_data_corrupted_message(ctx: Context<'_>, url: &str) { #[poise::command( slash_command, prefix_command, + category = "bk_week", required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" )] /// Fetches a post from Reddit and adds it to the database. @@ -232,6 +198,7 @@ async fn send_updated_msg(ctx: Context<'_>, url: &str) { #[poise::command( slash_command, prefix_command, + category = "bk_week", required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" )] /// Removes a post from the database. It will show who last removed it. @@ -270,6 +237,7 @@ pub async fn bk_week_remove( #[poise::command( slash_command, prefix_command, + category = "bk_week", required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" )] /// Approves a post in the database. Approving posts tells the bot that it's original. @@ -324,6 +292,7 @@ async fn approve_cmd(ctx: Context<'_>, url: &str, reddit_data: &Value, approve: #[poise::command( slash_command, prefix_command, + category = "admin", default_member_permissions = "ADMINISTRATOR", guild_only, required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" @@ -357,6 +326,7 @@ async fn send_server_not_in_data_msg(ctx: Context<'_>) { #[poise::command( slash_command, prefix_command, + category = "bk_week", guild_only, guild_cooldown = 120, required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL | READ_MESSAGE_HISTORY | EMBED_LINKS" @@ -655,6 +625,7 @@ async fn remove_dupes(http: &Http, c_id: ChannelId, msgs_json: &Value) { #[poise::command( slash_command, prefix_command, + category = "bk_week", required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" )] /// Adds/removes a vote from a post. These votes are not tied to Reddit upvotes. @@ -719,6 +690,7 @@ pub async fn bk_week_vote( #[poise::command( slash_command, prefix_command, + category = "bk_week", required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL | EMBED_LINKS" )] /// Gets the top N (up to 10) posts within a certain category, such as upvotes. (Sorted descending.) diff --git a/src/cmds.rs b/src/cmds.rs index 12352e7..d0e1356 100644 --- a/src/cmds.rs +++ b/src/cmds.rs @@ -5,15 +5,27 @@ use crate::websocket::send_cmd_json; use crate::{data, Context, Error}; use crate::messages::{edit_reply, send_embed, send_msg, Author, EmbedOptions, MANDATORY_MSG}; +use poise::samples::HelpConfiguration; use poise::serenity_prelude::{OnlineStatus, Timestamp}; use rand::{seq::IteratorRandom, Rng}; use regex::Regex; use serde_json::json; +use tokio::fs; + + +#[derive(poise::ChoiceParameter, PartialEq)] +enum HelpOptions { + BkWeek, + BkWeekReddit, + Generic, + +} #[poise::command( slash_command, prefix_command, + category = "fun", required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" )] /// Check if you have connection to the bot. @@ -31,10 +43,11 @@ pub async fn ping( #[poise::command( slash_command, prefix_command, + category = "owner", owners_only, required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" )] -/// Stops the bot... if you're mighty enough! +/// I have security measures, even in developer mode. You wont access this without being a bot "owner". pub async fn stop( ctx: Context<'_>, #[description = "Type \"i want to stop the bot now\" to confirm."] confirmation: Option, @@ -67,6 +80,7 @@ pub async fn stop( #[poise::command( slash_command, prefix_command, + category = "owner", owners_only, required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL | EMBED_LINKS" )] @@ -115,6 +129,7 @@ pub async fn embed( #[poise::command( slash_command, prefix_command, + category = "owner", owners_only, required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" )] @@ -134,6 +149,7 @@ pub async fn send( #[poise::command( slash_command, prefix_command, + category = "fun", rename = "8_ball", required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" )] @@ -198,6 +214,7 @@ pub fn to_shorturl(url: &str) -> Result { #[poise::command( slash_command, prefix_command, + category = "admin", default_member_permissions = "ADMINISTRATOR", guild_only, required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" @@ -223,6 +240,7 @@ pub async fn add_server( #[poise::command( slash_command, prefix_command, + category = "owner", owners_only, required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" )] @@ -231,16 +249,94 @@ pub async fn reload_cfg( ctx: Context<'_> ) -> Result<(), Error> { - let d = get_mutex_data(&ctx.data().cfg).await?; let d_str = serde_json::to_string(&d)?; - let r = send_cmd_json("update_cfg", Some(json!([d_str]))).await; // TODO: THIS + let r = send_cmd_json("update_cfg", Some(json!([d_str]))).await; if r.is_some() && r.unwrap()["value"].as_bool().unwrap() { - send_msg(ctx, "Successfully reloaded the configs!".to_string(), true, true).await; + send_msg( + ctx, + format!("Successfully reloaded the configs!\nNew configs:\n```\n{}\n```", serde_json::to_string_pretty(&d)?), + true, + true + ).await; return Ok(()); } send_msg(ctx, "Failed to reload configs: Failed-type response from Python.".to_string(), true, true).await; return Ok(()); +} + + +#[poise::command( + slash_command, + prefix_command, + category = "help", + required_bot_permissions = "SEND_MESSAGES | VIEW_CHANNEL" +)] +/// Shows helpful information on how to use the bk_week section of the bot. +pub async fn help( + ctx: Context<'_>, + #[description = "A full category of commands."] category: Option, + #[description = "The name of a single command. This argument will be prioritized over `category`."] cmd: Option +) -> Result<(), Error> +{ + match (category.is_some(), cmd.is_some()) { + (false, false) => (), + (true, false) => send_category_help(ctx, category.unwrap()).await, + _ => send_single_help(ctx, cmd).await + } + + return Ok(()); +} + + +async fn send_single_help(ctx: Context<'_>, mut cmd: Option) { + let inv_name = ctx.invoked_command_name(); + + if inv_name != "help" { + cmd = match cmd { + Some(c) => Some(format!("{} {}", inv_name, c)), + None => Some(inv_name.to_string()), + }; + } + + let bottom_text = "skibidi"; + + let config = HelpConfiguration { + show_subcommands: true, + show_context_menu_commands: true, + ephemeral: true, + extra_text_at_bottom: bottom_text, + + ..Default::default() + }; + let _ = poise::builtins::help(ctx, cmd.as_deref(), config).await; +} + + +async fn send_category_help(ctx: Context<'_>, category: HelpOptions) { + match category { + HelpOptions::BkWeekReddit => send_bk_week_help_re(ctx).await, + HelpOptions::BkWeek => send_bk_week_help (ctx).await, + HelpOptions::Generic => send_generic_help (ctx).await, + } +} + + +async fn send_bk_week_help_re(ctx: Context<'_>) { + let t: String = fs::read_to_string("./bk_week_help_re.md").await + .unwrap_or("Help text not found. Someone deleted it. :(".to_string()); + + send_msg(ctx, t, true, true).await; +} + + +async fn send_bk_week_help(ctx: Context<'_>) { + +} + + +async fn send_generic_help(ctx: Context<'_>) { + } \ No newline at end of file diff --git a/src/data.rs b/src/data.rs index 61fcd35..1e42086 100644 --- a/src/data.rs +++ b/src/data.rs @@ -188,7 +188,6 @@ pub async fn dc_contains_server(data: &Data, server_id: u64) -> bool { } -#[allow(non_snake_case)] pub async fn get_mutex_data(data: &Mutex>) -> Result { let data_lock = data.lock().await; return match data_lock.as_ref() { diff --git a/src/main.rs b/src/main.rs index 849c1b4..de5e7b3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -194,6 +194,7 @@ async fn gen_bot(data: Data, args: Args) -> Client { .options(poise::FrameworkOptions { owners: own, commands: vec![ + cmds::help(), cmds::ping(), cmds::embed(), cmds::send(), @@ -202,7 +203,6 @@ async fn gen_bot(data: Data, args: Args) -> Client { cmds::re_shorturl(), cmds::add_server(), // bk_week - bk_week_cmds::bk_week_help(), bk_week_cmds::bk_week_get(), bk_week_cmds::bk_week_add(), bk_week_cmds::bk_week_remove(), diff --git a/src/python/bot.py b/src/python/bot.py index 11b3c48..ba57c7f 100644 --- a/src/python/bot.py +++ b/src/python/bot.py @@ -55,6 +55,12 @@ class Bot: return False + async def update_cfg_str(self, new_cfg: str) -> bool: + json_cfg = json.loads(new_cfg) + self.sr = await self.r.subreddit(json_cfg[BK_WEEK]["subreddits"]) + self.fetch_limit = json_cfg[BK_WEEK]["fetch_limit"] + return True + async def update_cfg(self, new_cfg: dict) -> bool: self.sr = await self.r.subreddit(new_cfg[BK_WEEK]["subreddits"]) self.fetch_limit = new_cfg[BK_WEEK]["fetch_limit"] diff --git a/src/python/py_websocket.py b/src/python/py_websocket.py index d72134c..2111ccf 100644 --- a/src/python/py_websocket.py +++ b/src/python/py_websocket.py @@ -82,7 +82,7 @@ async def json_to_func(v: dict, bot: botPy.Bot) -> dict: case "set_approve_post": r = data .set_approve_post (bot, *v["args"]) case "set_vote_post": r = data .set_vote_post (bot, *v["args"]) case "remove_old_posts": r = data .remove_old_posts (bot, *v["args"]) - case "update_cfg": r = await bot .update_cfg (*v["args"]) + case "update_cfg": r = await bot .update_cfg_str (*v["args"]) case "stop_praw": r = await bot .stop () case _: value_supported = False