diff --git a/data/lang/en.json b/data/lang/en.json index 7f15a58..39a44cf 100644 --- a/data/lang/en.json +++ b/data/lang/en.json @@ -1,78 +1,37 @@ { - "dc_btn_approve": "Approve", - "dc_btn_remove": "Remove", - "dc_btn_unapprove": "Disapprove", - "dc_btn_unremove": "Restore", - "dc_btn_unvote": "Un-vote", - "dc_btn_vote": "Vote", - "dc_msg_8-ball_answer": "**8-ball Question:** {0}\n**Answer:** {1}", - "dc_msg_add_to_data": "Added your server to my data! Thanks for letting me steal it! (/s)", - "dc_msg_bound_channel": "Successfully added channel ID `{0}` to the database!", - "dc_msg_cmd_404": "No command \"{0}\" found!\nHint: Try `/help` without any arguments or `/help `", - "dc_msg_corrupted_data": "Oopsies `(。>\\\\<)`. It looks like my data i-is \\**sob*\\*... c-corrupted!", - "dc_msg_data_server_404": "This server is not in the data!\n Hint: Run the command `/database AddServer` inside of a Discord server (requires administrator permission).", - "dc_msg_dm_python_err_socket": "Unknown internal Python error occurred: Websocket response error", - "dc_msg_dm_python_err": "Unknown internal Python Error:\n```\n{0}\n```", - "dc_msg_embed_default_embed_desc": "Default english embed description.", - "dc_msg_embed_re_post": "Spoilers and vote length anonymizer for fair review!\n## Post Data:\n**Subreddit:** {0}\n**Post upvotes:** ||`{1:>6}`||\n**Moderator votes:** ||`{2:>6}`||\n**Media type:** `{3}`\n## Listing Data:\n**Added by:** human: {4} | bot: {5}\n**Approved:** {6}", - "dc_msg_embed_re_removed": "## Removed by `{0}`\n**Reason:** {1}", - "dc_msg_err_trace": "Unknown error!\nError trace: {0}", - "dc_msg_failed_shorturl_conversion": "Couldn't convert to shortURL: Invalid Reddit URL format.", - "dc_msg_mandatory_response": "Mandatory response message, please ignore.", - "dc_msg_no_perms": "Missing permission in that server: {0}", - "dc_msg_not_in_guild": "I am not a part of that guild.", - "dc_msg_owner_data_save_complete": "Saving data... Done!", - "dc_msg_owner_data_save": "Saving data...", - "dc_msg_owner_shutdown": "Shutting down...", - "dc_msg_owner_shutdown_failed_confirmation": "Failed to shut down: Invalid confirmation.", - "dc_msg_re_already_voted": "Couldn't cast a vote: You have already voted on this post!", - "dc_msg_re_also_approved": "Also approved it!", - "dc_msg_re_data_corrupted": "Post URL \"<{0}>\" not found: Post data is corrupted!\n Full details: Could not find key \"posts\" in data file \"re_data.json\"", - "dc_msg_re_help_removed": "Reddit help file not found, someone likely deleted it.\n Hint: You can find the official help text at https://github.com/ByteDice/ByteDiceAssistant in `re_help.md`.\n**CAUTION:** The official help file may contain incorrect information if you're not using the official bot by Byte Dice.", - "dc_msg_re_permdeny_not_re_mod": "Permission denied: You are not a moderator of the subreddit(s) {0}", - "dc_msg_re_post_404": "Post URL \"<{0}>\" not found: Post doesn't exist in the data!\n Hint: Run the command `/re_addpost [URL]` in a Discord channel or `u/ByteDiceAssistant add_post` in a Reddit post.", - "dc_msg_re_post_add_success": "Added post with URL \"<{0}>\"!", - "dc_msg_re_post_approve_remove": "Couldn't approve the post because it has been removed!", - "dc_msg_re_post_approve_success": "Successfully approved the post!", - "dc_msg_re_post_disapprove_success": "Successfully disapproved the post!", - "dc_msg_re_post_remove_success": "Successfully removed post with URL \"<{0}>\"!", - "dc_msg_re_post_unremove_success": "Successfully restored post with URL \"<{0}>\"!", - "dc_msg_re_post_update_success": "Updated post with URL \"<{0}>\"!", - "dc_msg_re_post_vote_removed_post": "Couldn't [vote / un-vote] the post because it has been removed!", - "dc_msg_re_posts_channel_404": "Could not find `re_posts_channel` in data!\nHint: Run `/database RedditChannel` in a (preferably read-only) channel (requires administrator permission).", - "dc_msg_re_vote_err": "Failed to [vote / un-vote]: Unknown internal error.", - "dc_msg_re_vote_mod_success": "Successfully voted (as moderator vote)!", - "dc_msg_re_vote_remove_havent": "Couldn't remove your vote: You haven't voted on this post yet!", - "dc_msg_re_vote_remove_success": "Successfully removed vote!", - "dc_msg_re_vote_success": "Successfully voted!", - "dc_msg_reload_cfg_python_fail": "Failed to reload configs: Failed-type response from Python.", - "dc_msg_reload_cfg_success": "Successfully reloaded the configs!\nNew configs:\n```\n{0}\n```", - "dc_msg_removed_square_brackets": "[REMOVED] {0}", - "dc_msg_shorturl": "ShortURL: <{0}>", - "dc_msg_update_add": "{0}Adding new posts...", - "dc_msg_update_done": "{0}Done!", - "dc_msg_update_editing": "{0}Editing updated posts...", - "dc_msg_update_fetch": "{0}Fetching new posts & updating data file...", - "dc_msg_update_parse": "{0}Parsing messages to JSON...", - "dc_msg_update_read": "{0}Reading messages in <#{1}>...", - "dc_msg_update_removing_dupe": "{0}Removing duplicate posts...", - "dc_msg_update_removing_old": "{0}Removing old posts (threshold: {1}d)...", - "dc_msg_update_removing": "{0}Removing removed posts...", - "dc_msg_whoami": "**Bot \"owner\":** {0}\n**BK moderator:** {1}", - "dc_msg_wwrps_already_submitted": "You can't compete against yourself! Please wait until another player has submitted their RPS.", - "dc_msg_wwrps_anon": "[Anonymous]", - "dc_msg_wwrps_draw": "DRAW", - "dc_msg_wwrps_fight": "### {0} (P1) vs {1} (P2)...\n## {2}\n**P1:** {3}\n**P2:** {4}", - "dc_msg_wwrps_not_in_data": "Could not find `wwrps_channel` in data!\nHint: Run `/database WWRPSChannel` in a channel (requires administrator permission).", - "dc_msg_wwrps_left_win": "P1 WINS", - "dc_msg_wwrps_right_win": "P2 WINS", - "dc_msg_wwrps_submitting": "Submitting your RPS... Please wait for another contestant to compete against you.", - "log_lang_load_success": "Successfully loaded the english language file!", - "none": "None", - "py_re_response_suffix": "^(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)!)", - "py_re_response_weekly_add": "Successfully added your post to the weekly art submissions! Thank you for participating!", - "py_re_response_weekly_exists": "Couldn't add this post to the submissions! Luckily, it's already there! Thank you for participating!", - "py_re_response_weekly_mod_add": "[MOD ACTION] Successfully added this post to the weekly art submissions!", - "py_re_response_weekly_mod_unremove": "[MOD ACTION] Successfully un-removed this post from the weekly art submissions!", - "success": "Success!" + "generic": { + "none": "None" + }, + "dc": { + "re": { + "buttons": { + "approve": "Approve", + "remove": "Remove", + "disapprove": "Disapprove", + "unremove": "Restore", + "vote": "Vote", + "unvote": "Un-vote" + }, + "approve": { + "success": "Successfully approved the post!", + "disapprove": "Successfully disapproved the post!", + "post_removed": "Couldn't approve the post because it has been removed!" + }, + "remove": { + "success": "Successfully removed post with URL \"<{0}>\"!", + "unremove": "Successfully restored post with URL \"<{0}>\"!" + }, + "vote": { + "success": "Successfully voted!", + "removed": "Successfully removed vote!", + "mod": "Successfully voted (as moderator vote)!", + "post_removed": "Couldn't [vote / un-vote] the post because the post has been removed!", + "remove_hasnt_voted": "Couldn't remove your vote: You haven't voted on this post yet!" + }, + "embed": { + "post": "Spoilers and vote length anonymizer for fair review!\n## Post Data:\n**Subreddit:** {0}\n**Post upvotes:** ||`{1:>6}`||\n**Moderator votes:** ||`{2:>6}`||\n**Media type:** `{3}`\n## Listing Data:\n**Added by:** human: {4} | bot: {5}\n**Approved:** {6}", + "post_removed": "## Removed by `{0}`\n**Reason:** {1}" + } + } + } } \ No newline at end of file diff --git a/data/lang/en_deprecated.json b/data/lang/en_deprecated.json new file mode 100644 index 0000000..eda264d --- /dev/null +++ b/data/lang/en_deprecated.json @@ -0,0 +1,78 @@ +{ + //"dc_btn_approve": "Approve", + //"dc_btn_remove": "Remove", + //"dc_btn_unapprove": "Disapprove", + //"dc_btn_unremove": "Restore", + //"dc_btn_unvote": "Un-vote", + //"dc_btn_vote": "Vote", + "dc_msg_8-ball_answer": "**8-ball Question:** {0}\n**Answer:** {1}", + "dc_msg_add_to_data": "Added your server to my data! Thanks for letting me steal it! (/s)", + "dc_msg_bound_channel": "Successfully added channel ID `{0}` to the database!", + "dc_msg_cmd_404": "No command \"{0}\" found!\nHint: Try `/help` without any arguments or `/help `", + "dc_msg_corrupted_data": "Oopsies `(。>\\\\<)`. It looks like my data i-is \\**sob*\\*... c-corrupted!", + "dc_msg_data_server_404": "This server is not in the data!\n Hint: Run the command `/database AddServer` inside of a Discord server (requires administrator permission).", + //"dc_msg_dm_python_err_socket": "Unknown internal Python error occurred: Websocket response error", + //"dc_msg_dm_python_err": "Unknown internal Python Error:\n```\n{0}\n```", + //"dc_msg_embed_default_embed_desc": "Default english embed description.", + //"dc_msg_embed_re_post": "Spoilers and vote length anonymizer for fair review!\n## Post Data:\n**Subreddit:** {0}\n**Post upvotes:** ||`{1:>6}`||\n**Moderator votes:** ||`{2:>6}`||\n**Media type:** `{3}`\n## Listing Data:\n**Added by:** human: {4} | bot: {5}\n**Approved:** {6}", + //"dc_msg_embed_re_removed": "## Removed by `{0}`\n**Reason:** {1}", + "dc_msg_err_trace": "Unknown error!\nError trace: {0}", + "dc_msg_failed_shorturl_conversion": "Couldn't convert to shortURL: Invalid Reddit URL format.", + "dc_msg_mandatory_response": "Mandatory response message, please ignore.", + "dc_msg_no_perms": "Missing permission in that server: {0}", + "dc_msg_not_in_guild": "I am not a part of that guild.", + "dc_msg_owner_data_save_complete": "Saving data... Done!", + "dc_msg_owner_data_save": "Saving data...", + "dc_msg_owner_shutdown": "Shutting down...", + "dc_msg_owner_shutdown_failed_confirmation": "Failed to shut down: Invalid confirmation.", + "dc_msg_re_already_voted": "Couldn't cast a vote: You have already voted on this post!", + "dc_msg_re_also_approved": "Also approved it!", + "dc_msg_re_data_corrupted": "Post URL \"<{0}>\" not found: Post data is corrupted!\n Full details: Could not find key \"posts\" in data file \"re_data.json\"", + "dc_msg_re_help_removed": "Reddit help file not found, someone likely deleted it.\n Hint: You can find the official help text at https://github.com/ByteDice/ByteDiceAssistant in `re_help.md`.\n**CAUTION:** The official help file may contain incorrect information if you're not using the official bot by Byte Dice.", + "dc_msg_re_permdeny_not_re_mod": "Permission denied: You are not a moderator of the subreddit(s) {0}", + "dc_msg_re_post_404": "Post URL \"<{0}>\" not found: Post doesn't exist in the data!\n Hint: Run the command `/re_addpost [URL]` in a Discord channel or `u/ByteDiceAssistant add_post` in a Reddit post.", + "dc_msg_re_post_add_success": "Added post with URL \"<{0}>\"!", + //"dc_msg_re_post_approve_remove": "Couldn't approve the post because it has been removed!", + //"dc_msg_re_post_approve_success": "Successfully approved the post!", + //"dc_msg_re_post_disapprove_success": "Successfully disapproved the post!", + //"dc_msg_re_post_remove_success": "Successfully removed post with URL \"<{0}>\"!", + "dc_msg_re_post_unremove_success": "Successfully restored post with URL \"<{0}>\"!", + "dc_msg_re_post_update_success": "Updated post with URL \"<{0}>\"!", + //"dc_msg_re_post_vote_removed_post": "Couldn't [vote / un-vote] the post because it has been removed!", + "dc_msg_re_posts_channel_404": "Could not find `re_posts_channel` in data!\nHint: Run `/database RedditChannel` in a (preferably read-only) channel (requires administrator permission).", + "dc_msg_re_vote_err": "Failed to [vote / un-vote]: Unknown internal error.", + //"dc_msg_re_vote_mod_success": "Successfully voted (as moderator vote)!", + //"dc_msg_re_vote_remove_havent": "Couldn't remove your vote: You haven't voted on this post yet!", + //"dc_msg_re_vote_remove_success": "Successfully removed vote!", + //"dc_msg_re_vote_success": "Successfully voted!", + "dc_msg_reload_cfg_python_fail": "Failed to reload configs: Failed-type response from Python.", + "dc_msg_reload_cfg_success": "Successfully reloaded the configs!\nNew configs:\n```\n{0}\n```", + "dc_msg_removed_square_brackets": "[REMOVED] {0}", + "dc_msg_shorturl": "ShortURL: <{0}>", + "dc_msg_update_add": "{0}Adding new posts...", + "dc_msg_update_done": "{0}Done!", + "dc_msg_update_editing": "{0}Editing updated posts...", + "dc_msg_update_fetch": "{0}Fetching new posts & updating data file...", + "dc_msg_update_parse": "{0}Parsing messages to JSON...", + "dc_msg_update_read": "{0}Reading messages in <#{1}>...", + "dc_msg_update_removing_dupe": "{0}Removing duplicate posts...", + "dc_msg_update_removing_old": "{0}Removing old posts (threshold: {1}d)...", + "dc_msg_update_removing": "{0}Removing removed posts...", + "dc_msg_whoami": "**Bot \"owner\":** {0}\n**BK moderator:** {1}", + "dc_msg_wwrps_already_submitted": "You can't compete against yourself! Please wait until another player has submitted their RPS.", + "dc_msg_wwrps_anon": "[Anonymous]", + "dc_msg_wwrps_draw": "DRAW", + "dc_msg_wwrps_fight": "### {0} (P1) vs {1} (P2)...\n## {2}\n**P1:** {3}\n**P2:** {4}", + "dc_msg_wwrps_not_in_data": "Could not find `wwrps_channel` in data!\nHint: Run `/database WWRPSChannel` in a channel (requires administrator permission).", + "dc_msg_wwrps_left_win": "P1 WINS", + "dc_msg_wwrps_right_win": "P2 WINS", + "dc_msg_wwrps_submitting": "Submitting your RPS... Please wait for another contestant to compete against you.", + "log_lang_load_success": "Successfully loaded the english language file!", + "none": "None", + "py_re_response_suffix": "^(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)!)", + "py_re_response_weekly_add": "Successfully added your post to the weekly art submissions! Thank you for participating!", + "py_re_response_weekly_exists": "Couldn't add this post to the submissions! Luckily, it's already there! Thank you for participating!", + "py_re_response_weekly_mod_add": "[MOD ACTION] Successfully added this post to the weekly art submissions!", + "py_re_response_weekly_mod_unremove": "[MOD ACTION] Successfully un-removed this post from the weekly art submissions!", + "success": "Success!" +} \ No newline at end of file diff --git a/src/events.rs b/src/events.rs index b85671b..353c66f 100644 --- a/src/events.rs +++ b/src/events.rs @@ -1,9 +1,10 @@ use crate::db::reddit::update_data; use crate::r#gen::set_status; +use crate::lang::Lang; use crate::messages::{make_post_embed, make_removed_embed, EmbedOptions}; use crate::cmds::reddit::generic_fns::{is_bk_mod, is_bk_mod_serenity, serenity_edit_msg_embed, serenity_send_msg}; use crate::websocket::send_cmd_json; -use crate::{Data, Error, lang, rs_println}; +use crate::{Data, Error, rs_println}; use crate::db::reddit::POSTS_KEY; use poise::serenity_prelude::{self as serenity, ChannelId, ComponentInteraction, Interaction, Member, MessageId, Ready}; @@ -67,11 +68,11 @@ async fn handle_buttons(ctx: &serenity::Context, data: &Data, interaction: &Inte } -async fn update_embed(ctx: &serenity::Context, url: &str, new_data: &Value, c_id: &ChannelId, m_id: &MessageId) { +async fn update_embed(ctx: &serenity::Context, lang: &Lang, url: &str, new_data: &Value, c_id: &ChannelId, m_id: &MessageId) { let remove = new_data["removed"]["removed"].as_bool().unwrap(); let e: EmbedOptions = - if remove { make_removed_embed(new_data, url, true) } - else { make_post_embed (new_data, url, true) }; + if remove { make_removed_embed(lang, new_data, url, true) } + else { make_post_embed (lang, new_data, url, true) }; serenity_edit_msg_embed(ctx, c_id, m_id, e).await; } @@ -89,19 +90,14 @@ async fn approve_btn(ctx: &serenity::Context, data: &Data, c_member: &Member, co let new_data = &data.reddit_data .lock().await[POSTS_KEY][&url]; - update_embed(ctx, &url, new_data, &c_id, &m_id).await; + update_embed(ctx, &data.lang, &url, new_data, &c_id, &m_id).await; if r["value"].as_bool().unwrap() { - if approve { - serenity_send_msg(ctx, component, lang!("dc_msg_re_post_approve_success"), true).await; - } - else { - serenity_send_msg(ctx, component, lang!("dc_msg_re_post_disapprove_success"), true).await; - } - } - else { - serenity_send_msg(ctx, component, lang!("dc_msg_re_post_approve_remove"), true).await; + if approve + { serenity_send_msg(ctx, component, data.lang.get("dc.re.approve.disapprove", &[]), true).await; } + else { serenity_send_msg(ctx, component, data.lang.get("dc.re.approve.success", &[]), true).await; } } + else { serenity_send_msg(ctx, component, data.lang.get("dc.re.approve.post_removed", &[]), true).await; } return Ok(()); } @@ -110,12 +106,9 @@ async fn approve_btn(ctx: &serenity::Context, data: &Data, c_member: &Member, co async fn remove_btn(ctx: &serenity::Context, data: &Data, c_member: &Member, component: &ComponentInteraction, url: String, remove: bool) -> Result<(), Error> { if !is_bk_mod_serenity(ctx, data, c_member, component).await { return Ok(()); } - let r: Value = if remove { - send_cmd_json("remove_post_url", Some(json!([&url, &c_member.user.name, None::])), true).await.unwrap() - } - else { - send_cmd_json("add_post_url", Some(json!([&url, false, true])), true).await.unwrap() - }; + let r: Value = + if remove { send_cmd_json("remove_post_url", Some(json!([&url, &c_member.user.name, None::])), true).await.unwrap() } + else { send_cmd_json("add_post_url", Some(json!([&url, false, true])), true).await.unwrap() }; let c_id = component.channel_id; let m_id = component.message.id; @@ -124,15 +117,11 @@ async fn remove_btn(ctx: &serenity::Context, data: &Data, c_member: &Member, com let new_data = &data.reddit_data .lock().await[POSTS_KEY][&url]; - update_embed(ctx, &url, new_data, &c_id, &m_id).await; + update_embed(ctx, &data.lang, &url, new_data, &c_id, &m_id).await; if r["value"].as_bool().unwrap() { - if remove { - serenity_send_msg(ctx, component, lang!("dc_msg_re_post_remove_success", &url), true).await; - } - else { - serenity_send_msg(ctx, component, lang!("dc_msg_re_post_unremove_success", &url), true).await; - } + if remove { serenity_send_msg(ctx, component, data.lang.get("dc.re.remove.success", &[url]), true).await; } + else { serenity_send_msg(ctx, component, data.lang.get("dc.re.remove.unremove", &[url]), true).await; } } return Ok(()); @@ -152,22 +141,22 @@ async fn vote_btn(ctx: &serenity::Context, data: &Data, c_member: &Member, compo let new_data = &data.reddit_data .lock().await[POSTS_KEY][&url]; - update_embed(ctx, &url, new_data, &c_id, &m_id).await; + update_embed(ctx, &data.lang, &url, new_data, &c_id, &m_id).await; if r["value"].as_bool().unwrap() { if vote { - if is_mod { serenity_send_msg(ctx, component, lang!("dc_msg_re_vote_mod_success"), true).await; } - else { serenity_send_msg(ctx, component, lang!("dc_msg_re_vote_success"), true).await; } + if is_mod { serenity_send_msg(ctx, component, data.lang.get("dc.re.vote.mod", &[]), true).await; } + else { serenity_send_msg(ctx, component, data.lang.get("dc.re.vote.success", &[]), true).await; } } else { - serenity_send_msg(ctx, component, lang!("dc_msg_re_vote_remove_success"), true).await; + serenity_send_msg(ctx, component, data.lang.get("dc.re.vote.removed", &[]), true).await; } } else if new_data["removed"]["removed"].as_bool().unwrap() { - serenity_send_msg(ctx, component, lang!("dc_msg_re_post_vote_removed_post"), true).await; + serenity_send_msg(ctx, component, data.lang.get("dc.re.vote.post_removed", &[]), true).await; } else if !vote { - serenity_send_msg(ctx, component, lang!("dc_msg_re_vote_remove_havent"), true).await; + serenity_send_msg(ctx, component, data.lang.get("dc.re.vote.remove_hasnt_voted", &[]), true).await; } return Ok(()); diff --git a/src/gen.rs b/src/gen.rs index 2f152d7..0fde4c0 100644 --- a/src/gen.rs +++ b/src/gen.rs @@ -1,3 +1,4 @@ +use std::path::PathBuf; use std::{collections::HashSet, process}; use poise::serenity_prelude::{ActivityData, UserId}; @@ -24,14 +25,19 @@ pub async fn gen_data(args: Args, env_vars: AssistantEnv) -> Data { let dc_data = discord::read_data(args.clone().wipe).await; let cf_data = cfg:: read_data(args.clone().wipe).await; + let cf_bind = cf_data.clone(); + let lang_name = cf_bind["general"]["lang"].as_str().unwrap(); + let lang_path = ["./data/lang/", lang_name, ".json"].concat(); + let lang_pathbuf = PathBuf::from(lang_path); + return Data { args: args.clone(), ball_prompts: [ball_classic, ball_quirk], cfg: cf_data, discord_data: dc_data.into(), env_vars: env_vars, - lang_name: "".to_string().into(), - lang: Lang::new().into(), + lang_name: lang_name.to_string(), + lang: Lang::from_file(lang_pathbuf).unwrap(), reddit_data: re_data.into(), rps_game: Mutex::new(RPSGame::new()) }; diff --git a/src/macros.rs b/src/macros.rs index 6b4724d..e57f08b 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -59,43 +59,4 @@ macro_rules! warnln { format!($($arg)*) ); }; -} - - -#[macro_export] -macro_rules! lang { - ($key:expr) => { - { - /*use $crate::{LANG, errln}; - let value = unsafe { - LANG - .as_ref() - .expect("LANG must be initialized before use") - .get($key) - }; - - if value.is_none() { errln!("Key not found in LANG JSON: \"{}\"", $key); } - - value.unwrap().as_str().expect("LANG JSON value is not a string!").to_string()*/ - - "hello".to_string() - } - }; - ($key:expr, $($arg:expr),*) => {{ - /*use $crate::{LANG, errln}; - use formatx::formatx; - - let value = unsafe { - LANG - .as_ref() - .expect("LANG must be initialized before use") - .get($key) - }; - - if value.is_none() { errln!("Key not found in LANG JSON: \"{}\"", $key); } - - let format_str = value.unwrap().as_str().expect("LANG JSON value is not a string!"); - formatx!(format_str, $($arg),*).unwrap()*/ - "hello".to_string() - }}; } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 2191338..4f8c60e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -48,7 +48,7 @@ async fn main() { rs_println!("Generating and/or fetching data and config..."); let data = gen_data(args, env_vars).await; - rs_println!("[IMPORTANT] The below message is a test message, it should be written in the language you've selected\nTest message: {}", lang!("log_lang_load_success")); + rs_println!("[IMPORTANT] The below message is a test message, it should be written in the language you've selected\nTest message: {}", data.lang.get("log_lang_load_success", &[])); // We start this here cuz we have all the data that we need if data.args.py && !data.args.rs { diff --git a/src/messages.rs b/src/messages.rs index 4d695c7..d7c34b6 100644 --- a/src/messages.rs +++ b/src/messages.rs @@ -1,7 +1,8 @@ use std::io::{Read, Write}; use crate::db::bot_data::Data; -use crate::{lang, Context}; +use crate::Context; +use crate::lang::Lang; use base64::engine::general_purpose; use base64::Engine; @@ -36,7 +37,7 @@ pub struct EmbedOptions { impl Default for EmbedOptions { fn default() -> Self { return EmbedOptions { - desc: lang!("dc_msg_embed_default_embed_desc"), + desc: "Default english embed description.".to_string(), title: None, col: None, url: None, @@ -226,19 +227,19 @@ pub async fn send_dm_min(msg: String, token: String, bot_owners: Vec) { } -pub fn make_post_embed(post_data: &Value, url: &str, ephemeral: bool) -> EmbedOptions { +pub fn make_post_embed(lang: &Lang, post_data: &Value, url: &str, ephemeral: bool) -> EmbedOptions { let media_type = &post_data["post_data"]["media_type"]; - let desc_str = lang!( - "dc_msg_embed_re_post", - post_data["post_data"]["subreddit"].as_str().unwrap(), - post_data["post_data"]["upvotes"].as_i64().unwrap(), - post_data["votes"]["mod_voters"].as_array().unwrap().len(), + let desc_str = lang.get( + "dc.re.embed.post", + &[post_data["post_data"]["subreddit"].as_str().unwrap(), + post_data["post_data"]["upvotes"].as_i64().unwrap().to_string().as_str(), + post_data["votes"]["mod_voters"].as_array().unwrap().len().to_string().as_str(), if !media_type.is_null() { media_type.as_str().unwrap() } else { "None" }, if post_data["added"] ["by_human"].as_bool().unwrap() { "✅" } else { "❌" }, if post_data["added"] ["by_bot"].as_bool().unwrap() { "✅" } else { "❌" }, - if post_data["approved"]["by_human"].as_bool().unwrap() { "✅" } else { "❌" } + if post_data["approved"]["by_human"].as_bool().unwrap() { "✅" } else { "❌" }].map(String::from) ); let trimmed = desc_str @@ -248,7 +249,7 @@ pub fn make_post_embed(post_data: &Value, url: &str, ephemeral: bool) -> EmbedOp .join("\n"); let media_urls = post_data["post_data"]["media_urls"].as_array().unwrap(); - let action_row = make_post_components(); + let action_row = make_post_components(lang); let json_encoded = trim_compress_and_encode_json(post_data); @@ -268,25 +269,25 @@ pub fn make_post_embed(post_data: &Value, url: &str, ephemeral: bool) -> EmbedOp } -pub fn make_removed_embed(post_data: &Value, url: &str, ephemeral: bool) -> EmbedOptions { - let action_row = make_removed_components(); +pub fn make_removed_embed(lang: &Lang, post_data: &Value, url: &str, ephemeral: bool) -> EmbedOptions { + let action_row = make_removed_components(lang); - let none = lang!("none"); + let none = lang.get("generic.none", &[]); - let desc = lang!( - "dc_msg_embed_re_removed", - if !post_data["removed"]["by"].is_null() + let desc = lang.get( + "dc.re.embed.post_removed", + &[if !post_data["removed"]["by"].is_null() { post_data["removed"]["by"].as_str().unwrap() } else { &none }, if !post_data["removed"]["reason"].is_null() { post_data["removed"]["reason"].as_str().unwrap() } - else { &none } + else { &none }].map(String::from) ); let json_encoded = trim_compress_and_encode_json(post_data); return EmbedOptions { - title: Some(lang!("dc_msg_removed_square_brackets", post_data["post_data"]["title"].clone())), + title: Some(lang.get("dc_msg_removed_square_brackets", &[post_data["post_data"]["title"].clone().to_string()])), desc: format!("{}\n\n{}{}{}", desc, JSON_TEXT_START, json_encoded, JSON_TEXT_END), col: Some(REMOVED_DC_COL), url: Some(url.to_string()), @@ -341,19 +342,19 @@ pub fn decode_and_decompress_json(t: String) -> Result } -fn make_post_components() -> CreateActionRow { +fn make_post_components(lang: &Lang) -> CreateActionRow { return CreateActionRow::Buttons(vec![ - CreateButton::new("vote_btn") .label(lang!("dc_btn_vote")) .emoji(ReactionType::Unicode("⬆️".to_string())), - CreateButton::new("unvote_btn") .label(lang!("dc_btn_unvote")), - CreateButton::new("approve_btn") .label(lang!("dc_btn_approve")) .emoji(ReactionType::Unicode("✅".to_string())), - CreateButton::new("unapprove_btn").label(lang!("dc_btn_unapprove")) .emoji(ReactionType::Unicode("❌".to_string())), - CreateButton::new("remove_btn") .label(lang!("dc_btn_remove")) .emoji(ReactionType::Unicode("🗑️".to_string())) + CreateButton::new("vote_btn") .label(lang.get("dc.re.buttons.vote", &[])).emoji(ReactionType::Unicode("⬆️".to_string())), + CreateButton::new("unvote_btn") .label(lang.get("dc.re.buttons.unvote", &[])), + CreateButton::new("approve_btn") .label(lang.get("dc.re.buttons.approve", &[])).emoji(ReactionType::Unicode("✅".to_string())), + CreateButton::new("unapprove_btn").label(lang.get("dc.re.buttons.disapprove", &[])).emoji(ReactionType::Unicode("❌".to_string())), + CreateButton::new("remove_btn") .label(lang.get("dc.re.buttons.remove", &[])).emoji(ReactionType::Unicode("🗑️".to_string())) ]); } -fn make_removed_components() -> CreateActionRow { +fn make_removed_components(lang: &Lang) -> CreateActionRow { return CreateActionRow::Buttons(vec![ - CreateButton::new("unremove_btn").label(lang!("dc_btn_unremove")).emoji(ReactionType::Unicode("↩️".to_string())) + CreateButton::new("unremove_btn").label(lang.get("dc.re.buttons.unremove", &[])).emoji(ReactionType::Unicode("↩️".to_string())) ]); } \ No newline at end of file diff --git a/src/python.rs b/src/python.rs index 072e620..d526a7a 100644 --- a/src/python.rs +++ b/src/python.rs @@ -1,7 +1,7 @@ use crate::db::env_vars::AssistantEnv; use crate::db::terminal_args::Args; use crate::messages::send_dm_min; -use crate::{errln, lang, rs_println}; +use crate::{errln, rs_println}; use std::fs; use std::ffi::CString; @@ -57,7 +57,7 @@ pub async fn start(args: Args, lang_name: String, env_vars: AssistantEnv) -> PyR if is_error { send_dm_min( - lang!("dc_msg_dm_python_err", traceback), + format!("Unknown internal Python Error:\n```\n{0}\n```", traceback), env_vars.token.clone(), env_vars.bot_owners.clone() ).await; diff --git a/src/websocket.rs b/src/websocket.rs index c2974d4..cf31eb4 100644 --- a/src/websocket.rs +++ b/src/websocket.rs @@ -10,7 +10,7 @@ use serde_json::{Value, json}; use crate::db::bot_data::Data; use crate::messages::send_dm_min; -use crate::{lang, rs_println}; +use crate::rs_println; use crate::Args; type Sender = Arc, tungstenite::Message>>>>; @@ -142,7 +142,7 @@ async fn handle_connections( async fn handle_message( msg: tungstenite::protocol::Message, token: String, - bot_owners: Vec + bot_owners: Vec, ) { match msg { tungstenite::Message::Text(text) => { @@ -152,7 +152,7 @@ async fn handle_message( let t_json: Value = serde_json::from_str(stripped).unwrap(); if t_json.get("error").is_some() { send_dm_min( - lang!("dc_msg_dm_python_err_socket"), + "Unknown internal Python error occurred: Websocket response error".to_string(), token, bot_owners ).await;