Fix clippy::pedantic lints

This commit is contained in:
Aadi Desai 2023-09-25 13:23:32 +01:00
parent eb77798c35
commit 69e7a5a4f4
Signed by: supleed2
SSH key fingerprint: SHA256:CkbNRs0yVzXEiUp2zd0PSxsfRUMFF9bLlKXtE1xEbKM
8 changed files with 87 additions and 115 deletions

View file

@ -18,7 +18,6 @@ pub(crate) async fn setup(
#[channel_types("Text", "News")] #[channel_types("Text", "News")]
channel: serenity::GuildChannel, channel: serenity::GuildChannel,
) -> Result<(), Error> { ) -> Result<(), Error> {
println!("Cmd: ({}) setup", ctx.author().name);
#[derive(Modal)] #[derive(Modal)]
struct Setup { struct Setup {
#[name = "Contents of the verification intro message"] #[name = "Contents of the verification intro message"]
@ -36,6 +35,8 @@ pub(crate) async fn setup(
text: Option<String>, text: Option<String>,
} }
println!("Cmd: ({}) setup", ctx.author().name);
if let Some(Setup { if let Some(Setup {
message, message,
emoji, emoji,
@ -89,22 +90,17 @@ pub(crate) async fn delete_member(
remove_roles: Option<bool>, remove_roles: Option<bool>,
) -> Result<(), Error> { ) -> Result<(), Error> {
println!("Cmd: ({}) delete_member {id}", ctx.author().name); println!("Cmd: ({}) delete_member {id}", ctx.author().name);
match db::delete_member_by_id(&ctx.data().db, id.user.id.into()).await? { if db::delete_member_by_id(&ctx.data().db, id.user.id.into()).await? {
true => { if remove_roles.unwrap_or(true) {
if remove_roles.unwrap_or(true) { let mut m = id.clone();
let mut m = id.clone(); crate::verify::remove_role(ctx.serenity_context(), &mut m, ctx.data().member).await?;
crate::verify::remove_role(ctx.serenity_context(), &mut m, ctx.data().member) crate::verify::remove_role(ctx.serenity_context(), &mut m, ctx.data().fresher).await?;
.await?;
crate::verify::remove_role(ctx.serenity_context(), &mut m, ctx.data().fresher)
.await?;
}
ctx.say(format!("Successfully deleted member info for {id}"))
.await?
}
false => {
ctx.say(format!("Failed to delete member info for {id}"))
.await?
} }
ctx.say(format!("Successfully deleted member info for {id}"))
.await?
} else {
ctx.say(format!("Failed to delete member info for {id}"))
.await?
}; };
Ok(()) Ok(())
} }
@ -112,7 +108,6 @@ pub(crate) async fn delete_member(
/// Print all members in members table /// Print all members in members table
#[poise::command(slash_command)] #[poise::command(slash_command)]
pub(crate) async fn get_all_members(ctx: ACtx<'_>) -> Result<(), Error> { pub(crate) async fn get_all_members(ctx: ACtx<'_>) -> Result<(), Error> {
println!("Cmd: ({}) get_all_members", ctx.author().name);
#[derive(Modal)] #[derive(Modal)]
struct Confirm { struct Confirm {
#[name = "This will output the members db as text"] #[name = "This will output the members db as text"]
@ -120,6 +115,8 @@ pub(crate) async fn get_all_members(ctx: ACtx<'_>) -> Result<(), Error> {
confirm: String, confirm: String,
} }
println!("Cmd: ({}) get_all_members", ctx.author().name);
if let Some(Confirm { confirm }) = Confirm::execute(ctx).await? { if let Some(Confirm { confirm }) = Confirm::execute(ctx).await? {
if confirm.to_lowercase().contains("yes") { if confirm.to_lowercase().contains("yes") {
let members = db::get_all_members(&ctx.data().db).await?; let members = db::get_all_members(&ctx.data().db).await?;
@ -320,15 +317,12 @@ pub(crate) async fn count_pending(ctx: ACtx<'_>) -> Result<(), Error> {
#[poise::command(slash_command)] #[poise::command(slash_command)]
pub(crate) async fn delete_pending(ctx: ACtx<'_>, id: serenity::User) -> Result<(), Error> { pub(crate) async fn delete_pending(ctx: ACtx<'_>, id: serenity::User) -> Result<(), Error> {
println!("Cmd: ({}) delete_pending {id}", ctx.author().name); println!("Cmd: ({}) delete_pending {id}", ctx.author().name);
match db::delete_pending_by_id(&ctx.data().db, id.id.into()).await? { if db::delete_pending_by_id(&ctx.data().db, id.id.into()).await? {
true => { ctx.say(format!("Successfully deleted pending member info for {id}"))
ctx.say(format!("Successfully deleted pending member info for {id}")) .await?
.await? } else {
} ctx.say(format!("Failed to delete pending member info for {id}"))
false => { .await?
ctx.say(format!("Failed to delete pending member info for {id}"))
.await?
}
}; };
Ok(()) Ok(())
} }
@ -336,7 +330,6 @@ pub(crate) async fn delete_pending(ctx: ACtx<'_>, id: serenity::User) -> Result<
/// Print all pending members in pending table /// Print all pending members in pending table
#[poise::command(slash_command)] #[poise::command(slash_command)]
pub(crate) async fn get_all_pending(ctx: ACtx<'_>) -> Result<(), Error> { pub(crate) async fn get_all_pending(ctx: ACtx<'_>) -> Result<(), Error> {
println!("Cmd: ({}) get_all_pending", ctx.author().name);
#[derive(Modal)] #[derive(Modal)]
struct ConfirmPending { struct ConfirmPending {
#[name = "This will output the pending db as text"] #[name = "This will output the pending db as text"]
@ -344,6 +337,8 @@ pub(crate) async fn get_all_pending(ctx: ACtx<'_>) -> Result<(), Error> {
confirm: String, confirm: String,
} }
println!("Cmd: ({}) get_all_pending", ctx.author().name);
if let Some(ConfirmPending { confirm }) = ConfirmPending::execute(ctx).await? { if let Some(ConfirmPending { confirm }) = ConfirmPending::execute(ctx).await? {
if confirm.to_lowercase().contains("yes") { if confirm.to_lowercase().contains("yes") {
let pending = db::get_all_pending(&ctx.data().db).await?; let pending = db::get_all_pending(&ctx.data().db).await?;
@ -402,7 +397,6 @@ pub(crate) async fn add_pending(
/// Delete all pending members in pending table /// Delete all pending members in pending table
#[poise::command(slash_command)] #[poise::command(slash_command)]
pub(crate) async fn delete_all_pending(ctx: ACtx<'_>) -> Result<(), Error> { pub(crate) async fn delete_all_pending(ctx: ACtx<'_>) -> Result<(), Error> {
println!("Cmd: ({}) delete_all_pending", ctx.author().name);
#[derive(Modal)] #[derive(Modal)]
struct ConfirmPurgePending { struct ConfirmPurgePending {
#[name = "This will wipe the pending db"] #[name = "This will wipe the pending db"]
@ -410,6 +404,8 @@ pub(crate) async fn delete_all_pending(ctx: ACtx<'_>) -> Result<(), Error> {
confirm: String, confirm: String,
} }
println!("Cmd: ({}) delete_all_pending", ctx.author().name);
if let Some(ConfirmPurgePending { confirm }) = ConfirmPurgePending::execute(ctx).await? { if let Some(ConfirmPurgePending { confirm }) = ConfirmPurgePending::execute(ctx).await? {
if confirm.to_lowercase().contains("yes") { if confirm.to_lowercase().contains("yes") {
let deleted = db::delete_all_pending(&ctx.data().db).await?; let deleted = db::delete_all_pending(&ctx.data().db).await?;
@ -440,15 +436,12 @@ pub(crate) async fn count_manual(ctx: ACtx<'_>) -> Result<(), Error> {
#[poise::command(slash_command)] #[poise::command(slash_command)]
pub(crate) async fn delete_manual(ctx: ACtx<'_>, id: serenity::User) -> Result<(), Error> { pub(crate) async fn delete_manual(ctx: ACtx<'_>, id: serenity::User) -> Result<(), Error> {
println!("Cmd: ({}) delete_manual {id}", ctx.author().name); println!("Cmd: ({}) delete_manual {id}", ctx.author().name);
match db::delete_manual_by_id(&ctx.data().db, id.id.into()).await? { if db::delete_manual_by_id(&ctx.data().db, id.id.into()).await? {
true => { ctx.say(format!("Successfully deleted manual member info for {id}"))
ctx.say(format!("Successfully deleted manual member info for {id}")) .await?
.await? } else {
} ctx.say(format!("Failed to delete manual member info for {id}"))
false => { .await?
ctx.say(format!("Failed to delete manual member info for {id}"))
.await?
}
}; };
Ok(()) Ok(())
} }
@ -456,7 +449,6 @@ pub(crate) async fn delete_manual(ctx: ACtx<'_>, id: serenity::User) -> Result<(
/// Print all manual members in manual table /// Print all manual members in manual table
#[poise::command(slash_command)] #[poise::command(slash_command)]
pub(crate) async fn get_all_manual(ctx: ACtx<'_>) -> Result<(), Error> { pub(crate) async fn get_all_manual(ctx: ACtx<'_>) -> Result<(), Error> {
println!("Cmd: ({}) get_all_manual", ctx.author().name);
#[derive(Modal)] #[derive(Modal)]
struct ConfirmManual { struct ConfirmManual {
#[name = "This will output the manual db as text"] #[name = "This will output the manual db as text"]
@ -464,6 +456,8 @@ pub(crate) async fn get_all_manual(ctx: ACtx<'_>) -> Result<(), Error> {
confirm: String, confirm: String,
} }
println!("Cmd: ({}) get_all_manual", ctx.author().name);
if let Some(ConfirmManual { confirm }) = ConfirmManual::execute(ctx).await? { if let Some(ConfirmManual { confirm }) = ConfirmManual::execute(ctx).await? {
if confirm.to_lowercase().contains("yes") { if confirm.to_lowercase().contains("yes") {
let manual = db::get_all_manual(&ctx.data().db).await?; let manual = db::get_all_manual(&ctx.data().db).await?;
@ -526,7 +520,6 @@ pub(crate) async fn add_manual(
/// Delete all manual members in manual table /// Delete all manual members in manual table
#[poise::command(slash_command)] #[poise::command(slash_command)]
pub(crate) async fn delete_all_manual(ctx: ACtx<'_>) -> Result<(), Error> { pub(crate) async fn delete_all_manual(ctx: ACtx<'_>) -> Result<(), Error> {
println!("Cmd: ({}) delete_all_manual", ctx.author().name);
#[derive(Modal)] #[derive(Modal)]
struct ConfirmPurgeManual { struct ConfirmPurgeManual {
#[name = "This will wipe the manual db"] #[name = "This will wipe the manual db"]
@ -534,6 +527,8 @@ pub(crate) async fn delete_all_manual(ctx: ACtx<'_>) -> Result<(), Error> {
confirm: String, confirm: String,
} }
println!("Cmd: ({}) delete_all_manual", ctx.author().name);
if let Some(ConfirmPurgeManual { confirm }) = ConfirmPurgeManual::execute(ctx).await? { if let Some(ConfirmPurgeManual { confirm }) = ConfirmPurgeManual::execute(ctx).await? {
if confirm.to_lowercase().contains("yes") { if confirm.to_lowercase().contains("yes") {
let deleted = db::delete_all_manual(&ctx.data().db).await?; let deleted = db::delete_all_manual(&ctx.data().db).await?;

View file

@ -1,6 +1,6 @@
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
#[serde(rename_all = "PascalCase")] #[serde(rename_all = "PascalCase")]
pub struct EaMember { pub struct Member {
pub first_name: String, pub first_name: String,
pub surname: String, pub surname: String,
pub login: String, pub login: String,
@ -10,13 +10,13 @@ pub struct EaMember {
pub(crate) async fn get_members_list( pub(crate) async fn get_members_list(
api_key: &str, api_key: &str,
url: &str, url: &str,
) -> Result<Vec<EaMember>, reqwest::Error> { ) -> Result<Vec<Member>, reqwest::Error> {
let members = reqwest::Client::new() let members = reqwest::Client::new()
.get(url) .get(url)
.header("X-API-Key", api_key) .header("X-API-Key", api_key)
.send() .send()
.await? .await?
.json::<Vec<EaMember>>() .json::<Vec<Member>>()
.await?; .await?;
Ok(members) Ok(members)
} }

View file

@ -97,19 +97,16 @@ async fn poise(
.into(); .into();
// Build Axum Router // Build Axum Router
use axum::routing::{get, post}; let router = axum::Router::new().route(
let router = axum::Router::new() "/verify",
.route("/", get(routes::hello_world)) axum::routing::post({
.route( let pool = pool.clone();
"/verify", let key = secret_store
post({ .get("VERIFY_KEY")
let pool = pool.clone(); .context("VERIFY_KEY not found")?;
let key = secret_store move |body| routes::verify(pool, body, key)
.get("VERIFY_KEY") }),
.context("VERIFY_KEY not found")?; );
move |body| routes::verify(pool, body, key)
}),
);
// Build Poise Instance // Build Poise Instance
let discord = poise::Framework::builder() let discord = poise::Framework::builder()
@ -172,7 +169,7 @@ async fn event_handler(
) -> Result<(), Error> { ) -> Result<(), Error> {
match event { match event {
poise::Event::GuildMemberAddition { new_member } => { poise::Event::GuildMemberAddition { new_member } => {
println!("Member joined:\n{:#?}", new_member) println!("Member joined:\n{new_member:#?}");
} }
poise::Event::InteractionCreate { poise::Event::InteractionCreate {
interaction: serenity::Interaction::MessageComponent(m), interaction: serenity::Interaction::MessageComponent(m),

View file

@ -1,10 +1,6 @@
use crate::PendingMember; use crate::PendingMember;
use axum::{http::StatusCode, response::IntoResponse, Json}; use axum::{http::StatusCode, response::IntoResponse, Json};
pub(crate) async fn hello_world() -> impl IntoResponse {
(StatusCode::OK, "Hello world!")
}
#[derive(serde::Deserialize, serde::Serialize)] #[derive(serde::Deserialize, serde::Serialize)]
pub(crate) struct Verify { pub(crate) struct Verify {
id: String, id: String,
@ -22,12 +18,10 @@ pub(crate) async fn verify(
None => (StatusCode::BAD_REQUEST, "Invalid request body").into_response(), None => (StatusCode::BAD_REQUEST, "Invalid request body").into_response(),
Some(Json(verify)) => { Some(Json(verify)) => {
if verify.key == key { if verify.key == key {
let id = match verify.id.parse::<i64>() { let Ok(id) = verify.id.parse::<i64>() else {
Ok(i) => i, return (StatusCode::BAD_REQUEST, "Invalid request body").into_response();
Err(_) => {
return (StatusCode::BAD_REQUEST, "Invalid request body").into_response();
}
}; };
// Delete from pending if exists // Delete from pending if exists
let _ = crate::db::delete_pending_by_id(&pool, id).await; let _ = crate::db::delete_pending_by_id(&pool, id).await;

View file

@ -66,7 +66,7 @@ pub(crate) async fn login_2(
.ephemeral(true) .ephemeral(true)
}) })
}) })
.await? .await?;
} }
Ok(None) => { Ok(None) => {
m.create_interaction_response(&ctx.http, |i| { m.create_interaction_response(&ctx.http, |i| {
@ -76,7 +76,7 @@ pub(crate) async fn login_2(
.ephemeral(true) .ephemeral(true)
}) })
}) })
.await? .await?;
} }
Ok(Some(_)) => { Ok(Some(_)) => {
m.create_interaction_response(&ctx.http, |i| { m.create_interaction_response(&ctx.http, |i| {
@ -99,7 +99,7 @@ pub(crate) async fn login_2(
}) })
}) })
}) })
.await? .await?;
} }
}; };
Ok(()) Ok(())
@ -245,9 +245,9 @@ pub(crate) async fn login_6(
data.au_ch_id data.au_ch_id
.send_message(&ctx.http, |cm| { .send_message(&ctx.http, |cm| {
cm.add_embed(|e| { cm.add_embed(|e| {
e.thumbnail(m.user.avatar_url().unwrap_or( e.thumbnail(
"https://cdn.discordapp.com/embed/avatars/0.png".to_string(), m.user.avatar_url().unwrap_or(super::AVATAR.to_string()),
)) )
.title("Member verified via login") .title("Member verified via login")
.description(&m.user) .description(&m.user)
.field("Fresher", fresher, true) .field("Fresher", fresher, true)
@ -279,12 +279,12 @@ pub(crate) async fn login_6(
.ephemeral(true) .ephemeral(true)
}) })
}) })
.await? .await?;
} }
} }
} }
Err(e) => { Err(e) => {
eprintln!("Error: {e}") eprintln!("Error: {e}");
} }
}; };
Ok(()) Ok(())

View file

@ -125,9 +125,7 @@ pub(crate) async fn manual_3(
.send_message(&ctx.http, |cm| { .send_message(&ctx.http, |cm| {
cm.add_embed(|e| { cm.add_embed(|e| {
e.title("New verification request from") e.title("New verification request from")
.thumbnail(m.user.avatar_url().unwrap_or( .thumbnail(m.user.avatar_url().unwrap_or(super::AVATAR.to_string()))
"https://cdn.discordapp.com/embed/avatars/0.png".to_string(),
))
.description(&m.user) .description(&m.user)
.field("Real Name (To be checked)", &realname, true) .field("Real Name (To be checked)", &realname, true)
.field("Imperial Shortcode (To be checked", &shortcode, true) .field("Imperial Shortcode (To be checked", &shortcode, true)
@ -206,12 +204,7 @@ pub(crate) async fn manual_4(
data: &Data, data: &Data,
id: &str, id: &str,
) -> Result<(), Error> { ) -> Result<(), Error> {
let verify = match id.chars().nth(7) { let verify = matches!(id.chars().nth(7), Some('y'));
Some('y') => true,
Some('n') => false,
_ => false,
};
let user = id let user = id
.chars() .chars()
.skip(9) .skip(9)
@ -246,13 +239,11 @@ pub(crate) async fn manual_4(
i.kind(serenity::InteractionResponseType::UpdateMessage) i.kind(serenity::InteractionResponseType::UpdateMessage)
.interaction_response_data(|d| { .interaction_response_data(|d| {
d.components(|c| c).embed(|e| { d.components(|c| c).embed(|e| {
e.thumbnail(user.avatar_url().unwrap_or( e.thumbnail(user.avatar_url().unwrap_or(super::AVATAR.to_string()))
"https://cdn.discordapp.com/embed/avatars/0.png".to_string(), .title("Member verified via manual")
)) .description(&user)
.title("Member verified via manual") .field("Fresher", fresher, true)
.description(&user) .timestamp(serenity::Timestamp::now())
.field("Fresher", fresher, true)
.timestamp(serenity::Timestamp::now())
}) })
}) })
}) })
@ -280,7 +271,7 @@ pub(crate) async fn manual_4(
d.content(format!("Failed to add user {user} to member database")) d.content(format!("Failed to add user {user} to member database"))
}) })
}) })
.await? .await?;
} }
} }
} else { } else {
@ -292,14 +283,12 @@ pub(crate) async fn manual_4(
d.components(|c| c).embed(|e| { d.components(|c| c).embed(|e| {
e.title("Member denied via manual") e.title("Member denied via manual")
.description(&user) .description(&user)
.thumbnail(user.avatar_url().unwrap_or( .thumbnail(user.avatar_url().unwrap_or(super::AVATAR.to_string()))
"https://cdn.discordapp.com/embed/avatars/0.png".to_string(),
))
.timestamp(serenity::Timestamp::now()) .timestamp(serenity::Timestamp::now())
}) })
}) })
}) })
.await? .await?;
} }
Ok(()) Ok(())

View file

@ -114,21 +114,18 @@ pub(crate) async fn membership_3(
return Ok(()); return Ok(());
} }
}; };
let member = match members let Some(member) = members
.iter() .iter()
.find(|&member| member.order_no.to_string() == order && member.login == shortcode) .find(|&member| member.order_no.to_string() == order && member.login == shortcode)
{ else {
Some(m) => m, m.create_interaction_response(&ctx.http, |i| {
None => { let msg = "Sorry, your order was not found, please check the \
m.create_interaction_response(&ctx.http, |i| {
let msg = "Sorry, your order was not found, please check the \
order number and that it is for your current year's membership"; order number and that it is for your current year's membership";
i.kind(serenity::InteractionResponseType::ChannelMessageWithSource) i.kind(serenity::InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|d| d.content(msg).ephemeral(true)) .interaction_response_data(|d| d.content(msg).ephemeral(true))
}) })
.await?; .await?;
return Ok(()); return Ok(());
}
}; };
if crate::db::insert_member( if crate::db::insert_member(
&data.db, &data.db,
@ -171,13 +168,11 @@ pub(crate) async fn membership_3(
data.au_ch_id data.au_ch_id
.send_message(&ctx.http, |cm| { .send_message(&ctx.http, |cm| {
cm.add_embed(|e| { cm.add_embed(|e| {
e.thumbnail(m.user.avatar_url().unwrap_or( e.thumbnail(m.user.avatar_url().unwrap_or(super::AVATAR.to_string()))
"https://cdn.discordapp.com/embed/avatars/0.png".to_string(), .title("Member verified via membership")
)) .description(&m.user)
.title("Member verified via membership") .field("Fresher", fresher, true)
.description(&m.user) .timestamp(serenity::Timestamp::now())
.field("Fresher", fresher, true)
.timestamp(serenity::Timestamp::now())
}) })
}) })
.await?; .await?;

View file

@ -10,6 +10,8 @@ pub(crate) use membership::*;
pub(crate) mod manual; pub(crate) mod manual;
pub(crate) use manual::*; pub(crate) use manual::*;
const AVATAR: &str = "https://cdn.discordapp.com/embed/avatars/0.png";
const INFO_MSG: &str = indoc::indoc! {" const INFO_MSG: &str = indoc::indoc! {"
Nano is a Discord bot written with serenity-rs/poise and tokio-rs/axum. Nano is a Discord bot written with serenity-rs/poise and tokio-rs/axum.
@ -72,7 +74,7 @@ pub(crate) async fn start(
.ephemeral(true) .ephemeral(true)
}) })
}) })
.await? .await?;
} else { } else {
m.create_interaction_response(&ctx.http, |i| { m.create_interaction_response(&ctx.http, |i| {
i.kind(if init { i.kind(if init {
@ -105,7 +107,7 @@ pub(crate) async fn start(
}) })
}) })
}) })
.await? .await?;
}; };
Ok(()) Ok(())
} }