Add basic moderator commands

This commit is contained in:
2025-08-23 00:02:10 -03:00
parent 8868b18be3
commit eaa38f3474
27 changed files with 752 additions and 249 deletions
+3 -6
View File
@@ -51,15 +51,13 @@ impl Command<State, Extras> for HelpCommand {
.component(HelpGoBackButton, 1)
.component(HelpSupportLinkButton, 1)
.await
.inspect_err(|e| log::error!("Failed to send message! {e}"))
.map_err(|_| CommandError::MessageSendingFailed)?;
.inspect_err(|e| log::error!("Failed to send message! {e}"))?;
} else {
ctx.send()
.embed(get_command_not_found_embed(&ctx.rt, command_name.0))
.component(HelpGoBackButton, 1)
.component(HelpSupportLinkButton, 1)
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
}
} else {
ctx.send()
@@ -67,8 +65,7 @@ impl Command<State, Extras> for HelpCommand {
.component(HelpWebsiteLinkButton, 1)
.component(HelpSupportLinkButton, 1)
.component(HelpDonateLinkButton, 1)
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
}
Ok(())
+34 -28
View File
@@ -2,7 +2,10 @@ use async_trait::async_trait;
use crate::{
extras::Extras,
framework::interactions::{InteractionError, components::Button, context::InteractionContext},
framework::{
interactions::{InteractionError, components::Button, context::InteractionContext},
messages::MessageEditBuilder,
},
groups::about::embeds::get_all_command_help_embed,
state::State,
};
@@ -12,8 +15,12 @@ pub struct HelpGoBackButton;
#[async_trait]
impl Button<State, Extras> for HelpGoBackButton {
fn label(&self) -> Option<&'static str> {
Some("← Go back to commands list")
fn id(&self) -> Option<String> {
Some("help:go-back".into())
}
fn label(&self) -> Option<String> {
Some("← Go back to commands list".into())
}
async fn on_press(
@@ -21,16 +28,15 @@ impl Button<State, Extras> for HelpGoBackButton {
ctx: InteractionContext<State, Extras>,
) -> Result<(), InteractionError> {
ctx
.original_message()
.expect(
"Buttons always have the original message in the interaction context, this one didn't (got None)"
.edit_original_message(
MessageEditBuilder::new().embed(
get_all_command_help_embed(&ctx.prefix, &ctx.rt, &ctx.extras)
)
.component(HelpWebsiteLinkButton, 1)
.component(HelpSupportLinkButton, 1)
.component(HelpDonateLinkButton, 1)
.component(CodeOfConductLinkButton, 1)
)
.edit()
.embed(get_all_command_help_embed(&ctx.prefix, &ctx.rt, &ctx.extras))
.component(HelpWebsiteLinkButton, 1)
.component(HelpSupportLinkButton, 1)
.component(HelpDonateLinkButton, 1)
.component(CodeOfConductLinkButton, 1)
.await
.inspect_err(|e| log::error!("An error occurred while attempting to edit the original message of an interaction. {e:?}"))
.map_err(
@@ -46,12 +52,12 @@ pub struct HelpSupportLinkButton;
#[async_trait]
impl Button<State, Extras> for HelpSupportLinkButton {
fn label(&self) -> Option<&'static str> {
Some("Get help")
fn label(&self) -> Option<String> {
Some("Get help".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://discord.gg/9daSsrfTmE")
fn url(&self) -> Option<String> {
Some("https://discord.gg/9daSsrfTmE".into())
}
}
@@ -60,12 +66,12 @@ pub struct HelpWebsiteLinkButton;
#[async_trait]
impl Button<State, Extras> for HelpWebsiteLinkButton {
fn label(&self) -> Option<&'static str> {
Some("Website")
fn label(&self) -> Option<String> {
Some("Website".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://payphone.lat/")
fn url(&self) -> Option<String> {
Some("https://payphone.lat/".into())
}
}
@@ -74,12 +80,12 @@ pub struct HelpDonateLinkButton;
#[async_trait]
impl Button<State, Extras> for HelpDonateLinkButton {
fn label(&self) -> Option<&'static str> {
Some("Donate")
fn label(&self) -> Option<String> {
Some("Donate".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://ko-fi.com/payphonedev")
fn url(&self) -> Option<String> {
Some("https://ko-fi.com/payphonedev".into())
}
}
@@ -88,11 +94,11 @@ pub struct CodeOfConductLinkButton;
#[async_trait]
impl Button<State, Extras> for CodeOfConductLinkButton {
fn label(&self) -> Option<&'static str> {
Some("Code of Conduct")
fn label(&self) -> Option<String> {
Some("Code of Conduct".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://payphone.lat/code-of-conduct")
fn url(&self) -> Option<String> {
Some("https://payphone.lat/code-of-conduct".into())
}
}
+31 -65
View File
@@ -66,8 +66,7 @@ impl Command<State, Extras> for CallCommand {
.await
.inspect_err(|e| {
log::error!("Failed to get or create channel: {e:?}");
})
.map_err(|_| CommandError::DatabaseFailed)?;
})?;
if channel.is_searching || self.channel_lock.contains(&ctx.event.channel_id.get()) {
ctx.send()
@@ -75,8 +74,7 @@ impl Command<State, Extras> for CallCommand {
"☎️ You are already searching for a call! Use `{}hangup` to hang up the phone.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
}
@@ -85,27 +83,21 @@ impl Command<State, Extras> for CallCommand {
ctx.send()
.content(format!("☎️ You are already on a call! Use `{}hangup` to hang up the phone, or `{}skip` to skip to the next call.", ctx.prefix, ctx.prefix))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
?;
return Ok(());
}
self.channel_lock
.insert_async(ctx.event.channel_id.get())
.await
.bye();
self.channel_lock.insert(ctx.event.channel_id.get()).bye();
let call = Call::start(&channel, &ctx.rt.state.db)
.await
.inspect_err(|e| {
log::error!("Failed to start call: {e:?}");
self.channel_lock.remove(&ctx.event.channel_id.get());
})
.map_err(|_| CommandError::DatabaseFailed)?;
})?;
self.channel_lock
.remove_async(&ctx.event.channel_id.get())
.await;
self.channel_lock.remove(&ctx.event.channel_id.get());
if let Some(call) = call {
ctx.send()
@@ -130,8 +122,7 @@ impl Command<State, Extras> for CallCommand {
get_string_tips(ctx.prefix),
get_string_call_searching(ctx.prefix)
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
}
Ok(())
@@ -168,8 +159,7 @@ impl Command<State, Extras> for SkipCommand {
.await
.inspect_err(|e| {
log::error!("Failed to get or create channel: {e:?}");
})
.map_err(|_| CommandError::DatabaseFailed)?;
})?;
if channel.call_id.is_none() {
ctx.send()
@@ -177,8 +167,7 @@ impl Command<State, Extras> for SkipCommand {
"❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
}
@@ -189,22 +178,19 @@ impl Command<State, Extras> for SkipCommand {
"☎️ You're already searching for a call! Use `{}hangup` to cancel the search.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
}
let call = Call::get_by_id(channel.call_id.unwrap(), &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))
.map_err(|_| CommandError::DatabaseFailed)?
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))?
.ok_or(CommandError::DatabaseInconsistentState)?;
call.hangup(&ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to hang up call: {e:?}"))
.map_err(|_| CommandError::DatabaseFailed)?;
.inspect_err(|e| log::error!("Failed to hang up call: {e:?}"))?;
let other_channel_id = call.other_party_channel_id(ctx.event.channel_id.get());
@@ -218,15 +204,13 @@ impl Command<State, Extras> for SkipCommand {
.await
.inspect_err(|e| {
log::error!("Failed to send message to other party: {e:?}");
})
.map_err(|_| CommandError::MessageSendingFailed)?;
})?;
let call = Call::start(&channel, &ctx.rt.state.db)
.await
.inspect_err(|e| {
log::error!("Failed to start (skipped) call: {e:?}");
})
.map_err(|_| CommandError::DatabaseFailed)?;
})?;
if let Some(call) = call {
ctx.send()
@@ -248,8 +232,7 @@ impl Command<State, Extras> for SkipCommand {
} else {
ctx.send()
.content("☎️ Skipped! Searching for a call...")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
}
Ok(())
@@ -280,16 +263,14 @@ impl Command<State, Extras> for HangupCommand {
) -> Result<(), CommandError> {
let Some(channel) = Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get channel: {e:?}"))
.map_err(|_| CommandError::DatabaseFailed)?
.inspect_err(|e| log::error!("Failed to get channel: {e:?}"))?
else {
ctx.send()
.content(format!(
"❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
};
@@ -300,13 +281,11 @@ impl Command<State, Extras> for HangupCommand {
.await
.inspect_err(|e| {
log::error!("Failed to cancel search: {e:?}");
})
.map_err(|_| CommandError::DatabaseFailed)?;
})?;
ctx.send()
.content(format!("☎️ {}", get_string_call_no_answer(ctx.prefix)))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
}
@@ -314,21 +293,16 @@ impl Command<State, Extras> for HangupCommand {
if let Some(call_id) = channel.call_id {
let Some(call) = Call::get_by_id(call_id, &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))
.map_err(|_| CommandError::DatabaseFailed)?
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))?
else {
ctx.send()
.content("❌ Call not found.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
ctx.send().content("❌ Call not found.").await?;
return Err(CommandError::DatabaseInconsistentState);
};
call.hangup(&ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to hang up call: {e:?}"))
.map_err(|_| CommandError::DatabaseFailed)?;
.inspect_err(|e| log::error!("Failed to hang up call: {e:?}"))?;
ctx.send()
.content(format!(
@@ -345,16 +319,14 @@ impl Command<State, Extras> for HangupCommand {
"☎️ {}",
get_string_call_hangup_other_party(ctx.prefix)
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
} else {
ctx.send()
.content(format!(
"❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
}
@@ -391,8 +363,7 @@ impl Command<State, Extras> for FriendRequestCommand {
) -> Result<(), CommandError> {
let channel = Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get channel: {e:?}"))
.map_err(|_| CommandError::DatabaseFailed)?;
.inspect_err(|e| log::error!("Failed to get channel: {e:?}"))?;
let Some(channel) = channel else {
ctx.send()
@@ -400,8 +371,7 @@ impl Command<State, Extras> for FriendRequestCommand {
"❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
};
@@ -409,16 +379,14 @@ impl Command<State, Extras> for FriendRequestCommand {
let call = if let Some(call_id) = channel.call_id {
Call::get_by_id(call_id, &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))
.map_err(|_| CommandError::DatabaseFailed)?
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))?
} else {
ctx.send()
.content(format!(
"❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
};
@@ -426,8 +394,7 @@ impl Command<State, Extras> for FriendRequestCommand {
let Some(call) = call else {
ctx.send()
.content("❌ Oops! We could not find that call.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Err(CommandError::DatabaseInconsistentState);
};
@@ -450,12 +417,11 @@ impl Command<State, Extras> for FriendRequestCommand {
)
)
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
?;
ctx.send()
.content("📬 Asked the other party to send you a friend request!")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
Ok(())
}
+8 -8
View File
@@ -4,12 +4,12 @@ use crate::{extras::Extras, framework::interactions::components::Button, state::
pub struct CodeOfConductButton;
impl Button<State, Extras> for CodeOfConductButton {
fn label(&self) -> Option<&'static str> {
Some("Code of Conduct")
fn label(&self) -> Option<String> {
Some("Code of Conduct".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://payphone.lat/code-of-conduct")
fn url(&self) -> Option<String> {
Some("https://payphone.lat/code-of-conduct".into())
}
}
@@ -17,11 +17,11 @@ impl Button<State, Extras> for CodeOfConductButton {
pub struct NeedHelpButton;
impl Button<State, Extras> for NeedHelpButton {
fn label(&self) -> Option<&'static str> {
Some("Need Help?")
fn label(&self) -> Option<String> {
Some("Need Help?".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://discord.gg/9daSsrfTmE")
fn url(&self) -> Option<String> {
Some("https://discord.gg/9daSsrfTmE".into())
}
}
+2 -4
View File
@@ -16,8 +16,7 @@ impl Permission<State, Extras> for NotBannedPermission {
async fn check(&self, ctx: &CommandContext<State, Extras>) -> Result<bool, CommandError> {
let incidents = UserIncident::get_for_user(ctx.event.author.id.get(), &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get user incidents: {e}"))
.map_err(|_| CommandError::DatabaseFailed)?;
.inspect_err(|e| log::error!("Failed to get user incidents: {e}"))?;
if incidents.iter().any(|i| i.is_active()) {
Ok(false)
@@ -37,8 +36,7 @@ impl Permission<State, Extras> for NotBannedPermission {
.await
.inspect_err(|e| {
log::error!("Failed to send message: {e}");
})
.map_err(|_| CommandError::MessageSendingFailed)?;
})?;
Ok(())
}
+12 -18
View File
@@ -6,7 +6,13 @@ use twilight_util::builder::embed::{
};
use crate::{
constants::COLOR_WHITE, database::models::User, discord::{images, sanitizing::SanitizeDiscordMarkdown}, extras::Extras, framework::commands::{context::CommandContext, Command, CommandError}, groups::leveling::constants::KEY_LEADERBOARD_MONTHLY, state::State
constants::COLOR_WHITE,
database::models::User,
discord::{images, sanitizing::SanitizeDiscordMarkdown},
extras::Extras,
framework::commands::{Command, CommandError, context::CommandContext},
groups::leveling::constants::KEY_LEADERBOARD_MONTHLY,
state::State,
};
#[derive(Debug)]
@@ -31,33 +37,22 @@ impl Command<State, Extras> for LeaderboardCommand {
ctx: CommandContext<'_, State, Extras>,
_args: &str,
) -> Result<(), CommandError> {
let mut redis = ctx
.rt
.state
.redis
.get()
.await
.map_err(CommandError::RedisPoolFailed)?;
let mut redis = ctx.rt.state.redis.get().await?;
let top: Vec<(u64, f64)> = redis
.zrevrange_withscores(KEY_LEADERBOARD_MONTHLY, 0, 9)
.await
.map_err(CommandError::RedisFailed)?;
.await?;
log::trace!("Top users for leaderboard: {top:?}");
let current_user_rank: Option<usize> = redis
.zrevrank(KEY_LEADERBOARD_MONTHLY, ctx.event.author.id.get())
.await
.map_err(CommandError::RedisFailed)?;
.await?;
let mut users = Vec::new();
for (user_id, score) in top {
let Some(user) = User::get_by_id(user_id, &ctx.rt.state.db)
.await
.map_err(|_| CommandError::DatabaseFailed)?
else {
let Some(user) = User::get_by_id(user_id, &ctx.rt.state.db).await? else {
log::trace!("User ID {user_id} not found for leaderboard");
continue;
};
@@ -130,8 +125,7 @@ impl Command<State, Extras> for LeaderboardCommand {
ctx.send()
.embed(embed.build())
.await
.inspect_err(|e| log::error!("Failed to send leaderboard embed: {e}"))
.map_err(|_| CommandError::MessageSendingFailed)?;
.inspect_err(|e| log::error!("Failed to send leaderboard embed: {e}"))?;
Ok(())
}
+3 -10
View File
@@ -22,10 +22,7 @@ use crate::{
/// [`Result<User, ArgumentParser>`] - The user from the DB, or an [`ArgumentParsingError`] ready
/// to be returned by the parser.
async fn get_user_by_id(id: u64, db: &Session) -> Result<User, ArgumentParsingError> {
let Some(user) = User::get_by_id(id, db)
.await
.map_err(|_| ArgumentParsingError::DatabaseFailed)?
else {
let Some(user) = User::get_by_id(id, db).await? else {
return Err(ArgumentParsingError::InvalidArgument);
};
Ok(user)
@@ -49,8 +46,7 @@ async fn user_from_reply_or_command_executor(
if referenced.author.bot {
if let Some(message) =
Message::get_by_propagation_message_id(referenced.id.get(), &ctx.rt.state.db)
.await
.map_err(|_| ArgumentParsingError::DatabaseFailed)?
.await?
{
return get_user_by_id(message.author_id, &ctx.rt.state.db).await;
}
@@ -112,10 +108,7 @@ impl FromArguments<State, Extras> for UserArgument {
} else {
// The argument is (probably) a username.
let Some(db_user) = User::get_by_name(identifier.0, &ctx.rt.state.db)
.await
.map_err(|_| ArgumentParsingError::DatabaseFailed)?
else {
let Some(db_user) = User::get_by_name(identifier.0, &ctx.rt.state.db).await? else {
// Check in the message's reply, and if not use the command executor.
user = user_from_reply_or_command_executor(ctx).await?;
+11 -29
View File
@@ -1,7 +1,6 @@
use async_trait::async_trait;
use crate::{
database::models::UserIncident,
extras::Extras,
framework::{
commands::{
@@ -14,10 +13,10 @@ use crate::{
},
groups::moderation::{
arguments::UserArgument,
get_incident_page,
permissions::{BotModeratorPermission, BotOwnerPermission},
},
state::State,
utils::Bye,
};
#[derive(Debug)]
@@ -58,14 +57,11 @@ impl Command<State, Extras> for ModeratorCommand {
Ok(arg) => arg,
Err(e) => match e {
ArgumentParsingError::InvalidArgument => {
ctx.send()
.content("❌ User not found in DB.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
ctx.send().content("❌ User not found in DB.").await?;
return Ok(());
}
ArgumentParsingError::DatabaseFailed => {
return Err(CommandError::DatabaseFailed);
ArgumentParsingError::DatabaseFailed(e) => {
return Err(CommandError::DatabaseFailed(e));
}
e => {
unreachable!("Unexpected error: {e}");
@@ -75,9 +71,7 @@ impl Command<State, Extras> for ModeratorCommand {
user.is_moderator = !user.is_moderator;
user.insert(&ctx.rt.state.db)
.await
.map_err(|_| CommandError::DatabaseFailed)?;
user.insert(&ctx.rt.state.db).await?;
ctx.send()
.content(format!(
@@ -89,8 +83,7 @@ impl Command<State, Extras> for ModeratorCommand {
"**is no longer** a moderator"
}
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
Ok(())
}
@@ -126,14 +119,11 @@ impl Command<State, Extras> for IncidentsCommand {
Ok(Arg(user)) => user,
Err(e) => match e {
ArgumentParsingError::InvalidArgument => {
ctx.send()
.content("❌ User not found in DB.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
ctx.send().content("❌ User not found in DB.").await?;
return Ok(());
}
ArgumentParsingError::DatabaseFailed => {
return Err(CommandError::DatabaseFailed);
ArgumentParsingError::DatabaseFailed(e) => {
return Err(CommandError::DatabaseFailed(e));
}
e => {
unreachable!("Unexpected error: {e}");
@@ -141,17 +131,9 @@ impl Command<State, Extras> for IncidentsCommand {
},
};
let incidents = UserIncident::get_for_user(user.id, &ctx.rt.state.db)
.await
.map_err(|_| CommandError::DatabaseFailed)?;
let message = get_incident_page(user.id, &ctx.rt.state.db, 0).await?;
ctx.send()
.content(format!(
"Great! The user fetched from the DB is {}",
user.name
))
.await
.bye();
ctx.send_from_builder(message).await?;
Ok(())
}
+135
View File
@@ -0,0 +1,135 @@
use async_trait::async_trait;
use twilight_model::channel::message::component::ButtonStyle;
use crate::{
database::models::UserIncident,
extras::Extras,
framework::interactions::{InteractionError, components::Button, context::InteractionContext},
groups::moderation::get_incident_page,
state::State,
utils::get_random_u64,
};
#[derive(Debug)]
pub struct ArrowIncidentButton {
pub arrow: char,
pub user_id: u64,
pub go_to: Option<usize>,
}
#[async_trait]
impl Button<State, Extras> for ArrowIncidentButton {
fn id(&self) -> Option<String> {
Some(format!("incidents:arrow:{}", get_random_u64()))
}
fn label(&self) -> Option<String> {
Some(format!("{}", self.arrow))
}
fn disabled(&self) -> bool {
self.go_to.is_none()
}
async fn on_press(
&self,
ctx: InteractionContext<State, Extras>,
) -> Result<(), InteractionError> {
if !ctx.extras.user.is_moderator {
ctx.defer().await?;
return Ok(());
}
if let Some(go_to) = self.go_to {
ctx.edit_original_message(
get_incident_page(self.user_id, &ctx.rt.state.db, go_to)
.await
.inspect_err(|e| log::error!("Failed to get incident page: {e:?}"))?
.into(),
)
.await
.inspect_err(|e| log::error!("Failed to edit original message: {e:?}"))?;
} else {
ctx.defer().await?;
}
Ok(())
}
}
#[derive(Debug)]
pub struct CounterButton {
pub current: usize,
pub total: usize,
}
#[async_trait]
impl Button<State, Extras> for CounterButton {
fn id(&self) -> Option<String> {
Some("incidents:counter".into())
}
fn label(&self) -> Option<String> {
Some(format!("{}/{}", self.current, self.total))
}
fn disabled(&self) -> bool {
true
}
}
#[derive(Debug)]
pub struct DeleteIncidentButton {
pub user_id: u64,
pub incident_id: u64,
pub incident_index: usize,
}
#[async_trait]
impl Button<State, Extras> for DeleteIncidentButton {
fn id(&self) -> Option<String> {
Some(format!("incidents:delete:{}", get_random_u64()))
}
fn label(&self) -> Option<String> {
Some("Delete Incident".into())
}
fn style(&self) -> ButtonStyle {
ButtonStyle::Danger
}
fn disabled(&self) -> bool {
false
}
async fn on_press(
&self,
ctx: InteractionContext<State, Extras>,
) -> Result<(), InteractionError> {
if !ctx.extras.user.is_moderator {
ctx.defer().await?;
return Ok(());
}
UserIncident::delete_by_user_and_incident_id(
self.user_id,
self.incident_id,
&ctx.rt.state.db,
)
.await?;
let new_page_index = self.incident_index.saturating_sub(1);
ctx.edit_original_message(
get_incident_page(self.user_id, &ctx.rt.state.db, new_page_index)
.await
.inspect_err(|e| log::error!("Failed to get incident page: {e:?}"))?
.into(),
)
.await
.inspect_err(|e| log::error!("Failed to edit original message: {e:?}"))?;
Ok(())
}
}
+102
View File
@@ -0,0 +1,102 @@
use time::UtcDateTime;
use twilight_model::channel::message::Embed;
use twilight_util::builder::embed::{
EmbedAuthorBuilder, EmbedBuilder, EmbedFieldBuilder, ImageSource,
};
use crate::{
constants::{COLOR_RED, COLOR_YELLOW},
database::models::{UserIncident, UserIncidentType},
utils::ellipse,
};
fn format_timestamp(timestamp: UtcDateTime) -> String {
format!(
"<t:{}> (<t:{}:R>)",
timestamp.unix_timestamp(),
timestamp.unix_timestamp()
)
}
pub fn incident_embed(incident: &UserIncident) -> Embed {
if let Some(message) = &incident.message {
let mut builder = EmbedBuilder::new()
.color(match incident.r#type {
UserIncidentType::Ban => COLOR_RED,
UserIncidentType::Warning => COLOR_YELLOW,
})
.author(
EmbedAuthorBuilder::new(&message.author_name)
.icon_url(ImageSource::url(&message.author_avatar_url).unwrap()),
)
.title("Message Incident")
.thumbnail(ImageSource::url(message.author_avatar_url.clone()).unwrap())
.field(EmbedFieldBuilder::new("Message", ellipse(message.content.clone(), 100)).build())
.field(EmbedFieldBuilder::new("Author Name", message.author_name.clone()).build())
.field(
EmbedFieldBuilder::new(
"Author Avatar",
format!("[Click to open avatar](<{}>)", &message.author_avatar_url),
)
.build(),
)
.field(
EmbedFieldBuilder::new("Created At", format_timestamp(incident.created_at)).build(),
)
.field(EmbedFieldBuilder::new(
"Created By",
incident
.created_by_id
.map(|id| format!("<@{id}>"))
.unwrap_or("Automod".into()),
));
if incident.r#type == UserIncidentType::Ban {
builder = builder.field(
EmbedFieldBuilder::new(
"Expires At",
incident
.expires_at
.map(format_timestamp)
.unwrap_or("*Never*".into()),
)
.build(),
);
}
builder.build()
} else {
let mut builder = EmbedBuilder::new()
.color(match incident.r#type {
UserIncidentType::Ban => COLOR_RED,
UserIncidentType::Warning => COLOR_YELLOW,
})
.title("Manual Incident")
.field(EmbedFieldBuilder::new("Reason", incident.reason.clone()))
.field(
EmbedFieldBuilder::new("Created At", format_timestamp(incident.created_at)).build(),
)
.field(EmbedFieldBuilder::new(
"Created By",
incident
.created_by_id
.map(|id| format!("<@{id}>"))
.unwrap_or("Automod".into()),
));
if incident.r#type == UserIncidentType::Ban {
builder = builder.field(
EmbedFieldBuilder::new(
"Expires At",
incident
.expires_at
.map(format_timestamp)
.unwrap_or("*Never*".into()),
)
.build(),
);
}
builder.build()
}
}
+65
View File
@@ -1,3 +1,68 @@
use scylla::client::session::Session;
use crate::{
database::models::{DatabaseError, UserIncident},
extras::Extras,
framework::messages::MessageBuilder,
groups::moderation::{
components::{ArrowIncidentButton, CounterButton, DeleteIncidentButton},
embeds::incident_embed,
},
state::State,
};
pub mod arguments;
pub mod commands;
pub mod components;
pub(super) mod embeds;
pub mod permissions;
pub(super) async fn get_incident_page(
user_id: u64,
session: &Session,
page_index: usize,
) -> Result<MessageBuilder<State, Extras>, DatabaseError> {
let incidents = UserIncident::get_for_user(user_id, session).await?;
if let Some(incident) = incidents.get(page_index) {
Ok(MessageBuilder::new()
.embed(incident_embed(incident))
.component(
ArrowIncidentButton {
arrow: '<',
user_id,
go_to: if page_index > 0 {
Some(page_index - 1)
} else {
None
},
},
1,
)
.component(
CounterButton {
current: page_index + 1,
total: incidents.len(),
},
1,
)
.component(
ArrowIncidentButton {
arrow: '>',
user_id,
go_to: incidents.get(page_index + 1).map(|_| page_index + 1),
},
1,
)
.component(
DeleteIncidentButton {
incident_id: incident.incident_id,
incident_index: page_index,
user_id,
},
1,
))
} else {
Ok(MessageBuilder::new().content("No incidents found for this user."))
}
}
+2 -4
View File
@@ -21,14 +21,12 @@ impl Permission<State, Extras> for BotOwnerPermission {
) -> Result<(), CommandError> {
ctx.send()
.content("⛔ Not enough aura to run this command.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
Ok(())
}
}
#[derive(Debug)]
pub struct BotModeratorPermission;
@@ -45,7 +43,7 @@ impl Permission<State, Extras> for BotModeratorPermission {
ctx.send()
.content("⛔ You're not a Payphone moderator.\n-# If you need to check your incidents, contact a Payphone moderator in the official server.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
?;
Ok(())
}
+15 -13
View File
@@ -1,9 +1,18 @@
use async_trait::async_trait;
use crate::{
constants::DEFAULT_PREFIX, database::models::Server, discord::sanitizing::SanitizeDiscordMarkdown, extras::Extras, framework::commands::{
arguments::{Arg, Argument, GreedyString, ParseArguments}, context::CommandContext, permissions::Permission, Command, CommandError
}, groups::servers::permissions::{GuildOnlyPermission, ServerModeratorPermission}, state::State
constants::DEFAULT_PREFIX,
database::models::Server,
discord::sanitizing::SanitizeDiscordMarkdown,
extras::Extras,
framework::commands::{
Command, CommandError,
arguments::{Arg, Argument, GreedyString, ParseArguments},
context::CommandContext,
permissions::Permission,
},
groups::servers::permissions::{GuildOnlyPermission, ServerModeratorPermission},
state::State,
};
#[derive(Debug)]
@@ -55,18 +64,14 @@ impl Command<State, Extras> for PrefixCommand {
&ctx.rt.http,
)
.await
.inspect_err(|e| log::error!("Failed to get or create server: {e}"))
.map_err(|_| CommandError::DatabaseFailed)?;
.inspect_err(|e| log::error!("Failed to get or create server: {e}"))?;
if prefix.is_empty() {
prefix = DEFAULT_PREFIX;
}
server.prefix = prefix.to_string();
server
.upsert(&ctx.rt.state.db)
.await
.map_err(|_| CommandError::DatabaseFailed)?;
server.upsert(&ctx.rt.state.db).await?;
ctx.send()
.content(format!(
@@ -74,10 +79,7 @@ impl Command<State, Extras> for PrefixCommand {
prefix.sanitize(false)
))
.await
.map_err(|e| {
log::error!("Failed to send prefix update message: {e}");
CommandError::MessageSendingFailed
})?;
.inspect_err(|e| log::error!("Failed to send prefix update message: {e}"))?;
Ok(())
}
+2 -4
View File
@@ -49,11 +49,9 @@ impl Permission<State, Extras> for ServerModeratorPermission {
.rt
.http
.guild_member(guild_id, ctx.event.author.id)
.await
.map_err(CommandError::DiscordAPIFailed)?
.await?
.model()
.await
.map_err(CommandError::DiscordDeserializationFailed)?;
.await?;
let Some(everyone_role) = ctx.rt.cache.role(guild_id.cast()) else {
log::warn!("Could not get @everyone role for guild ID {guild_id}!");