Compare commits

...

10 commits

10 changed files with 83 additions and 98 deletions

View file

@ -1,5 +1,4 @@
use std::sync::atomic::{AtomicU64, Ordering};
use anyhow::Result;
use serenity::all::{CommandInteraction, Context, CreateCommand};
use sqlx::PgPool;
@ -11,6 +10,7 @@ include!("./mod_gen.rs");
pub enum CommandCategory {
Moderation,
Utils,
Gestion,
}
impl CommandCategory {
@ -18,6 +18,7 @@ impl CommandCategory {
match self {
Self::Utils => "🌐",
Self::Moderation => "🛡️",
Self::Gestion => "👑",
}
}
@ -25,6 +26,7 @@ impl CommandCategory {
match self {
Self::Utils => "Utils",
Self::Moderation => "Moderation",
Self::Gestion => "Gestion",
}
}
}
@ -34,15 +36,6 @@ pub trait SlashCommand: Send + Sync {
fn name(&self) -> &'static str;
fn description(&self) -> &'static str;
fn category(&self) -> &'static CommandCategory;
fn command_id_ref(&self) -> &AtomicU64;
fn get_id(&self) -> u64 {
self.command_id_ref().load(Ordering::Relaxed)
}
fn set_id(&self, id: u64) {
self.command_id_ref().store(id, Ordering::Relaxed);
}
fn register(&self) -> CreateCommand;
@ -52,7 +45,7 @@ pub trait SlashCommand: Send + Sync {
command: &CommandInteraction,
database: &PgPool,
_emoji: &EmojiConfig,
) -> Result<(), serenity::Error>;
) -> Result<()>;
}
pub struct CommandEntry {

View file

@ -1,7 +1,4 @@
use std::{
sync::atomic::{
AtomicU64,
},
time::Instant,
};
@ -17,19 +14,10 @@ use serenity::all::{
CreateInteractionResponseMessage, EditInteractionResponse,
};
use sqlx::PgPool;
use tracing::info;
use tracing::{debug, info};
use anyhow::Result;
pub struct Ping {
pub command_id: AtomicU64,
}
impl Ping {
pub fn new() -> Self {
Self {
command_id: AtomicU64::new(0),
}
}
}
pub struct Ping;
#[serenity::async_trait]
impl SlashCommand for Ping {
@ -45,10 +33,6 @@ impl SlashCommand for Ping {
&CommandCategory::Utils
}
fn command_id_ref(&self) -> &AtomicU64 {
&self.command_id
}
fn register(&self) -> CreateCommand {
info!("\t✅ | {}", self.name());
CreateCommand::new(self.name()).description(self.description())
@ -60,7 +44,8 @@ impl SlashCommand for Ping {
command: &CommandInteraction,
_database: &PgPool,
_emoji: &EmojiConfig,
) -> Result<(), serenity::Error> {
) -> Result<()> {
debug!("Ping command called");
let message: CreateInteractionResponseMessage = CreateInteractionResponseMessage::new()
.content("🏓 | Pong!")
.ephemeral(true);
@ -81,5 +66,5 @@ impl SlashCommand for Ping {
}
inventory::submit! {
CommandEntry { create: || Box::new(Ping::new()) }
CommandEntry { create: || Box::new(Ping) }
}

View file

@ -1,16 +1,17 @@
use sqlx::{PgPool, query, query_as};
use crate::models::bot::{DbBot, BotPresence, BotActivity};
use anyhow::Result;
const BOT_ID: i32 = 1;
pub async fn init(db: &PgPool) -> Result<(), sqlx::Error> {
pub async fn init(db: &PgPool) -> Result<()> {
query!("INSERT INTO bots (id) VALUES ($1) ON CONFLICT DO NOTHING", BOT_ID)
.execute(db)
.await?;
Ok(())
}
pub async fn get(db: &PgPool) -> Result<Option<DbBot>, sqlx::Error> {
pub async fn get(db: &PgPool) -> Result<Option<DbBot>> {
let bot: Option<DbBot> = query_as!(
DbBot,
r#"SELECT status, activity_type as "activity_type: BotActivity", presence as "presence: BotPresence" FROM bots WHERE id = $1"#,
@ -21,21 +22,21 @@ pub async fn get(db: &PgPool) -> Result<Option<DbBot>, sqlx::Error> {
Ok(bot)
}
pub async fn set_status(db: &PgPool, status: &str) -> Result<(), sqlx::Error> {
pub async fn set_status(db: &PgPool, status: &str) -> Result<()> {
query!("UPDATE bots SET status = $1 WHERE id = $2", status, BOT_ID)
.execute(db)
.await?;
Ok(())
}
pub async fn set_activity(db: &PgPool, activity: BotActivity) -> Result<(), sqlx::Error> {
pub async fn set_activity(db: &PgPool, activity: BotActivity) -> Result<()> {
query!("UPDATE bots SET activity_type = $1::bot_activity WHERE id = $2", activity as BotActivity, BOT_ID)
.execute(db)
.await?;
Ok(())
}
pub async fn set_presence(db: &PgPool, presence: BotPresence) -> Result<(), sqlx::Error> {
pub async fn set_presence(db: &PgPool, presence: BotPresence) -> Result<()> {
query!("UPDATE bots SET presence = $1::bot_presence WHERE id = $2", presence as BotPresence, BOT_ID)
.execute(db)
.await?;

View file

@ -5,6 +5,7 @@ use sqlx::{
query_scalar,
};
use crate::models::DbGuild;
use anyhow::Result;
pub enum LogChannel {
Bot,
@ -48,21 +49,21 @@ fn protect_select(asked: Protect) -> &'static str {
}
}
pub async fn create(db: &PgPool, guild_id: &str) -> Result<(), sqlx::Error> {
pub async fn create(db: &PgPool, guild_id: &str) -> Result<()> {
query!("INSERT INTO guilds (guild_id) VALUES ($1) ON CONFLICT DO NOTHING", guild_id)
.execute(db)
.await?;
Ok(())
}
pub async fn delete(db: &PgPool, guild_id: &str) -> Result<(), sqlx::Error> {
pub async fn delete(db: &PgPool, guild_id: &str) -> Result<()> {
query!("DELETE FROM guilds WHERE guild_id = $1", guild_id)
.execute(db)
.await?;
Ok(())
}
pub async fn get(db: &PgPool, guild_id: &str) -> Result<Option<DbGuild>, sqlx::Error> {
pub async fn get(db: &PgPool, guild_id: &str) -> Result<Option<DbGuild>> {
let guild: Option<DbGuild> = query_as!(
DbGuild,
"SELECT * FROM guilds WHERE guild_id = $1",
@ -73,7 +74,7 @@ pub async fn get(db: &PgPool, guild_id: &str) -> Result<Option<DbGuild>, sqlx::E
Ok(guild)
}
pub async fn get_log(db: &PgPool, guild_id: &str, asked: LogChannel) -> Result<Option<String>, sqlx::Error> {
pub async fn get_log(db: &PgPool, guild_id: &str, asked: LogChannel) -> Result<Option<String>> {
let sql: String = format!("SELECT {} FROM guilds WHERE guild_id = $1", log_select(asked));
let channel_id: Option<String> = query_scalar(&sql)
.bind(guild_id)
@ -82,7 +83,7 @@ pub async fn get_log(db: &PgPool, guild_id: &str, asked: LogChannel) -> Result<O
Ok(channel_id)
}
pub async fn set_log(db: &PgPool, guild_id: &str, asked: LogChannel, value: &str) -> Result<(), sqlx::Error> {
pub async fn set_log(db: &PgPool, guild_id: &str, asked: LogChannel, value: &str) -> Result<()> {
let sql: String = format!("UPDATE guilds set {} = $1 WHERE guild_id = $2", log_select(asked));
query(&sql)
.bind(value)
@ -92,7 +93,7 @@ pub async fn set_log(db: &PgPool, guild_id: &str, asked: LogChannel, value: &str
Ok(())
}
pub async fn get_protect(db: &PgPool, guild_id: &str, asked: Protect) -> Result<Option<bool>, sqlx::Error> {
pub async fn get_protect(db: &PgPool, guild_id: &str, asked: Protect) -> Result<Option<bool>> {
let sql: String = format!("SELECT {} FROM guilds WHERE guild_id = $1", protect_select(asked));
let state: Option<bool> = query_scalar(&sql)
.bind(guild_id)
@ -101,7 +102,7 @@ pub async fn get_protect(db: &PgPool, guild_id: &str, asked: Protect) -> Result<
Ok(state)
}
pub async fn set_protect(db: &PgPool, guild_id: &str, asked: Protect, value: &str) -> Result<(), sqlx::Error> {
pub async fn set_protect(db: &PgPool, guild_id: &str, asked: Protect, value: &str) -> Result<()> {
let sql: String = format!("UPDATE guilds set {} = $1 WHERE guild_id = $2", protect_select(asked));
query(&sql)
.bind(value)
@ -111,9 +112,9 @@ pub async fn set_protect(db: &PgPool, guild_id: &str, asked: Protect, value: &st
Ok(())
}
pub async fn get_or_create(db: &PgPool, guild_id: &str) -> Result<DbGuild, sqlx::Error> {
pub async fn get_or_create(db: &PgPool, guild_id: &str) -> Result<DbGuild> {
create(db, guild_id).await?;
get(db, guild_id)
.await?
.ok_or_else(|| sqlx::Error::RowNotFound)
.ok_or_else(|| sqlx::Error::RowNotFound.into())
}

View file

@ -1,11 +1,12 @@
use sqlx::{PgPool, query, query_as, query_scalar};
use crate::models::guild_user::DbGuildUser;
use anyhow::Result;
pub async fn get(
db: &PgPool,
user_id: &str,
guild_id: &str,
) -> Result<Option<DbGuildUser>, sqlx::Error> {
) -> Result<Option<DbGuildUser>> {
let guild_user = query_as!(
DbGuildUser,
"SELECT * FROM guild_users WHERE user_id = $1 AND guild_id = $2",
@ -21,7 +22,7 @@ pub async fn create(
db: &PgPool,
user_id: &str,
guild_id: &str,
) -> Result<(), sqlx::Error> {
) -> Result<()> {
query!(
"INSERT INTO guild_users (user_id, guild_id) \
VALUES ($1, $2) \
@ -38,7 +39,7 @@ pub async fn delete(
db: &PgPool,
user_id: &str,
guild_id: &str,
) -> Result<(), sqlx::Error> {
) -> Result<()> {
query!(
"DELETE FROM guild_users WHERE user_id = $1 AND guild_id = $2",
user_id,
@ -52,7 +53,7 @@ pub async fn delete(
pub async fn delete_all_in_guild(
db: &PgPool,
guild_id: &str,
) -> Result<(), sqlx::Error> {
) -> Result<()> {
query!("DELETE FROM guild_users WHERE guild_id = $1", guild_id)
.execute(db)
.await?;
@ -64,7 +65,7 @@ pub async fn add_xp(
user_id: &str,
guild_id: &str,
amount: i32,
) -> Result<(), sqlx::Error> {
) -> Result<()> {
query!(
"UPDATE guild_users SET xp = xp + $1 \
WHERE user_id = $2 AND guild_id = $3",
@ -82,7 +83,7 @@ pub async fn set_level(
user_id: &str,
guild_id: &str,
level: i32,
) -> Result<(), sqlx::Error> {
) -> Result<()> {
query!(
"UPDATE guild_users SET level = $1 \
WHERE user_id = $2 AND guild_id = $3",
@ -99,7 +100,7 @@ pub async fn get_xp(
db: &PgPool,
user_id: &str,
guild_id: &str,
) -> Result<Option<i32>, sqlx::Error> {
) -> Result<Option<i32>> {
let xp: Option<i32> = query_scalar(
"SELECT xp FROM guild_users WHERE user_id = $1 AND guild_id = $2",
)
@ -114,7 +115,7 @@ pub async fn get_level(
db: &PgPool,
user_id: &str,
guild_id: &str,
) -> Result<Option<i32>, sqlx::Error> {
) -> Result<Option<i32>> {
let level: Option<i32> = query_scalar("SELECT level FROM guild_users WHERE user_id = $1 AND guild_id = $2")
.bind(user_id)
.bind(guild_id)
@ -128,7 +129,7 @@ pub async fn set_wl(
user_id: &str,
guild_id: &str,
value: bool,
) -> Result<(), sqlx::Error> {
) -> Result<()> {
query!(
"UPDATE guild_users SET is_wl_user = $1 \
WHERE user_id = $2 AND guild_id = $3",
@ -144,7 +145,7 @@ pub async fn set_wl(
pub async fn get_all_wl(
db: &PgPool,
guild_id: &str,
) -> Result<Vec<DbGuildUser>, sqlx::Error> {
) -> Result<Vec<DbGuildUser>> {
let users = query_as!(
DbGuildUser,
"SELECT * FROM guild_users \
@ -161,7 +162,7 @@ pub async fn set_invited_by(
user_id: &str,
guild_id: &str,
inviter_id: &str,
) -> Result<(), sqlx::Error> {
) -> Result<()> {
query!(
"UPDATE guild_users SET invited_by = $1 \
WHERE user_id = $2 AND guild_id = $3",
@ -178,7 +179,7 @@ pub async fn increment_invitations(
db: &PgPool,
user_id: &str,
guild_id: &str,
) -> Result<(), sqlx::Error> {
) -> Result<()> {
query!(
"UPDATE guild_users SET invitation_count = invitation_count + 1 \
WHERE user_id = $1 AND guild_id = $2",
@ -194,7 +195,7 @@ pub async fn decrement_invitations(
db: &PgPool,
user_id: &str,
guild_id: &str,
) -> Result<(), sqlx::Error> {
) -> Result<()> {
query!(
"UPDATE guild_users SET invitation_count = GREATEST(invitation_count - 1, 0) \
WHERE user_id = $1 AND guild_id = $2",
@ -210,7 +211,7 @@ pub async fn leaderboard_xp(
db: &PgPool,
guild_id: &str,
limit: i64,
) -> Result<Vec<DbGuildUser>, sqlx::Error> {
) -> Result<Vec<DbGuildUser>> {
let users = query_as!(
DbGuildUser,
"SELECT * FROM guild_users \
@ -229,7 +230,7 @@ pub async fn leaderboard_invitations(
db: &PgPool,
guild_id: &str,
limit: i64,
) -> Result<Vec<DbGuildUser>, sqlx::Error> {
) -> Result<Vec<DbGuildUser>> {
let users = query_as!(
DbGuildUser,
"SELECT * FROM guild_users \
@ -243,9 +244,9 @@ pub async fn leaderboard_invitations(
.await?;
Ok(users)
}
pub async fn get_or_create(db: &PgPool, user_id: &str, guild_id: &str) -> Result<DbGuildUser, sqlx::Error> {
pub async fn get_or_create(db: &PgPool, user_id: &str, guild_id: &str) -> Result<DbGuildUser> {
create(db, user_id, guild_id).await?;
get(db, user_id, guild_id)
.await?
.ok_or_else(|| sqlx::Error::RowNotFound)
.ok_or_else(|| sqlx::Error::RowNotFound.into())
}

View file

@ -4,6 +4,7 @@ use sqlx::{
query_as,
};
use crate::models::DbUser;
use anyhow::Result;
/// Adding the user (if exist do nothing)
///
@ -12,8 +13,8 @@ use crate::models::DbUser;
///
/// # Errors
///
/// Returns `sqlx::Error` if the query fails.
pub async fn create(db: &PgPool, user_id: &str) -> Result<(), sqlx::Error> {
/// Returns `Error` if the query fails.
pub async fn create(db: &PgPool, user_id: &str) -> Result<()> {
query!("INSERT INTO users (user_id) VALUES ($1) ON CONFLICT DO NOTHING", user_id)
.execute(db)
.await?;
@ -32,8 +33,8 @@ pub async fn create(db: &PgPool, user_id: &str) -> Result<(), sqlx::Error> {
///
/// # Errors
///
/// Returns `sqlx::Error` if the query fails.
pub async fn get(db: &PgPool, user_id: &str) -> Result<Option<DbUser>, sqlx::Error> {
/// Returns `Error` if the query fails.
pub async fn get(db: &PgPool, user_id: &str) -> Result<Option<DbUser>> {
let user: Option<DbUser> = query_as!(
DbUser,
"SELECT * FROM users WHERE user_id = $1",
@ -52,8 +53,8 @@ pub async fn get(db: &PgPool, user_id: &str) -> Result<Option<DbUser>, sqlx::Err
///
/// # Errors
///
/// Returns `sqlx::Error` if the query fails.
pub async fn set_owner(db: &PgPool, user_id: &str, value: bool) -> Result<(), sqlx::Error> {
/// Returns `Error` if the query fails.
pub async fn set_owner(db: &PgPool, user_id: &str, value: bool) -> Result<()> {
query!("UPDATE users set is_owner = $1 WHERE user_id = $2", value, user_id)
.execute(db)
.await?;
@ -68,8 +69,8 @@ pub async fn set_owner(db: &PgPool, user_id: &str, value: bool) -> Result<(), sq
///
/// # Errors
///
/// Returns `sqlx::Error` if the query fails.
pub async fn set_buyer(db: &PgPool, user_id: &str, value: bool) -> Result<(), sqlx::Error> {
/// Returns `Error` if the query fails.
pub async fn set_buyer(db: &PgPool, user_id: &str, value: bool) -> Result<()> {
query!(
"UPDATE users set is_buyer = $1 WHERE user_id = $2",
value,
@ -80,9 +81,9 @@ pub async fn set_buyer(db: &PgPool, user_id: &str, value: bool) -> Result<(), sq
Ok(())
}
pub async fn get_or_create(db: &PgPool, user_id: &str) -> Result<DbUser, sqlx::Error> {
pub async fn get_or_create(db: &PgPool, user_id: &str) -> Result<DbUser> {
create(db, user_id).await?;
get(db, user_id)
.await?
.ok_or_else(|| sqlx::Error::RowNotFound)
.ok_or_else(|| anyhow::anyhow!("Not able to get or create the user"))
}

View file

@ -1,4 +1,4 @@
use serenity::all::*;
use serenity::all::{Context, Interaction};
use sqlx::PgPool;
use crate::commands::SlashCommand;
use crate::config::EmojiConfig;

View file

@ -11,13 +11,14 @@ use crate::models::bot::{
BotActivity,
BotPresence
};
use anyhow::Result;
pub struct ReadyHandler;
async fn fetch_all_members(
ctx: &Context,
guild_id: GuildId,
) -> Result<Vec<Member>, serenity::Error> {
) -> Result<Vec<Member>> {
let mut all_members: Vec<Member> = Vec::new();
let mut last_id: Option<UserId> = None;

View file

@ -5,22 +5,22 @@ mod events;
mod models;
mod utils;
use dotenvy::dotenv;
use events::Bot;
use serenity::all::*;
use serenity::Client;
use serenity::all::GatewayIntents;
use sqlx::postgres::PgPoolOptions;
use sqlx::{Pool, Postgres, migrate};
use std::env;
use tracing::{
info,
error
};
use tracing::{error, info};
use tracing_subscriber::fmt;
use self::config::emoji::EmojiConfig;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
dotenvy::dotenv().ok();
fmt::init();
dotenv().ok();
let token: String =
env::var("DISCORD_TOKEN").expect("❌ | DISCORD_TOKEN missing (check the env file)");

View file

@ -1,9 +1,11 @@
use anyhow::Result;
use sqlx::{
PgPool,
query_scalar,
};
use tracing::warn;
pub async fn is_whitelist(db: &PgPool, user_id: &str, guild_id: &str) -> Result<bool, sqlx::Error> {
pub async fn is_whitelist(db: &PgPool, user_id: &str, guild_id: &str) -> Result<bool> {
let result: Option<bool> = query_scalar(
"SELECT TRUE FROM guild_users gu \
LEFT JOIN users u ON u.user_id = gu.user_id \
@ -22,9 +24,19 @@ pub async fn is_whitelist(db: &PgPool, user_id: &str, guild_id: &str) -> Result<
Ok(result.is_some())
}
pub async fn is_owner(db: &PgPool, user_id: &str) -> Result<bool, sqlx::Error> {
pub async fn is_owner(db: &PgPool, user_id: &str) -> Result<bool> {
let result: bool = query_scalar(
"SELECT is_dev, is_buyer, is_owner FROM users WHERE user_id = $1 AND (is_dev = true OR is_buyer = true OR is_owner = true)",
)
.bind(user_id)
.fetch_one(db)
.await?;
Ok(result)
}
pub async fn is_buyer(db: &PgPool, user_id: &str) -> Result<bool> {
let result: Option<bool> = query_scalar(
"SELECT TRUE FROM users WHERE user_id = $1 AND is_dev = true OR is_buyer = true OR is_owner = true",
"SELECT is_dev, is_buyer FROM users WHERE user_id = $1 AND (is_dev = true OR is_buyer = true)",
)
.bind(user_id)
.fetch_optional(db)
@ -32,19 +44,9 @@ pub async fn is_owner(db: &PgPool, user_id: &str) -> Result<bool, sqlx::Error> {
Ok(result.is_some())
}
pub async fn is_buyer(db: &PgPool, user_id: &str) -> Result<bool, sqlx::Error> {
pub async fn is_dev(db: &PgPool, user_id: &str) -> Result<bool> {
let result: Option<bool> = query_scalar(
"SELECT TRUE FROM users WHERE user_id = $1 AND is_dev = true OR is_buyer = true",
)
.bind(user_id)
.fetch_optional(db)
.await?;
Ok(result.is_some())
}
pub async fn is_dev(db: &PgPool, user_id: &str) -> Result<bool, sqlx::Error> {
let result: Option<bool> = query_scalar(
"SELECT TRUE FROM users WHERE user_id = $1 AND is_dev = true",
"SELECT is_dev FROM users WHERE user_id = $1 AND is_dev = true",
)
.bind(user_id)
.fetch_optional(db)