Verified Commit 80648a82 authored by Mathias B.'s avatar Mathias B.
Browse files

Assignation d'un rôle à un utilisateur

parent f0fc2128
......@@ -530,6 +530,7 @@ dependencies = [
"serde_json",
"serenity",
"translation",
"uuid",
]
[[package]]
......@@ -590,6 +591,7 @@ dependencies = [
"tracing",
"tracing-subscriber",
"translation",
"uuid",
]
[[package]]
......@@ -1469,6 +1471,7 @@ dependencies = [
"chrono",
"fallible-iterator",
"postgres-protocol",
"uuid",
]
[[package]]
......@@ -2491,6 +2494,12 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "uuid"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7"
[[package]]
name = "uwl"
version = "0.6.0"
......
......@@ -26,7 +26,8 @@ tracing-subscriber = "0.2.19"
# Databases, crypto
tokio-postgres = { version = "0.7.2", features = ["with-chrono-0_4"] }
tokio-postgres = { version = "0.7.2", features = ["with-chrono-0_4", "with-uuid-0_8"] }
uuid = "0.8.2"
chacha20poly1305 = { version = "0.8.1", features = ["std"] }
rand = "0.8.4"
......
......@@ -10,7 +10,6 @@ use serenity::async_trait;
use serenity::model::prelude::*;
use serenity::prelude::*;
use tracing::{debug, info};
use serenity::client::bridge::gateway::event::ShardStageUpdateEvent;
pub struct Handler;
......@@ -310,7 +309,7 @@ impl EventHandler for Handler {
}
async fn reaction_remove(&self, ctx: Context, removed_reaction: Reaction) {
process_handler_result(crate::modules::role_reaction::reaction_remove(&ctx, &reaction).await);
process_handler_result(crate::modules::role_reaction::reaction_remove(&ctx, &removed_reaction).await);
}
async fn ready(&self, _ctx: Context, ready: Ready) {
......
SELECT *
FROM bot.role_reaction_assignments
WHERE messages_id = $1
AND emoji = $2
\ No newline at end of file
use serenity::client::Context;
use serenity::model::channel::Reaction;
use crate::repositories::RoleReactionRepository;
use eyre::ContextCompat;
pub async fn reaction_add(ctx: &Context, reaction: &Reaction) -> eyre::Result<()> {
// Récupérer le message correspondant au menu
// Récupérer la réaction en base afin de déterminer le rôle
// Assigner le rôle
let reaction_message = RoleReactionRepository::fetch_reaction_menu(reaction.message_id)
.await?
// Si on ne trouve aucun message correspondant à un menu, on retourne (Option::with_context)
// retourne un eyre::Result<T> et, par voie de conséquence, nous permet d'utiliser le sucre
// syntaxique ? qui permet de retourner l'erreur à l'appelant immédiatement.
.context("Aucun message trouvé qui correspond à un menu de réaction")?;
// Récupérer la réaction en base afin de déterminer le rôle à assigner
let reaction_role = RoleReactionRepository::fetch_role_from_reaction(reaction_message.id, &reaction.emoji.to_string())
.await?
.context("Aucun rôle correspondant à la réaction donnée")?;
// Chercher le rôle dans ceux de l'utilisateur. A force de déplacer les choses, la personne peut
// s'"assigner" le rôle mais en réalité ce sera un no-op.
let mut member = ctx.cache.member(
reaction.guild_id.context("Réaction pas dans une guilde")?,
reaction.user_id.expect("Cache is unavaliable")
)
.await
.context("Aucun membre correspondant dans la guilde")?;
if member.roles.contains(&reaction_role.roles_id) {
return Ok(());
}
member.add_role(ctx, reaction_role.roles_id).await?;
Ok(())
}
pub async fn reaction_remove(ctx: &Context, reaction: &Reaction) {
pub async fn reaction_remove(ctx: &Context, reaction: &Reaction) -> eyre::Result<()> {
todo!()
}
\ No newline at end of file
use serenity::model::id::MessageId;
use datastructs::bot::ReactionMessage;
use serenity::model::id::{MessageId, RoleId, GuildId, ChannelId};
use datastructs::bot::{ReactionMessage, ReactionAssignment};
use crate::utils::database::DatabaseClient;
use tokio_postgres::Row;
use uuid::Uuid;
pub struct RoleReactionRepository;
......@@ -13,7 +14,7 @@ impl RoleReactionRepository {
let rows = db.query(
include_str!("../files/sql/role_reaction/fetch_reaction_menu.sql"),
&[
&message_id.0.into()
&(message_id.0 as i64)
]
).await?;
......@@ -26,17 +27,48 @@ impl RoleReactionRepository {
}
}
}
#[tracing::instrument]
pub async fn fetch_role_from_reaction(menu_id: Uuid, emoji: &str) -> super::PostgreSQLResult<Option<ReactionAssignment>> {
let db = DatabaseClient::get();
let rows = db.query(
include_str!("../files/sql/role_reaction/fetch_role_reaction.sql"),
&[
&menu_id,
&emoji
]
).await?;
match rows.len() {
0 => Ok(None),
1 => Ok(Some(convert_row_to_assignment(&rows[0]))),
_ => {
tracing::warn!("Plus d'une ligne retournée lors de la requête d'un message de menu. Retour de la première ligne");
Ok(Some(convert_row_to_assignment(&rows[0])))
}
}
}
}
fn convert_row_to_reaction_menu(row: &Row) -> ReactionMessage {
ReactionMessage {
id: row.get("id"),
message_id: row.get("message_id"),
guilds_id: row.get("guilds_id"),
channels_id: row.get("channels_id"),
message_id: MessageId(row.get::<_, i64>("message_id") as u64),
guilds_id: GuildId(row.get::<_, i64>("guilds_id") as u64),
channels_id: ChannelId(row.get::<_, i64>("channels_id") as u64),
created_at: row.get("created_at"),
updated_at: row.get("updated_at"),
state: row.get("state"),
description: row.get("description")
state: row.get::<_, i16>("state") as u16,
description: row.get("menu_description")
}
}
fn convert_row_to_assignment(row: &Row) -> ReactionAssignment {
ReactionAssignment {
id: row.get("id"),
emoji: row.get("emoji"),
messages_id: row.get("messages_id"),
roles_id: RoleId(row.get::<_, i64>("roles_id") as u64),
order: row.get::<_, i32>("order") as u32
}
}
\ No newline at end of file
......@@ -17,6 +17,7 @@ serde = { version = "1.0.126", features = ["derive"] }
cryptoutils = { path = "../cryptoutils" }
translation = { path = "../translation" }
serenity = "0.10.8"
uuid = "0.8.2"
[dev-dependencies]
serde_json = "1.0.66"
......
use serenity::model::id::{MessageId, GuildId, ChannelId, RoleId};
use chrono::{DateTime, Utc};
use uuid::Uuid;
pub struct ReactionMessage {
pub id: String,
pub id: Uuid,
pub message_id: MessageId,
pub guilds_id: GuildId,
pub channels_id: ChannelId,
......@@ -13,9 +14,9 @@ pub struct ReactionMessage {
}
pub struct ReactionAssignment {
pub id: String,
pub id: Uuid,
pub emoji: String,
pub messages_id: String,
pub messages_id: Uuid,
pub roles_id: RoleId,
pub order: u32
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment