added preset commands and MORE DEBUG INFO LES GOOOOO

This commit is contained in:
2025-02-05 22:11:53 +01:00
parent 99b30f4cfa
commit b178968940
10 changed files with 117 additions and 38 deletions
+3 -1
View File
@@ -5,7 +5,6 @@
- [x] ~~Scrape the data~~ - [x] ~~Scrape the data~~
- [x] ~~Put it in a JSON~~ - [x] ~~Put it in a JSON~~
- [x] ~~Multithread so it can run both Discord and Reddit bot!!!~~ - [x] ~~Multithread so it can run both Discord and Reddit bot!!!~~
- [ ] Ship Python data to Rust
- [ ] Allow updating the data autonomously and via manual commands. - [ ] Allow updating the data autonomously and via manual commands.
- [ ] Manually add posts (via `u/[bot] add` or `/bk_week_add [url]`) - [ ] Manually add posts (via `u/[bot] add` or `/bk_week_add [url]`)
- [ ] Manually remove posts (via `/bk_week_remove [url]`) - [ ] Manually remove posts (via `/bk_week_remove [url]`)
@@ -16,6 +15,9 @@
- [x] ~~Function~~ - [x] ~~Function~~
- [ ] Automate - [ ] Automate
- [ ] Automatically approve posts that dont get caught by reverse image search (ris) - [ ] Automatically approve posts that dont get caught by reverse image search (ris)
- [ ] Log all posts in a Discord thread
- [ ] `/bk_week_get` command. Idk how to do this efficiently and automatically
- [ ] Removes the thread (if any exists), creates a new one, and sends all posts as embeds.
### Medium priority: ### Medium priority:
- [x] ~~JSON -> Rules list~~ - [x] ~~JSON -> Rules list~~
+76
View File
@@ -0,0 +1,76 @@
use crate::{Context, Error};
use crate::messages::send_msg;
use std::fs;
#[poise::command(slash_command, prefix_command)]
pub async fn bk_week_help(
ctx: Context<'_>,
) -> Result<(), Error>
{
let help = fs::read_to_string("./bk_week_help.txt").unwrap();
send_msg(ctx, help, true, true).await;
return Ok(());
}
#[poise::command(slash_command, prefix_command)]
pub async fn bk_week_get(
ctx: Context<'_>,
#[description = "The post URL"] url: Option<String>
) -> Result<(), Error>
{
// log all posts in a thread
return Ok(());
}
#[poise::command(slash_command, prefix_command)]
pub async fn bk_week_add(
ctx: Context<'_>,
#[description = "The post URL"] url: Option<String>,
#[description = "Wether to approve it after adding it"] approve: Option<bool>
) -> Result<(), Error>
{
// update data
// use python_comms.rs to tell python to update its data
return Ok(());
}
#[poise::command(slash_command, prefix_command)]
pub async fn bk_week_remove(
ctx: Context<'_>,
#[description = "The post URL"] url: Option<String>
) -> Result<(), Error>
{
// update data
// use python_comms.rs to tell python to update its data
return Ok(());
}
#[poise::command(slash_command, prefix_command)]
pub async fn bk_week_approve(
ctx: Context<'_>,
#[description = "The post URL"] url: Option<String>
) -> Result<(), Error>
{
// update data
// use python_comms.rs to tell python to update its data
return Ok(());
}
#[poise::command(slash_command, prefix_command)]
pub async fn bk_week_disapprove(
ctx: Context<'_>,
#[description = "The post URL"] url: Option<String>
) -> Result<(), Error>
{
// update data
// use python_comms.rs to tell python to update its data
return Ok(());
}
+2 -15
View File
@@ -1,8 +1,6 @@
use crate::{Context, Error}; use crate::{Context, Error};
use crate::messages::{send_embed, send_msg, edit_msg, EmbedOptions}; use crate::messages::{send_embed, send_msg, edit_msg, EmbedOptions};
use std::fs;
use poise::serenity_prelude::{GetMessages, OnlineStatus, Timestamp, UserId}; use poise::serenity_prelude::{GetMessages, OnlineStatus, Timestamp, UserId};
use rand::{seq::IteratorRandom, Rng}; use rand::{seq::IteratorRandom, Rng};
@@ -180,7 +178,7 @@ pub async fn write_json(
} }
async fn autocomplete_rule_list(_: Context<'_>, _partial: &str) -> Vec<String> { /* async fn autocomplete_rule_list(_: Context<'_>, _partial: &str) -> Vec<String> {
let json_str = std::fs::read_to_string("./data/write_json.json") let json_str = std::fs::read_to_string("./data/write_json.json")
.expect("No JSON preset file exists."); .expect("No JSON preset file exists.");
let json_json: serde_json::Value = serde_json::from_str(&json_str).expect("JSON was improperly formatted"); let json_json: serde_json::Value = serde_json::from_str(&json_str).expect("JSON was improperly formatted");
@@ -218,15 +216,4 @@ pub async fn rule(
{ {
return Ok(()); return Ok(());
} }
*/
#[poise::command(slash_command, prefix_command)]
pub async fn bk_week_help(
ctx: Context<'_>,
) -> Result<(), Error>
{
let help = fs::read_to_string("./bk_week_help.txt").unwrap();
send_msg(ctx, help, true, true).await;
return Ok(());
}
+9 -3
View File
@@ -1,7 +1,9 @@
mod cmds; mod cmds;
mod bk_week_cmds;
mod events; mod events;
mod messages; mod messages;
mod python; mod python;
mod reddit_data;
use std::env; use std::env;
use std::process; use std::process;
@@ -11,11 +13,14 @@ use std::fs;
use tokio::runtime::Runtime; use tokio::runtime::Runtime;
use poise::serenity_prelude::Client; use poise::serenity_prelude::Client;
use poise::serenity_prelude as serenity; use poise::serenity_prelude as serenity;
use serde_json::Value;
struct Data { struct Data {
dev: bool, dev: bool,
ball_prompts: [Vec<String>; 2], ball_prompts: [Vec<String>; 2],
creator_id: u64 creator_id: u64,
reddit_data: Option<Value>,
// TODO: schedules
} }
type Error = Box<dyn std::error::Error + Send + Sync>; type Error = Box<dyn std::error::Error + Send + Sync>;
type Context<'a> = poise::Context<'a, Data, Error>; type Context<'a> = poise::Context<'a, Data, Error>;
@@ -91,6 +96,7 @@ fn gen_data(args: Vec<String>) -> Data {
dev: args.contains(&"--dev".to_string()), dev: args.contains(&"--dev".to_string()),
ball_prompts: [ball_classic, ball_quirk], ball_prompts: [ball_classic, ball_quirk],
creator_id: 697149665166229614, creator_id: 697149665166229614,
reddit_data: None
}; };
} }
@@ -113,8 +119,8 @@ async fn gen_bot(data: Data) -> Client {
cmds::stop(), cmds::stop(),
cmds::eight_ball(), cmds::eight_ball(),
cmds::write_json(), cmds::write_json(),
cmds::rule(), //cmds::rule(),
cmds::bk_week_help() bk_week_cmds::bk_week_help()
], ],
event_handler: events::event_handler, event_handler: events::event_handler,
..Default::default() ..Default::default()
+5 -17
View File
@@ -65,7 +65,7 @@ def read_data(bot: botPy.Bot):
bot.data_f = open(data_path + "\\reddit_data.json", "r+") bot.data_f = open(data_path + "\\reddit_data.json", "r+")
except FileNotFoundError: except FileNotFoundError:
print("reddit_data.json not found, creating new from preset...") py_print("reddit_data.json not found, creating new from preset...")
with open(data_path + "\\reddit_data.json", "w") as f: with open(data_path + "\\reddit_data.json", "w") as f:
f.write(open(data_path + "\\reddit_data_preset.json", "r").read()) f.write(open(data_path + "\\reddit_data_preset.json", "r").read())
@@ -84,28 +84,16 @@ def write_data(bot: botPy.Bot):
bot.data_f.truncate() bot.data_f.truncate()
def update_post_in_data(bot: botPy.Bot, new_data: PostData): def add_post_to_data(bot: botPy.Bot, new_data: PostData) -> bool:
if new_data.url not in bot.data[BK_WEEKLY]: if new_data.url not in bot.data[BK_WEEKLY]:
bot.data[BK_WEEKLY][new_data.url] = new_data.to_json() bot.data[BK_WEEKLY][new_data.url] = new_data.to_json()
py_print(f"Added post \"{new_data.url}\"") py_print(f"Added post \"{new_data.url}\"")
return return True
elif "removed" in bot.data[BK_WEEKLY][new_data.url]: elif "removed" in bot.data[BK_WEEKLY][new_data.url]:
py_print(f"Failed to add post \"{new_data.url}\": Removed flag is True.") py_print(f"Failed to add post \"{new_data.url}\": Removed flag is True.")
return return False
else: else:
py_print(f"Failed to add post \"{new_data.url}\": Already exists.") py_print(f"Failed to add post \"{new_data.url}\": Already exists.")
return False
def remove_old_posts(bot: botPy.Bot, max_age_unix: int):
for post in bot.data[BK_WEEKLY]:
if post["date_unix"] > max_age_unix:
dict(bot.data[BK_WEEKLY]).pop(post)
def clear_posts_without_media(bot: botPy.Bot):
for post in bot.data[BK_WEEKLY]:
post_data = post["post_data"]
if post_data["media_type"] == None and len(post_data["media_urls"]) == 0:
dict(bot.data[BK_WEEKLY]).pop(post)
+3
View File
@@ -13,6 +13,9 @@ def main():
py_print("Reading data...") py_print("Reading data...")
data.read_data(bot) data.read_data(bot)
# TEMPORARY, will be replaced with a
# schedule and/or Discord bot command
# config file or options ^
posts.add_new_posts(bot) posts.add_new_posts(bot)
+17 -2
View File
@@ -12,8 +12,13 @@ def add_new_posts(bot: botPy.Bot, debug_print: bool = False):
posts = reddit.fetch_posts_with_flair(bot, "Original Art") posts = reddit.fetch_posts_with_flair(bot, "Original Art")
py_print("Evaluating posts...\n") py_print("Evaluating posts...\n")
added_posts = 0
without_media = 0
not_added = 0
for post in posts: for post in posts:
media = reddit.has_media(post) media = reddit.has_media(post)
media_urls = "\n ".join(media[3]) media_urls = "\n ".join(media[3])
if debug_print: print( if debug_print: print(
@@ -23,7 +28,11 @@ def add_new_posts(bot: botPy.Bot, debug_print: bool = False):
f"\n {media_urls}\n" f"\n {media_urls}\n"
) )
data.update_post_in_data( if not media[0]:
without_media += 1
continue
post_added = data.add_post_to_data(
bot, bot,
data.PostData( data.PostData(
post.shortlink, post.shortlink,
@@ -36,6 +45,12 @@ def add_new_posts(bot: botPy.Bot, debug_print: bool = False):
) )
) )
py_print(f"Sucessfully fetched {len(posts)} posts") if post_added: added_posts += 1
else: not_added += 1
py_print(f"Sucessfully fetched {len(posts)} posts.\n" +
f" Out of which were {added_posts} added.\n" +
f" {without_media} had no media, " +
f"and {not_added} weren't added because they are removed or already existed")
data.write_data(bot) data.write_data(bot)
+1
View File
@@ -0,0 +1 @@
# communicate with rust.
+1
View File
@@ -0,0 +1 @@
// communicate with python
View File