feat: when a user links their mail it will also activate any roles

This commit is contained in:
silver 2023-09-17 21:33:36 +01:00
parent 6eb61c6798
commit 56aaf107d6

View file

@ -235,7 +235,10 @@ pub(crate) mod link {
pub(crate) mod verify { pub(crate) mod verify {
use super::*; use super::*;
use crate::commands::link_email::link::{db_pending_clear_expired, get_verify_from_db}; use crate::commands::link_email::link::{db_pending_clear_expired, get_verify_from_db};
use serenity::model::user::User;
use skynet_discord_bot::{get_server_config, ServerMembersWolves, Servers};
use sqlx::Error; use sqlx::Error;
pub async fn run(command: &ApplicationCommandInteraction, ctx: &Context) -> String { pub async fn run(command: &ApplicationCommandInteraction, ctx: &Context) -> String {
let db_lock = { let db_lock = {
let data_read = ctx.data.read().await; let data_read = ctx.data.read().await;
@ -274,12 +277,16 @@ pub(crate) mod verify {
match db_pending_clear_successful(&db, &command.user.name).await { match db_pending_clear_successful(&db, &command.user.name).await {
Ok(_) => { Ok(_) => {
return match set_discord(&db, &command.user.name, &details.email).await { return match set_discord(&db, &command.user.name, &details.email).await {
Ok(_) => "Discord username linked to Wolves".to_string(), Ok(_) => {
// get teh right roles for the user
set_server_roles(&db, &command.user, ctx).await;
"Discord username linked to Wolves".to_string()
}
Err(e) => { Err(e) => {
println!("{:?}", e); println!("{:?}", e);
"Failed to save, please try /link again".to_string() "Failed to save, please try /link again".to_string()
} }
} };
} }
Err(e) => println!("{:?}", e), Err(e) => println!("{:?}", e),
} }
@ -323,4 +330,52 @@ pub(crate) mod verify {
.fetch_optional(db) .fetch_optional(db)
.await .await
} }
async fn set_server_roles(db: &Pool<Sqlite>, discord: &User, ctx: &Context) {
if let Ok(servers) = get_servers(db, &discord.name).await {
for server in servers {
if let Ok(mut member) = server.server.member(&ctx.http, &discord.id).await {
if let Some(config) = get_server_config(db, &server.server).await {
let Servers {
role_past,
role_current,
..
} = config;
let mut roles = vec![];
if let Some(role) = &role_past {
if !member.roles.contains(role) {
roles.push(role.to_owned());
}
}
if let Some(role) = &role_current {
if !member.roles.contains(role) {
roles.push(role.to_owned());
}
}
if let Err(e) = member.add_roles(&ctx, &roles).await {
println!("{:?}", e);
}
}
}
}
}
}
async fn get_servers(db: &Pool<Sqlite>, discord: &str) -> Result<Vec<ServerMembersWolves>, Error> {
sqlx::query_as::<_, ServerMembersWolves>(
"
SELECT *
FROM server_members
JOIN wolves USING (id_wolves)
WHERE discord = ?
",
)
.bind(discord)
.fetch_all(db)
.await
}
} }