too much to remember, mostly refactoring/enhancing/changing/re-doing/re-writing stuff

This commit is contained in:
2025-04-12 23:14:56 +02:00
parent 149a22ff7f
commit 854809e321
20 changed files with 96 additions and 114 deletions
+6 -4
View File
@@ -4,7 +4,7 @@ use std::path::Path;
use serde_json::{self, Value, json};
use tokio::sync::Mutex;
use crate::{errln, rs_println, Data, Error, BK_WEEK, LANG};
use crate::{errln, rs_println, Data, Error, CFG_DATA_RE, LANG};
use crate::websocket::send_cmd_json;
@@ -16,6 +16,8 @@ static DATA_PATH_CFG: &str = "./data/cfg.json";
static PRESET_PATH_CFG: &str = "./data/cfg_default.json";
static DATA_PATH_LANG: &str = "./data/lang/";
pub static DC_POSTS_CHANNEL_KEY: &str = "re_posts_channel";
pub async fn read_dc_data(data: &Data, wipe: bool) {
if !Path::new(DATA_PATH_DC).exists() || wipe {
@@ -88,7 +90,7 @@ fn generate_re_data() {
let preset_str = fs::read_to_string(PRESET_PATH_RE).unwrap();
let mut preset_json: Value = serde_json::from_str(&preset_str).unwrap();
if let Some(bk_week) = preset_json[BK_WEEK].as_object_mut() {
if let Some(bk_week) = preset_json[CFG_DATA_RE].as_object_mut() {
bk_week.remove("EXAMPLE VALUE");
bk_week.remove("EXAMPLE VALUE DELETED");
}
@@ -149,7 +151,7 @@ pub async fn dc_add_server(data: &Data, server_id: u64) -> Result<(), ()> {
let servers = dc_data["servers"].as_object_mut().unwrap();
if !servers.contains_key(&server_id.to_string()) {
servers.insert(server_id.to_string(), json!({ "bk_week_channel": 0 }));
servers.insert(server_id.to_string(), json!({ DC_POSTS_CHANNEL_KEY: 0 }));
}
return Ok(());
@@ -170,7 +172,7 @@ pub async fn dc_bind_bk(data: &Data, server_id: u64, channel_id: u64) -> Result<
let server = servers[&server_id.to_string()].as_object_mut().unwrap();
server.insert("bk_week_channel".to_string(), channel_id.into());
server.insert(DC_POSTS_CHANNEL_KEY.to_string(), channel_id.into());
return Ok(());
}
+7 -7
View File
@@ -59,7 +59,7 @@ struct Args {
noping: bool,
#[arg(long, help = "Makes the program not use the schedules.")]
nosched: bool,
#[arg(long, default_value = "en", help = "Which language file to use (Do not include file extention)")]
#[arg(long, default_value = "en", help = "Which language file to use (Do not include file extensions)")]
lang: String
}
@@ -79,7 +79,7 @@ struct Data {
}
static BK_WEEK: &str = "bk_weekly_art_posts";
static CFG_DATA_RE: &str = "posts";
pub static mut LANG: Option<serde_json::Value> = None;
@@ -100,19 +100,19 @@ async fn main() {
.map(|s| s.parse::<u64>().expect("Failed to parse ASSISTANT_OWNERS. Invalid syntax."))
.collect();
if args.test { println!("----- USING TEST BOT -----"); }
if args.dev { println!("----- DEV MODE ENABLED -----"); }
if args.test { println!("----- USING TEST BOT -----"); }
if args.dev { println!("----- DEV MODE ENABLED -----"); }
if args.dev && args.wipe { println!("----- \"DON'T WORRY ABOUT IT\" MODE ENABLED -----"); }
if args.nosched { println!("----- NO SCHEDULES -----") }
if args.nosched { println!("----- NO SCHEDULES -----"); }
if args.py && !args.rs {
println!("----- PYTHON ONLY MODE -----");
println!("----- PYTHON ONLY MODE -----");
rs_println!("ARGS: {}", args_str);
let _ = python::start(args).await;
process::exit(0);
}
else if args.rs && ! args.py {
println!("----- RUST ONLY MODE -----");
println!("----- RUST ONLY MODE -----");
rs_println!("ARGS: {}", args_str);
start(args, own_vec_u64.clone()).await;
process::exit(0);
+7 -7
View File
@@ -6,8 +6,8 @@ from macros import *
import json
BK_WEEKLY: Final[str] = "bk_weekly_art_posts"
BK_WEEK: Final[str] = "bk_week"
RE_DATA_POSTS: Final[str] = "posts"
CFG_DATA_RE: Final[str] = "reddit"
class Bot:
@@ -22,7 +22,7 @@ class Bot:
useragent: str =\
f"{username} by u/RandomPersonDotExe aka u/Byte_Dice"\
if r_id == "YmZjr4zLr2qtHdpQXtj0sBOOdJzrXQ"\
else f"{username} (original program by u/RandomPersonDotExe aka u/Byte_Dice)"
else f"{username} (Original program by u/RandomPersonDotExe aka u/Byte_Dice)"
if password is None:
py_error("Environment variable \"ASSISTANT_R_PASS\" is null!")
@@ -57,11 +57,11 @@ class Bot:
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"]
self.sr = await self.r.subreddit(json_cfg[CFG_DATA_RE]["subreddits"])
self.fetch_limit = json_cfg[CFG_DATA_RE]["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"]
self.sr = await self.r.subreddit(new_cfg[CFG_DATA_RE]["subreddits"])
self.fetch_limit = new_cfg[CFG_DATA_RE]["fetch_limit"]
return True
+6 -7
View File
@@ -6,7 +6,7 @@ import data
import posts
BOT_ACTION_POSTFIX = "\n\n^(I am not an AI, I am just a bot. This action was performed automatically by the way.)"
BOT_ACTION_POSTFIX = "^(I am not an AI, I am just a bot. This action was performed automatically by the way. You can report bugs and view my source code [here](https://github.com/ByteDice/ByteDiceAssistant)!)"
async def make_cmd(cmd: str, bot: botPy.Bot) -> str:
@@ -29,7 +29,7 @@ async def respond_to_mention(bot: botPy.Bot) -> bool:
py_print(f"New mention: {truncated}")
if await is_cmd("bk_week_add", body, bot):
if await is_cmd("add_post", body, bot):
await bk_week_add(mention, bot)
else:
@@ -57,17 +57,16 @@ async def bk_week_add(mention: models.Comment, bot: botPy.Bot):
short_url = mention.submission.shortlink
r = ""
bd = bot.data[botPy.BK_WEEKLY]
# TODO: ask if the messages should be changed
bd = bot.data[botPy.RE_DATA_POSTS]
if short_url not in bd:
posts.add_post_url(bot, short_url)
r = "Successfully added this post to the data!"
if short_url in bd and is_mod:
if "removed" in bd[short_url]:
r = "(Mod action) Successfully un-removed this post from the data!"
r = "[MOD ACTION] Successfully un-removed this post from the data!"
else:
r = "(Mod action) Successfully added this post to the data!"
r = "[MOD ACTION] Successfully added this post to the data!"
post = await posts.from_url(bot, short_url)
post_data = posts.get_post_details(post[1])
@@ -77,5 +76,5 @@ async def bk_week_add(mention: models.Comment, bot: botPy.Bot):
r = "Could not add this post to the data. Luckily, it's already there, so there's nothing to worry about!"
await mention.reply(r + " Thank you for participating!" + BOT_ACTION_POSTFIX)
await mention.reply(r + " Thank you for participating!" + "\n\n" + BOT_ACTION_POSTFIX)
await mention.mark_read()
+16 -16
View File
@@ -79,8 +79,8 @@ def read_data(bot: botPy.Bot) -> bool:
with open(os.path.join(DATA_PATH, "re_data_preset.json", "r")) as f:
data_preset_json = json.load(f)
data_preset_json[botPy.BK_WEEKLY].pop("EXAMPLE VALUE", None)
data_preset_json[botPy.BK_WEEKLY].pop("EXAMPLE VALUE DELETED", None)
data_preset_json[botPy.RE_DATA_POSTS].pop("EXAMPLE VALUE", None)
data_preset_json[botPy.RE_DATA_POSTS].pop("EXAMPLE VALUE DELETED", None)
with open(r_path, "w") as f:
json.dump(data_preset_json, f, indent = 2)
@@ -126,7 +126,7 @@ async def read_cfg(bot: botPy.Bot) -> bool:
def add_post_to_data(bot: botPy.Bot, new_data: PostData, bypass_conditions: bool = False) -> bool:
if bypass_conditions:
bot.data[botPy.BK_WEEKLY][new_data.url] = new_data.to_json()
bot.data[botPy.RE_DATA_POSTS][new_data.url] = new_data.to_json()
if bot.args["dev"]:
py_print(f"Added post \"{new_data.url}\" (Conditions bypassed)")
return True
@@ -134,14 +134,14 @@ def add_post_to_data(bot: botPy.Bot, new_data: PostData, bypass_conditions: bool
# not sure what this is for
updated = False
if new_data.url not in bot.data[botPy.BK_WEEKLY] or updated:
bot.data[botPy.BK_WEEKLY][new_data.url] = new_data.to_json()
if new_data.url not in bot.data[botPy.RE_DATA_POSTS] or updated:
bot.data[botPy.RE_DATA_POSTS][new_data.url] = new_data.to_json()
if bot.args["dev"]:
py_print(f"Added post \"{new_data.url}\"")
return True
if "removed" not in bot.data[botPy.BK_WEEKLY][new_data.url]:
updated = new_data.upvotes != bot.data[botPy.BK_WEEKLY][new_data.url]["post_data"]
if "removed" not in bot.data[botPy.RE_DATA_POSTS][new_data.url]:
updated = new_data.upvotes != bot.data[botPy.RE_DATA_POSTS][new_data.url]["post_data"]
else:
py_print(f"Failed to add post \"{new_data.url}\": Removed flag is True.")
@@ -149,15 +149,15 @@ def add_post_to_data(bot: botPy.Bot, new_data: PostData, bypass_conditions: bool
def set_approve_post(bot: botPy.Bot, approved: bool, url: str) -> bool:
if not hasattr(bot.data[botPy.BK_WEEKLY][url], "removed"):
bot.data[botPy.BK_WEEKLY][url]["approved"]["by_human"] = approved
if not hasattr(bot.data[botPy.RE_DATA_POSTS][url], "removed"):
bot.data[botPy.RE_DATA_POSTS][url]["approved"]["by_human"] = approved
return True
return False
def remove_post(bot: botPy.Bot, url: str, removed_by: str = "UNKNOWN", reason: str = "None") -> bool:
weekly = bot.data[botPy.BK_WEEKLY]
weekly = bot.data[botPy.RE_DATA_POSTS]
if url in weekly:
weekly[url] = {
@@ -173,7 +173,7 @@ def remove_post(bot: botPy.Bot, url: str, removed_by: str = "UNKNOWN", reason: s
def remove_old_posts(bot: botPy.Bot, max_age: int) -> bool:
now = int(time.time())
weekly = bot.data[botPy.BK_WEEKLY]
weekly = bot.data[botPy.RE_DATA_POSTS]
remove: list[str] = []
for url, post in weekly.items():
@@ -194,10 +194,10 @@ def set_vote_post(
from_dc: bool = False,
remove_vote: bool = False,
) -> bool:
if url not in bot.data[botPy.BK_WEEKLY]:
if url not in bot.data[botPy.RE_DATA_POSTS]:
return False
votes = bot.data[botPy.BK_WEEKLY][url]["votes"]
votes = bot.data[botPy.RE_DATA_POSTS][url]["votes"]
re_voters: set[str] = set(votes["voters_re"])
dc_voters: set[int] = set(votes["voters_dc"])
mod_voters: set[int] = set(votes["mod_voters"])
@@ -214,8 +214,8 @@ def set_vote_post(
return False
target_voters.add(user)
bot.data[botPy.BK_WEEKLY][url]["votes"]["voters_re"] = list(re_voters)
bot.data[botPy.BK_WEEKLY][url]["votes"]["voters_dc"] = list(dc_voters)
bot.data[botPy.BK_WEEKLY][url]["votes"]["mod_voters"] = list(mod_voters)
bot.data[botPy.RE_DATA_POSTS][url]["votes"]["voters_re"] = list(re_voters)
bot.data[botPy.RE_DATA_POSTS][url]["votes"]["voters_dc"] = list(dc_voters)
bot.data[botPy.RE_DATA_POSTS][url]["votes"]["mod_voters"] = list(mod_voters)
return True
+5 -4
View File
@@ -2,8 +2,8 @@ use serde_json::json;
use crate::data::get_mutex_data;
use crate::messages::send_msg;
use crate::{data, websocket, Context, Error, BK_WEEK};
use crate::re_cmds::generic_fns::{is_bk_mod, to_shorturl};
use crate::{data, websocket, Context, Error, CFG_DATA_RE};
use crate::re_cmds::generic_fns::{get_readable_subreddits, is_bk_mod, to_shorturl};
use crate::lang;
#[poise::command(
@@ -21,7 +21,8 @@ pub async fn cmd(
) -> Result<(), Error>
{
if !is_bk_mod(ctx.data().bk_mods.clone(), ctx.author().id.get()) {
send_msg(ctx, lang!("dc_msg_re_permdeny_not_re_mod"), false, false).await; // TODO: add subreddit arg to lang
let sr = get_readable_subreddits(ctx).await?;
send_msg(ctx, lang!("dc_msg_re_permdeny_not_re_mod", sr), false, false).await;
return Ok(());
}
@@ -31,7 +32,7 @@ pub async fn cmd(
data::update_re_data(ctx.data()).await;
let reddit_data = get_mutex_data(&ctx.data().reddit_data).await?;
if let Some(bk_week) = reddit_data.get(BK_WEEK) {
if let Some(bk_week) = reddit_data.get(CFG_DATA_RE) {
let a = approve.unwrap_or(false);
let r = websocket::send_cmd_json("add_post_url", Some(json!([&shorturl, a, true]))).await.unwrap();
+4 -3
View File
@@ -1,6 +1,6 @@
use serde_json::{json, Value};
use crate::{data::{self, get_mutex_data}, lang, messages::send_msg, re_cmds::generic_fns::is_bk_mod, websocket, Context, Error, BK_WEEK};
use crate::{data::{self, get_mutex_data}, lang, messages::send_msg, re_cmds::generic_fns::{get_readable_subreddits, is_bk_mod}, websocket, Context, Error, CFG_DATA_RE};
use super::generic_fns::send_embed_for_removed;
@@ -19,7 +19,8 @@ pub async fn cmd(
) -> Result<(), Error>
{
if !is_bk_mod(ctx.data().bk_mods.clone(), ctx.author().id.get()) {
send_msg(ctx, lang!("dc_msg_re_permdeny_not_re_mod"), false, false).await;
let sr = get_readable_subreddits(ctx).await?;
send_msg(ctx, lang!("dc_msg_re_permdeny_not_re_mod", sr), false, false).await;
return Ok(());
}
@@ -33,7 +34,7 @@ pub async fn cmd(
async fn approve_cmd(ctx: Context<'_>, url: &str, reddit_data: &Value, approve: bool) {
if let Some(post) = reddit_data.get(BK_WEEK).unwrap().get(url) {
if let Some(post) = reddit_data.get(CFG_DATA_RE).unwrap().get(url) {
if post.get("removed").is_some() {
send_embed_for_removed(ctx, url, post).await;
return;
+11 -1
View File
@@ -1,7 +1,7 @@
use regex::Regex;
use serde_json::Value;
use crate::{messages::{make_post_embed, make_removed_embed, send_embed}, Context, Error};
use crate::{data::get_mutex_data, messages::{make_post_embed, make_removed_embed, send_embed}, Context, Error};
pub fn is_bk_mod(mod_list: Vec<u64>, uid: u64) -> bool {
return mod_list.contains(&uid);
@@ -31,4 +31,14 @@ pub async fn send_embed_for_removed(ctx: Context<'_>, url: &str, post: &Value) {
make_removed_embed(post, url, true),
true
).await;
}
pub async fn get_readable_subreddits(ctx: Context<'_>) -> Result<String, Error> {
let d = get_mutex_data(&ctx.data().cfg).await?;
let sr = d["reddit"]["subreddits"].as_str().ok_or("Item of key \"subreddit\" is not a string type.\nTrace: get_readable_subreddits -> let sr = ...")?;
let split: Vec<&str> = sr.split("+").collect();
let join = split.join(", r/");
return Ok(join);
}
+2 -2
View File
@@ -1,6 +1,6 @@
use serde_json::Value;
use crate::{data::{self, get_mutex_data}, lang, messages::send_msg, re_cmds::generic_fns::send_embed_for_post, rs_println, Context, Error, BK_WEEK};
use crate::{data::{self, get_mutex_data}, lang, messages::send_msg, re_cmds::generic_fns::send_embed_for_post, rs_println, Context, Error, CFG_DATA_RE};
use super::generic_fns::send_embed_for_removed;
@@ -30,7 +30,7 @@ pub async fn cmd(
async fn get_post_from_data(ctx: Context<'_>, reddit_data: &Value, url: &str) -> Result<Option<Value>, Error> {
if let Some(bk_week) = reddit_data.get(BK_WEEK) {
if let Some(bk_week) = reddit_data.get(CFG_DATA_RE) {
if let Some(post) = bk_week.get(url) {
if post.get("removed").is_some() {
send_embed_for_removed(ctx, url, post).await;
+3 -2
View File
@@ -1,6 +1,6 @@
use serde_json::json;
use crate::{lang, messages::send_msg, re_cmds::generic_fns::is_bk_mod, websocket::send_cmd_json, Context, Error};
use crate::{lang, messages::send_msg, re_cmds::generic_fns::{get_readable_subreddits, is_bk_mod}, websocket::send_cmd_json, Context, Error};
#[poise::command(
slash_command,
@@ -17,7 +17,8 @@ pub async fn cmd(
) -> Result<(), Error>
{
if !is_bk_mod(ctx.data().bk_mods.clone(), ctx.author().id.get()) {
send_msg(ctx, lang!("dc_msg_re_permdeny_not_re_mod"), false, false).await;
let sr = get_readable_subreddits(ctx).await?;
send_msg(ctx, lang!("dc_msg_re_permdeny_not_re_mod", sr), false, false).await;
return Ok(());
}
+2 -2
View File
@@ -1,6 +1,6 @@
use std::collections::HashMap;
use crate::{data::get_mutex_data, re_cmds::generic_fns::send_embed_for_post, Context, Error, BK_WEEK};
use crate::{data::get_mutex_data, re_cmds::generic_fns::send_embed_for_post, Context, Error, CFG_DATA_RE};
#[derive(poise::ChoiceParameter, PartialEq)]
enum TopCategory {
@@ -30,7 +30,7 @@ pub async fn cmd(
) -> Result<(), Error>
{
let mut all: HashMap<&str, i32> = HashMap::new();
let posts = &get_mutex_data(&ctx.data().reddit_data).await?[BK_WEEK];
let posts = &get_mutex_data(&ctx.data().reddit_data).await?[CFG_DATA_RE];
let posts_u = posts.as_object().unwrap();
for (url, dat) in posts_u {
+6 -6
View File
@@ -3,7 +3,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use poise::{serenity_prelude::{ChannelId, EditMessage, GetMessages, Http, Message, MessageId, UserId}, ReplyHandle};
use serde_json::{json, Map, Value};
use crate::{data::{self, get_mutex_data}, lang, messages::{edit_reply, embed_from_options, http_send_embed, make_post_embed, make_removed_embed, send_msg}, websocket::send_cmd_json, Context, Error, BK_WEEK};
use crate::{data::{self, get_mutex_data, DC_POSTS_CHANNEL_KEY}, lang, messages::{edit_reply, embed_from_options, http_send_embed, make_post_embed, make_removed_embed, send_msg}, websocket::send_cmd_json, Context, Error, CFG_DATA_RE};
#[poise::command(
slash_command,
@@ -27,7 +27,7 @@ pub async fn cmd(
{
let http = ctx.http();
let mut p_text = "`/bk_week_update`:".to_string();
let mut p_text = "`/re_updatediscord`:".to_string();
let progress = send_msg(ctx, p_text.clone(), true, true).await.unwrap();
p_text = update_progress(ctx, progress.clone(), p_text, "\nFetching new posts & updating data file...".to_string()).await;
@@ -42,7 +42,7 @@ pub async fn cmd(
let c_id_u = get_c_id(ctx).await;
if c_id_u.is_none() {
send_msg(ctx, "Could not find bk_week_channel in data!\nHint: Run (or tell an admin to run) `/bk_admin_bind` in a (preferably read-only) channel.".to_string(), true, true).await;
send_msg(ctx, lang!("dc_msg_re_posts_channel_404"), true, true).await;
return Ok(());
}
@@ -58,7 +58,7 @@ pub async fn cmd(
// Adding new posts
p_text = update_progress(ctx, progress.clone(), p_text.clone(), "\nAdding new posts...".to_string()).await;
let weekly_art = r_data[BK_WEEK].as_object().unwrap();
let weekly_art = r_data[CFG_DATA_RE].as_object().unwrap();
add_posts(http, c_id, weekly_art, &msgs_json, max_age_secs).await;
// Stop if only_add
@@ -113,7 +113,7 @@ async fn get_c_id(ctx: Context<'_>) -> Option<ChannelId> {
let c_id_u =
d["servers"]
[ctx.guild_id().unwrap().to_string()]
["bk_week_channel"].as_u64().unwrap();
[DC_POSTS_CHANNEL_KEY].as_u64().unwrap();
let c_id = ChannelId::new(c_id_u);
@@ -187,7 +187,7 @@ async fn msgs_to_json(msgs: Vec<Message>, reddit_data: &Value, max_age: u64) ->
if msg_json.is_err() { continue; }
let mut u_json: Value = msg_json.unwrap();
let re_url = &reddit_data[BK_WEEK][&url];
let re_url = &reddit_data[CFG_DATA_RE][&url];
let post_date = re_url["post_data"]["date_unix"].as_u64().unwrap_or(0);
+2 -2
View File
@@ -1,6 +1,6 @@
use serde_json::json;
use crate::{data::{self, get_mutex_data}, lang, messages::send_msg, re_cmds::generic_fns::{is_bk_mod, send_embed_for_removed}, websocket::send_cmd_json, Context, Error, BK_WEEK};
use crate::{data::{self, get_mutex_data}, lang, messages::send_msg, re_cmds::generic_fns::{is_bk_mod, send_embed_for_removed}, websocket::send_cmd_json, Context, Error, CFG_DATA_RE};
#[poise::command(
slash_command,
@@ -19,7 +19,7 @@ pub async fn cmd(
data::update_re_data(ctx.data()).await;
let uid = ctx.author().id.get();
let re_data = get_mutex_data(&ctx.data().reddit_data).await?;
let post_data = re_data[BK_WEEK].clone();
let post_data = re_data[CFG_DATA_RE].clone();
let unw_vote = un_vote.unwrap_or(false);
if post_data.get(&url).is_none() {
+1 -1
View File
@@ -5,7 +5,7 @@ use std::time::Duration;
use tokio::task::JoinHandle;
use tokio::time;
use crate::{lang, rs_println};
use crate::rs_println;
pub type Schedule = (Duration, fn() -> Pin<Box<dyn Future<Output = ()> + Send>>);