From a23cd73b48c9e4dc12897d2fe153c5bc8991158e Mon Sep 17 00:00:00 2001 From: ByteDice Date: Wed, 5 Mar 2025 20:02:40 +0100 Subject: [PATCH] made clippy happy. Hopefully didnt break anything as well --- src/bk_week_cmds.rs | 47 +++++++++++++++++++++------------------------ src/cmds.rs | 19 +++++++++--------- src/data.rs | 3 +-- src/main.rs | 20 ++++++++----------- src/messages.rs | 8 ++++---- src/python.rs | 4 ++-- src/websocket.rs | 14 +++++++------- 7 files changed, 53 insertions(+), 62 deletions(-) diff --git a/src/bk_week_cmds.rs b/src/bk_week_cmds.rs index fd0214a..ce24aae 100644 --- a/src/bk_week_cmds.rs +++ b/src/bk_week_cmds.rs @@ -175,13 +175,13 @@ pub async fn bk_week_add( } let shorturl_u = cmds::to_shorturl(&url); - let shorturl = if shorturl_u.is_ok() { shorturl_u.unwrap() } else { url }; + let shorturl = &shorturl_u.unwrap_or(url.clone()); 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) { - let a = approve.unwrap_or_else(|| false); + let a = approve.unwrap_or(false); let r = websocket::send_cmd_json("add_post_url", Some(json!([&shorturl, a, true]))).await.unwrap(); if !r["value"].as_bool().unwrap() { @@ -196,12 +196,12 @@ pub async fn bk_week_add( return Ok(()); } - if let Some(post) = bk_week.get(&shorturl) { + if let Some(post) = bk_week.get(shorturl) { if post.get("removed").is_some() { - send_unremove_msg(ctx, &shorturl).await; + send_unremove_msg(ctx, shorturl).await; } else { - send_updated_msg(ctx, &shorturl).await; + send_updated_msg(ctx, shorturl).await; } } else { @@ -287,16 +287,16 @@ pub async fn bk_week_approve( data::update_re_data(ctx.data()).await; let reddit_data = get_mutex_data(&ctx.data().reddit_data).await?; - approve_cmd(ctx, &url, &reddit_data, !disapprove.unwrap_or_else(|| false)).await; + approve_cmd(ctx, &url, &reddit_data, !disapprove.unwrap_or(false)).await; return Ok(()); } 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(BK_WEEK).unwrap().get(url) { if post.get("removed").is_some() { - send_post_removed_message(ctx, &url, post).await; + send_post_removed_message(ctx, url, post).await; return; } @@ -310,11 +310,11 @@ async fn approve_cmd(ctx: Context<'_>, url: &str, reddit_data: &Value, approve: } } else { - send_msg(ctx, format!("Unknown error!\nError trace: `bk_week_cmds.rs -> bk_week_approve() -> unwrap websocket result error`."), true, true).await; + send_msg(ctx, "Unknown error!\nError trace: `bk_week_cmds.rs -> bk_week_approve() -> unwrap websocket result error`.".to_string(), true, true).await; } } else { - send_post_not_found_message(ctx, &url).await; + send_post_not_found_message(ctx, url).await; } } @@ -379,7 +379,7 @@ pub async fn bk_week_update( 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; - let max_age_u = max_age.unwrap_or_else(|| 8); + let max_age_u = max_age.unwrap_or(8); let max_age_secs = max_age_u as u64 * (60 * 60 * 24); send_cmd_json("add_new_posts", Some(json!([max_age_secs]))).await; @@ -409,7 +409,7 @@ pub async fn bk_week_update( add_posts(http, c_id, weekly_art, &msgs_json, max_age_secs).await; // Stop if only_add - if only_add.unwrap_or_else(|| false) { + if only_add.unwrap_or(false) { send_msg(ctx, "`/bk_week_update`\n## Done!".to_string(), true, true).await; update_progress(ctx, progress.clone(), p_text, "✅\n## Done!".to_string()).await; return Ok(()); @@ -471,7 +471,7 @@ async fn get_c_id(ctx: Context<'_>) -> Option { async fn read_msgs(http: &Http, bot_id: UserId, c_id: ChannelId) -> Vec { let b = GetMessages::new().limit(100); let mut msgs = c_id.messages(http, b).await.unwrap(); - msgs = msgs.into_iter().filter(|item| item.author.id == bot_id).collect(); + msgs.retain(|item| item.author.id == bot_id); let mut last_msg: Option = msgs.last().cloned(); @@ -497,15 +497,15 @@ async fn read_msgs(http: &Http, bot_id: UserId, c_id: ChannelId) -> Vec } -async fn msgs_to_json<'a>(msgs: Vec, reddit_data: &'a Value, max_age: u64) -> Value { +async fn msgs_to_json(msgs: Vec, reddit_data: &Value, max_age: u64) -> Value { let mut msgs_json: Value = json!({"no_change": {}, "updated": {}, "removed": {}, "duplicates": {}, "old": {}}); let now = SystemTime::now() .duration_since(UNIX_EPOCH) .expect("Time went backwards") - .as_secs() as u64; + .as_secs(); for msg in msgs { - if msg.embeds.len() == 0 { continue; } + if msg.embeds.is_empty() { continue; } if msg.embeds[0].url.is_none() { continue; } let url = msg.embeds[0].url.clone().unwrap(); @@ -536,7 +536,7 @@ async fn msgs_to_json<'a>(msgs: Vec, reddit_data: &'a Value, max_age: u let mut u_json: Value = msg_json.unwrap(); let re_url = &reddit_data[BK_WEEK][&url]; - let post_date = re_url["post_data"]["date_unix"].as_u64().unwrap_or_else(|| 0); + let post_date = re_url["post_data"]["date_unix"].as_u64().unwrap_or(0); // old if now - post_date > max_age { @@ -591,7 +591,7 @@ async fn add_posts(http: &Http, c_id: ChannelId, r_data: &Map, ms let now = SystemTime::now() .duration_since(UNIX_EPOCH) .expect("Time went backwards") - .as_secs() as u64; + .as_secs(); for url in r_data.keys() { if ["no_change", "updated", "removed", "old", "duplicates"] @@ -668,7 +668,7 @@ pub async fn bk_week_vote( 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 unw_vote = un_vote.unwrap_or_else(|| false); + let unw_vote = un_vote.unwrap_or(false); if post_data.get(&url).is_none() { send_post_not_found_message(ctx, &url).await; @@ -749,11 +749,8 @@ pub async fn bk_week_top( all.insert(url, val); } - let amount_u = amount.unwrap_or_else(|| 3); - let amount_clamped = - if amount_u > 10 { 10 } - else if amount_u < 1 { 1 } - else { amount_u }; + let amount_u = amount.unwrap_or(3); + let amount_clamped = amount_u.clamp(1, 10); let top = if category != TopCategory::Oldest @@ -762,7 +759,7 @@ pub async fn bk_week_top( for post in top { let url = post.0; - let _ = send_embed_for_post(ctx, posts_u[url].clone(), &url).await; + let _ = send_embed_for_post(ctx, posts_u[url].clone(), url).await; } return Ok(()); diff --git a/src/cmds.rs b/src/cmds.rs index aa5f522..12352e7 100644 --- a/src/cmds.rs +++ b/src/cmds.rs @@ -41,7 +41,7 @@ pub async fn stop( ) -> Result<(), Error> { let should_stop = ctx.data().args.dev - || confirmation.unwrap_or_else(|| "".to_string()).to_lowercase() == "i want to stop the bot now"; + || confirmation.unwrap_or_default().to_lowercase() == "i want to stop the bot now"; if should_stop { let msg = send_msg(ctx, "Saving data...".to_string(), true, true).await.unwrap(); @@ -63,6 +63,7 @@ pub async fn stop( } +#[allow(clippy::too_many_arguments)] #[poise::command( slash_command, prefix_command, @@ -84,20 +85,20 @@ pub async fn embed( #[description = "Sets yourself as the author."] author: Option ) -> Result<(), Error> { - let reply_unwrap = reply.unwrap_or_else(|| false); + let reply_unwrap = reply.unwrap_or(false); send_embed( ctx, EmbedOptions { desc: description.replace("\\n", "\n"), - title: if title.is_some() { Some(title.unwrap().replace("\\n", "\n")) } else { None }, + title: title.map(|t| t.replace("\\n", "\n")), col: color, url, ts: timestamp, - ephemeral: ephemeral.unwrap_or_else(|| false), + ephemeral: ephemeral.unwrap_or(false), message, thumbnail, - author: if author.unwrap_or_else(|| false) { Some(Author { name: ctx.author().name.clone(), url: "".to_string(), icon_url: ctx.author().avatar_url().unwrap() }) } else { None } + author: if author.unwrap_or(false) { Some(Author { name: ctx.author().name.clone(), url: "".to_string(), icon_url: ctx.author().avatar_url().unwrap() }) } else { None } }, reply_unwrap ).await; @@ -235,11 +236,9 @@ pub async fn reload_cfg( let d_str = serde_json::to_string(&d)?; let r = send_cmd_json("update_cfg", Some(json!([d_str]))).await; // TODO: THIS - if r.is_some() { - if r.unwrap()["value"].as_bool().unwrap() { - send_msg(ctx, "Successfully reloaded the configs!".to_string(), true, true).await; - return Ok(()); - } + if r.is_some() && r.unwrap()["value"].as_bool().unwrap() { + send_msg(ctx, "Successfully reloaded the configs!".to_string(), true, true).await; + return Ok(()); } send_msg(ctx, "Failed to reload configs: Failed-type response from Python.".to_string(), true, true).await; diff --git a/src/data.rs b/src/data.rs index cc39917..61fcd35 100644 --- a/src/data.rs +++ b/src/data.rs @@ -184,8 +184,7 @@ pub async fn dc_contains_server(data: &Data, server_id: u64) -> bool { let mut clone = dc_data.clone(); let servers = clone["servers"].as_object_mut().unwrap(); - if servers.contains_key(&server_id.to_string()) { return true; } - else { return false; } + return servers.contains_key(&server_id.to_string()) } diff --git a/src/main.rs b/src/main.rs index 5ea84e4..849c1b4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,7 +27,6 @@ use serde::Serialize; use serde_json::Value; use tokio::runtime::Runtime; use tokio::sync::Mutex; -use serde_json; use tokio::task::JoinHandle; use tokio::time; use websocket::send_cmd_json; @@ -56,6 +55,7 @@ struct Args { type Error = Box; type Context<'a> = poise::Context<'a, Data, Error>; +type Schedule = (Duration, fn() -> Pin + Send>>); struct Data { @@ -81,7 +81,7 @@ async fn main() { let own_vec_str: Vec = own_env.split(",").map(String::from).collect(); let own_vec_u64: Vec = own_vec_str .iter() - .filter_map(|s| Some(s.parse::().expect("Failed to parse ASSISTANT_OWNERS. Invalid syntax."))) + .map(|s| s.parse::().expect("Failed to parse ASSISTANT_OWNERS. Invalid syntax.")) .collect(); if args.test { println!("----- USING TEST BOT -----"); } @@ -123,7 +123,7 @@ async fn main() { }); if !args.nosched { - let schedules: Vec<(Duration, fn() -> Pin + Send>>)> = vec![ + let schedules: Vec = vec![ (Duration::from_secs(2 * 60), || Box::pin(read_reddit_inbox())) ]; @@ -155,7 +155,7 @@ async fn gen_data(args: Args, owners: Vec) -> Data { let mods_vec_str: Vec = mods_env.split(",").map(String::from).collect(); let mods_vec_u64: Vec = mods_vec_str .iter() - .filter_map(|s| Some(s.parse::().expect("Failed to parse ASSISTANT_BK_MODS. Invalid syntax."))) + .map(|s| s.parse::().expect("Failed to parse ASSISTANT_BK_MODS. Invalid syntax.")) .collect(); let data = Data { @@ -177,13 +177,9 @@ async fn gen_data(args: Args, owners: Vec) -> Data { async fn gen_bot(data: Data, args: Args) -> Client { - let token; - if !args.test { - token = std::env::var("ASSISTANT_TOKEN").expect("Missing ASSISTANT_TOKEN env var!"); - } - else { - token = std::env::var("ASSISTANT_TOKEN_TEST").expect("Missing ASSISTANT_TOKEN_TEST env var!"); - } + let token = + if !args.test { std::env::var("ASSISTANT_TOKEN").expect("Missing ASSISTANT_TOKEN env var!") } + else { std::env::var("ASSISTANT_TOKEN_TEST").expect("Missing ASSISTANT_TOKEN_TEST env var!") }; let intents = serenity::GatewayIntents::all(); @@ -246,7 +242,7 @@ async fn run_schedule Pin + Send>>>(d: Du } -async fn run_schedules(schedules: Vec<(Duration, fn() -> Pin + Send>>)>) { +async fn run_schedules(schedules: Vec) { let mut handles: Vec> = vec![]; rs_println!("Starting schedules..."); diff --git a/src/messages.rs b/src/messages.rs index 97f4931..4db60e8 100644 --- a/src/messages.rs +++ b/src/messages.rs @@ -49,7 +49,7 @@ pub static MANDATORY_MSG: &str = "Mandatory response, please ignore."; fn none_to_empty(string: Option) -> String { - return string.unwrap_or_else(|| "".to_string()); + return string.unwrap_or_default(); } @@ -143,7 +143,7 @@ pub fn embed_from_options(options: EmbedOptions) -> CreateEmbed { let mut embed = CreateEmbed::new() .title (none_to_empty(options.title)) .description(options.desc) - .colour (Color::new(options.col.unwrap_or_else(|| DEFAULT_DC_COL))) + .colour (Color::new(options.col.unwrap_or(DEFAULT_DC_COL))) .url (none_to_empty(options.url)); if let Some(a) = author { embed = embed.author(a); } @@ -240,9 +240,9 @@ pub fn embed_post(post_data: &Value, url: &str, ephemeral: bool) -> EmbedOptions url: Some(url.to_string()), ts: Some(Timestamp::from_unix_timestamp(post_data["post_data"]["date_unix"].as_i64().unwrap()).unwrap()), ephemeral, - thumbnail: media_urls.get(0) + thumbnail: media_urls.first() .and_then(|url| url.as_str().map(|s| s.to_string())) - .or_else(|| None), + .or(None), ..Default::default() }; } diff --git a/src/python.rs b/src/python.rs index e834be6..326e2dd 100644 --- a/src/python.rs +++ b/src/python.rs @@ -12,7 +12,7 @@ pub fn start(args: String) -> PyResult<()> { rs_println!("Running Python program..."); let slash = if cfg!(windows) { "\\" } else if cfg!(unix) { "/" } else { "" }; - if slash == "" { errln!("Man what kinda OS do you have? Neither unix or windows, what the hell!? I can't process this anymore, you're too weird!"); } + if slash.is_empty() { errln!("Man what kinda OS do you have? Neither unix or windows, what the hell!? I can't process this anymore, you're too weird!"); } let path = format!("{0}{1}src{1}python", env!("CARGO_MANIFEST_DIR"), slash); @@ -39,6 +39,6 @@ pub fn start(args: String) -> PyResult<()> { fn get_code(path: &str) -> String { return fs::read_to_string(path) - .expect(&format!("Failed to read Python file.\nPath: {}", path)) + .unwrap_or_else(|_| panic!("Failed to read Python file.\nPath: {}", path)) .to_string(); } diff --git a/src/websocket.rs b/src/websocket.rs index a97d554..10bda9a 100644 --- a/src/websocket.rs +++ b/src/websocket.rs @@ -51,9 +51,9 @@ pub async fn send_cmd_json(func_name: &str, func_args: Option) -> Option< unsafe { let Some(sender) = &GLOBAL_SENDER else { return None }; let mut sender = sender.lock().await; - let Some(s) = sender.as_mut() else { return None }; + let s = sender.as_mut()?; - let unw_args = if func_args.is_some() { func_args.unwrap() } else { json!([]) }; + let unw_args = func_args.unwrap_or(json!([])); let json_str = format!( "json:{{\"type\": \"function\", \"value\":\"{}\", \"args\": {}}}", @@ -83,13 +83,13 @@ async fn receive_response() -> Option { unsafe { let Some(receiver) = &GLOBAL_RECEIVER else { return None }; let mut receiver = receiver.lock().await; - let Some(r) = receiver.as_mut() else { return None }; + let r = receiver.as_mut()?; let Some(Ok(msg)) = r.next().await else { return None }; let tungstenite::Message::Text(response) = msg else { return None }; - if response.starts_with("json:") { - return serde_json::from_str(&response[5..]).ok(); + if let Some(stripped) = response.strip_prefix("json:") { + return serde_json::from_str(stripped).ok(); } else { return serde_json::from_str(&response).ok(); @@ -131,8 +131,8 @@ async fn handle_message(msg: tungstenite::protocol::Message, args: Args, owners: tungstenite::Message::Text(text) => { rs_println!("Received from Python: {}", text); - if text.starts_with("json:") { - let t_json: Value = serde_json::from_str(&text[5..]).unwrap(); + if let Some(stripped) = text.strip_prefix("json:") { + let t_json: Value = serde_json::from_str(stripped).unwrap(); if t_json.get("error").is_some() { send_dm("Unknown internal Python error occurred!".to_string(), args, owners).await; }