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
Generated
+1 -1
View File
@@ -1437,7 +1437,7 @@ checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
[[package]] [[package]]
name = "payphone" name = "payphone"
version = "4.1.1" version = "4.2.3"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"axum", "axum",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "payphone" name = "payphone"
version = "4.1.1" version = "4.2.3"
edition = "2024" edition = "2024"
default-run = "payphone" default-run = "payphone"
+3 -1
View File
@@ -103,7 +103,9 @@
"--database-password", "--database-password",
"cassandra", "cassandra",
"--redis-urls", "--redis-urls",
"redis://redis-cluster.redis" "redis://redis-cluster.redis",
"--bot-owner-id",
"1357199907512914051"
] ]
envFrom: envFrom:
- secretRef: - secretRef:
+22
View File
@@ -1614,4 +1614,26 @@ impl UserIncident {
Ok(()) Ok(())
} }
pub async fn delete_by_user_and_incident_id(
user_id: u64,
incident_id: u64,
session: &Session,
) -> Result<(), DatabaseError> {
let user_id = u64_to_i64(user_id);
let incident_id = u64_to_i64(incident_id);
session
.query_unpaged(
r#"
DELETE FROM payphone.user_incidents
WHERE user_id = ? AND incident_id = ?;
"#,
(user_id, incident_id),
)
.await
.map_err(DatabaseError::QueryError)?;
Ok(())
}
} }
+18 -6
View File
@@ -5,7 +5,7 @@ use std::{
use thiserror::Error; use thiserror::Error;
use crate::framework::commands::context::CommandContext; use crate::{database::models::DatabaseError, framework::commands::context::CommandContext};
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum ArgumentParsingError { pub enum ArgumentParsingError {
@@ -16,7 +16,7 @@ pub enum ArgumentParsingError {
InvalidArgument, InvalidArgument,
#[error("A database operation failed")] #[error("A database operation failed")]
DatabaseFailed, DatabaseFailed(#[from] DatabaseError),
} }
pub trait FromArguments<S, E>: Sized { pub trait FromArguments<S, E>: Sized {
@@ -218,7 +218,10 @@ impl<T, S, E> ParseArguments<S, E> for Arg<T>
where where
T: FromArguments<S, E>, T: FromArguments<S, E>,
{ {
async fn parse(args: &str, ctx: &CommandContext<'_, S, E>) -> Result<Self, ArgumentParsingError> { async fn parse(
args: &str,
ctx: &CommandContext<'_, S, E>,
) -> Result<Self, ArgumentParsingError> {
let (value, _) = T::from_args(args, ctx).await?; let (value, _) = T::from_args(args, ctx).await?;
Ok(Arg(value)) Ok(Arg(value))
@@ -229,7 +232,10 @@ impl<A, S, E> ParseArguments<S, E> for (A,)
where where
A: FromArguments<S, E>, A: FromArguments<S, E>,
{ {
async fn parse(args: &str, ctx: &CommandContext<'_, S, E>) -> Result<Self, ArgumentParsingError> { async fn parse(
args: &str,
ctx: &CommandContext<'_, S, E>,
) -> Result<Self, ArgumentParsingError> {
let (a, _) = A::from_args(args, ctx).await?; let (a, _) = A::from_args(args, ctx).await?;
Ok((a,)) Ok((a,))
@@ -241,7 +247,10 @@ where
A: FromArguments<S, E>, A: FromArguments<S, E>,
B: FromArguments<S, E>, B: FromArguments<S, E>,
{ {
async fn parse(args: &str, ctx: &CommandContext<'_, S, E>) -> Result<Self, ArgumentParsingError> { async fn parse(
args: &str,
ctx: &CommandContext<'_, S, E>,
) -> Result<Self, ArgumentParsingError> {
let (a, args) = A::from_args(args, ctx).await?; let (a, args) = A::from_args(args, ctx).await?;
let (b, _) = B::from_args(args, ctx).await?; let (b, _) = B::from_args(args, ctx).await?;
@@ -255,7 +264,10 @@ where
B: FromArguments<S, E>, B: FromArguments<S, E>,
C: FromArguments<S, E>, C: FromArguments<S, E>,
{ {
async fn parse(args: &str, ctx: &CommandContext<'_, S, E>) -> Result<Self, ArgumentParsingError> { async fn parse(
args: &str,
ctx: &CommandContext<'_, S, E>,
) -> Result<Self, ArgumentParsingError> {
let (a, args) = A::from_args(args, ctx).await?; let (a, args) = A::from_args(args, ctx).await?;
let (b, args) = B::from_args(args, ctx).await?; let (b, args) = B::from_args(args, ctx).await?;
let (c, _) = C::from_args(args, ctx).await?; let (c, _) = C::from_args(args, ctx).await?;
+64 -2
View File
@@ -1,8 +1,15 @@
use std::sync::Arc; use std::sync::Arc;
use twilight_model::gateway::payload::incoming::MessageCreate; use twilight_http::{Error, Response};
use twilight_model::{
channel::{Message, message::Component},
gateway::payload::incoming::MessageCreate,
};
use crate::framework::{commands::messages::MessageSender, runtime::Runtime}; use crate::framework::{
commands::messages::MessageSender, interactions::components::ActionRow,
messages::MessageBuilder, runtime::Runtime,
};
pub struct CommandContext<'a, T, E> { pub struct CommandContext<'a, T, E> {
pub event: &'a MessageCreate, pub event: &'a MessageCreate,
@@ -33,4 +40,59 @@ where
pub fn send(&self) -> MessageSender<T, E> { pub fn send(&self) -> MessageSender<T, E> {
MessageSender::new(self.event.channel_id, self.rt.clone()) MessageSender::new(self.event.channel_id, self.rt.clone())
} }
pub async fn send_from_builder(
&self,
builder: MessageBuilder<T, E>,
) -> Result<Response<Message>, Error> {
let mut sender = self.rt.http.create_message(self.event.channel_id);
if let Some(content) = &builder.content {
sender = sender.content(content);
}
let mut current_row = ActionRow::new(&[]);
let mut current_index = 0;
let mut rows: Vec<Component> = vec![];
let mut custom_ids: Vec<String> = vec![];
for (component, index) in builder.components {
if index != current_index {
if !current_row.is_empty() {
rows.push(current_row.build());
current_row = ActionRow::new(&[]);
}
current_index += 1;
}
let custom_id = component.custom_id();
if let Some(custom_id) = &custom_id {
custom_ids.push(custom_id.clone());
self.rt.registry.register(custom_id, component.clone());
}
current_row.add(custom_id.clone(), component.clone());
}
if !current_row.is_empty() {
rows.push(current_row.build());
}
sender = sender.components(&rows);
sender = sender.embeds(&builder.embeds);
let result = sender.await;
if result.is_err() {
for custom_id in custom_ids {
self.rt.registry.unregister(custom_id);
}
}
result
}
} }
+6 -6
View File
@@ -5,9 +5,9 @@ use deadpool_redis::{cluster::PoolError, redis::RedisError};
use thiserror::Error; use thiserror::Error;
use twilight_http::response::DeserializeBodyError; use twilight_http::response::DeserializeBodyError;
use crate::framework::{commands::{ use crate::{database::models::{DatabaseError, DatabaseOrDiscordError}, framework::{commands::{
arguments::Argument, context::CommandContext, permissions::Permission, arguments::Argument, context::CommandContext, permissions::Permission,
}, runtime::Runtime}; }, runtime::Runtime}};
pub mod arguments; pub mod arguments;
pub mod context; pub mod context;
@@ -18,11 +18,8 @@ pub mod runner;
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum CommandError { pub enum CommandError {
#[error("A message was attempted to be sent but it failed")]
MessageSendingFailed,
#[error("A database query failed")] #[error("A database query failed")]
DatabaseFailed, DatabaseFailed(#[from] DatabaseError),
#[error("A database operation failed due to an inconsistent state")] #[error("A database operation failed due to an inconsistent state")]
DatabaseInconsistentState, DatabaseInconsistentState,
@@ -41,6 +38,9 @@ pub enum CommandError {
#[error(transparent)] #[error(transparent)]
RedisFailed(#[from] RedisError), RedisFailed(#[from] RedisError),
#[error(transparent)]
DatabaseOrDiscordError(#[from] DatabaseOrDiscordError)
} }
#[async_trait] #[async_trait]
+10 -3
View File
@@ -64,7 +64,7 @@ where
fn build(&self, id: Option<String>) -> TwilightComponent { fn build(&self, id: Option<String>) -> TwilightComponent {
TwilightComponent::Button(TwilightButton { TwilightComponent::Button(TwilightButton {
custom_id: id, custom_id: id,
disabled: false, disabled: self.disabled(),
emoji: None, emoji: None,
label: self.label().map(|i| i.to_string()), label: self.label().map(|i| i.to_string()),
style: if self.url().is_none() { style: if self.url().is_none() {
@@ -95,16 +95,23 @@ where
None None
} }
} }
fn style(&self) -> ButtonStyle { fn style(&self) -> ButtonStyle {
ButtonStyle::Secondary ButtonStyle::Secondary
} }
fn label(&self) -> Option<&'static str> {
fn label(&self) -> Option<String> {
None None
} }
fn url(&self) -> Option<&'static str> {
fn url(&self) -> Option<String> {
None None
} }
fn disabled(&self) -> bool {
false
}
async fn on_press(&self, ctx: InteractionContext<S, E>) -> Result<(), InteractionError> { async fn on_press(&self, ctx: InteractionContext<S, E>) -> Result<(), InteractionError> {
ctx.defer().await ctx.defer().await
} }
+80 -25
View File
@@ -1,13 +1,16 @@
use std::sync::Arc; use std::sync::Arc;
use twilight_http::{Error, Response, response::marker::EmptyBody};
use twilight_model::{ use twilight_model::{
gateway::payload::incoming::InteractionCreate, gateway::payload::incoming::InteractionCreate,
http::interaction::{InteractionResponse, InteractionResponseType}, http::interaction::{InteractionResponse, InteractionResponseType},
id::{Id, marker::InteractionMarker},
}; };
use twilight_util::builder::InteractionResponseDataBuilder;
use crate::framework::{ use crate::framework::{
commands::messages::OriginalMessageUpdater, interactions::InteractionError, runtime::Runtime, interactions::{InteractionError, components::ActionRow},
messages::MessageEditBuilder,
runtime::Runtime,
}; };
pub struct InteractionContext<T, E> { pub struct InteractionContext<T, E> {
@@ -17,7 +20,11 @@ pub struct InteractionContext<T, E> {
pub extras: E, pub extras: E,
} }
impl<T, E> InteractionContext<T, E> { impl<T, E> InteractionContext<T, E>
where
T: Send + Sync + 'static,
E: Send + Sync + 'static,
{
pub fn new( pub fn new(
event: InteractionCreate, event: InteractionCreate,
rt: Arc<Runtime<T, E>>, rt: Arc<Runtime<T, E>>,
@@ -44,37 +51,85 @@ impl<T, E> InteractionContext<T, E> {
kind: InteractionResponseType::DeferredUpdateMessage, kind: InteractionResponseType::DeferredUpdateMessage,
}, },
) )
.await .await?;
.map_err(|_| InteractionError::DeferringFailed)?;
Ok(()) Ok(())
} }
pub fn original_message(&self) -> Option<OriginalMessage<T, E>> { pub async fn edit_original_message(
self.event.message.as_ref().map(|_| OriginalMessage { &self,
interaction_id: self.event.id, builder: MessageEditBuilder<T, E>,
interaction_token: self.event.token.clone(), ) -> Result<Response<EmptyBody>, Error> {
rt: self.rt.clone(), let mut sender = InteractionResponseDataBuilder::new();
})
if let Some(content) = &builder.content {
if let Some(content) = content {
sender = sender.content(content);
} else {
sender = sender.content("");
} }
} }
pub struct OriginalMessage<T, E> { let mut current_row = ActionRow::new(&[]);
interaction_id: Id<InteractionMarker>, let mut current_index = 0;
interaction_token: String,
rt: Arc<Runtime<T, E>>, let mut custom_ids: Vec<String> = vec![];
if let Some(components) = builder.components {
let mut rows = vec![];
for (component, index) in components {
if index != current_index {
if !current_row.is_empty() {
rows.push(current_row.build());
current_row = ActionRow::new(&[]);
} }
impl<T, E> OriginalMessage<T, E> current_index += 1;
where }
T: Send + Sync + 'static,
E: Send + Sync + 'static, let custom_id = component.custom_id();
{
pub fn edit(&self) -> OriginalMessageUpdater<T, E> { if let Some(custom_id) = &custom_id {
OriginalMessageUpdater::new( custom_ids.push(custom_id.clone());
self.interaction_id,
self.interaction_token.clone(), self.rt.registry.register(custom_id, component.clone());
self.rt.clone(), }
current_row.add(custom_id.clone(), component.clone());
}
if !current_row.is_empty() {
rows.push(current_row.build());
}
sender = sender.components(rows);
}
if let Some(embeds) = builder.embeds {
sender = sender.embeds(embeds);
}
let result = self
.rt
.http
.interaction(self.rt.app.id)
.create_response(
self.event.id,
&self.event.token,
&InteractionResponse {
data: Some(sender.build()),
kind: InteractionResponseType::UpdateMessage,
},
) )
.await;
if result.is_err() {
for custom_id in custom_ids {
self.rt.registry.unregister(custom_id);
}
}
result
} }
} }
+8 -3
View File
@@ -1,5 +1,7 @@
use thiserror::Error; use thiserror::Error;
use crate::database::models::DatabaseError;
pub mod components; pub mod components;
pub mod context; pub mod context;
pub mod registry; pub mod registry;
@@ -12,9 +14,6 @@ pub enum InteractionError {
)] )]
InteractionNotFound, InteractionNotFound,
#[error("The interaction was attempted to be deferred, but it failed to be done")]
DeferringFailed,
#[error("Discord responded with an interaction type Payphone does not use")] #[error("Discord responded with an interaction type Payphone does not use")]
InteractionTypeUnsent, InteractionTypeUnsent,
@@ -26,4 +25,10 @@ pub enum InteractionError {
#[error("The extras getter failed to retrieve extras")] #[error("The extras getter failed to retrieve extras")]
ExtrasGetterFailed, ExtrasGetterFailed,
#[error(transparent)]
DatabaseError(#[from] DatabaseError),
#[error(transparent)]
DiscordAPIError(#[from] twilight_http::Error),
} }
+9 -2
View File
@@ -47,7 +47,10 @@ where
if let Some(data) = &event.data { if let Some(data) = &event.data {
match data { match data {
InteractionData::MessageComponent(data) => { InteractionData::MessageComponent(data) => {
if let Some(component) = self.inner.get_async(&data.custom_id).await { if let Some(guarded_component) = self.inner.get(&data.custom_id) {
let component = guarded_component.clone();
drop(guarded_component);
let prefixes = rt let prefixes = rt
.get_prefixes( .get_prefixes(
event.guild_id.map(|id| id.get()), event.guild_id.map(|id| id.get()),
@@ -60,7 +63,7 @@ where
let extras = extras let extras = extras
.get_extra( .get_extra(
&event.author().expect("Component interaction had no author"), event.author().expect("Component interaction had no author"),
&rt, &rt,
) )
.await .await
@@ -77,6 +80,10 @@ where
extras, extras,
)) ))
.await .await
.inspect(|_| log::debug!("Executed component interaction"))
.inspect_err(|e| {
log::error!("Interaction execution failed: {e:?}")
})
} else { } else {
Err(InteractionError::InteractionNotFound) Err(InteractionError::InteractionNotFound)
} }
+96
View File
@@ -0,0 +1,96 @@
use std::sync::Arc;
use twilight_model::channel::message::Embed;
use crate::framework::interactions::components::Component;
type ComponentWithRowIndex<S, E> = (Arc<dyn Component<S, E>>, usize);
pub struct MessageBuilder<S, E> {
pub content: Option<String>,
pub embeds: Vec<Embed>,
pub components: Vec<ComponentWithRowIndex<S, E>>,
}
impl<S, E> MessageBuilder<S, E> {
pub fn new() -> Self {
Self {
content: None,
embeds: Vec::new(),
components: Vec::new(),
}
}
pub fn content(mut self, content: impl Into<String>) -> Self {
self.content = Some(content.into());
self
}
pub fn embed(mut self, embed: Embed) -> Self {
self.embeds.push(embed);
self
}
pub fn component(mut self, component: impl Component<S, E> + 'static, row: usize) -> Self {
self.components.push((Arc::new(component), row));
self
}
}
pub struct MessageEditBuilder<S, E> {
pub content: Option<Option<String>>,
pub embeds: Option<Vec<Embed>>,
pub components: Option<Vec<ComponentWithRowIndex<S, E>>>,
}
impl<S, E> MessageEditBuilder<S, E> {
pub fn new() -> Self {
Self {
content: None,
embeds: None,
components: None,
}
}
pub fn content(mut self, content: impl Into<String>) -> Self {
self.content = Some(Some(content.into()));
self
}
pub fn embed(mut self, embed: Embed) -> Self {
if self.embeds.is_none() {
self.embeds = Some(Vec::new());
}
self.embeds.as_mut().unwrap().push(embed);
self
}
pub fn component(mut self, component: impl Component<S, E> + 'static, row: usize) -> Self {
if self.components.is_none() {
self.components = Some(Vec::new());
}
self.components
.as_mut()
.unwrap()
.push((Arc::new(component), row));
self
}
}
impl<S, E> From<MessageBuilder<S, E>> for MessageEditBuilder<S, E> {
fn from(builder: MessageBuilder<S, E>) -> Self {
Self {
content: builder.content.map(Some),
embeds: Some(builder.embeds),
components: Some(builder.components),
}
}
}
+3 -4
View File
@@ -76,8 +76,7 @@
//! // Your command logic here. //! // Your command logic here.
//! ctx.send() //! ctx.send()
//! .content("Hello, world!") //! .content("Hello, world!")
//! .await //! .await?;
//! .map_err(|_| CommandError::MessageSendingFailed)?;
//! //!
//! Ok(()) //! Ok(())
//! } //! }
@@ -149,8 +148,7 @@
//! //!
//! ctx.send() //! ctx.send()
//! .content(format!("Hello, {}!", name.0)) //! .content(format!("Hello, {}!", name.0))
//! .await //! .await?;
//! .map_err(|_| CommandError::MessageSendingFailed)?;
//! //!
//! Ok(()) //! Ok(())
//! } //! }
@@ -161,4 +159,5 @@ pub mod bot;
pub mod commands; pub mod commands;
pub mod events; pub mod events;
pub mod interactions; pub mod interactions;
pub mod messages;
pub mod runtime; pub mod runtime;
+3 -6
View File
@@ -51,15 +51,13 @@ impl Command<State, Extras> for HelpCommand {
.component(HelpGoBackButton, 1) .component(HelpGoBackButton, 1)
.component(HelpSupportLinkButton, 1) .component(HelpSupportLinkButton, 1)
.await .await
.inspect_err(|e| log::error!("Failed to send message! {e}")) .inspect_err(|e| log::error!("Failed to send message! {e}"))?;
.map_err(|_| CommandError::MessageSendingFailed)?;
} else { } else {
ctx.send() ctx.send()
.embed(get_command_not_found_embed(&ctx.rt, command_name.0)) .embed(get_command_not_found_embed(&ctx.rt, command_name.0))
.component(HelpGoBackButton, 1) .component(HelpGoBackButton, 1)
.component(HelpSupportLinkButton, 1) .component(HelpSupportLinkButton, 1)
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
} }
} else { } else {
ctx.send() ctx.send()
@@ -67,8 +65,7 @@ impl Command<State, Extras> for HelpCommand {
.component(HelpWebsiteLinkButton, 1) .component(HelpWebsiteLinkButton, 1)
.component(HelpSupportLinkButton, 1) .component(HelpSupportLinkButton, 1)
.component(HelpDonateLinkButton, 1) .component(HelpDonateLinkButton, 1)
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
} }
Ok(()) Ok(())
+30 -24
View File
@@ -2,7 +2,10 @@ use async_trait::async_trait;
use crate::{ use crate::{
extras::Extras, 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, groups::about::embeds::get_all_command_help_embed,
state::State, state::State,
}; };
@@ -12,8 +15,12 @@ pub struct HelpGoBackButton;
#[async_trait] #[async_trait]
impl Button<State, Extras> for HelpGoBackButton { impl Button<State, Extras> for HelpGoBackButton {
fn label(&self) -> Option<&'static str> { fn id(&self) -> Option<String> {
Some("← Go back to commands list") Some("help:go-back".into())
}
fn label(&self) -> Option<String> {
Some("← Go back to commands list".into())
} }
async fn on_press( async fn on_press(
@@ -21,16 +28,15 @@ impl Button<State, Extras> for HelpGoBackButton {
ctx: InteractionContext<State, Extras>, ctx: InteractionContext<State, Extras>,
) -> Result<(), InteractionError> { ) -> Result<(), InteractionError> {
ctx ctx
.original_message() .edit_original_message(
.expect( MessageEditBuilder::new().embed(
"Buttons always have the original message in the interaction context, this one didn't (got None)" get_all_command_help_embed(&ctx.prefix, &ctx.rt, &ctx.extras)
) )
.edit()
.embed(get_all_command_help_embed(&ctx.prefix, &ctx.rt, &ctx.extras))
.component(HelpWebsiteLinkButton, 1) .component(HelpWebsiteLinkButton, 1)
.component(HelpSupportLinkButton, 1) .component(HelpSupportLinkButton, 1)
.component(HelpDonateLinkButton, 1) .component(HelpDonateLinkButton, 1)
.component(CodeOfConductLinkButton, 1) .component(CodeOfConductLinkButton, 1)
)
.await .await
.inspect_err(|e| log::error!("An error occurred while attempting to edit the original message of an interaction. {e:?}")) .inspect_err(|e| log::error!("An error occurred while attempting to edit the original message of an interaction. {e:?}"))
.map_err( .map_err(
@@ -46,12 +52,12 @@ pub struct HelpSupportLinkButton;
#[async_trait] #[async_trait]
impl Button<State, Extras> for HelpSupportLinkButton { impl Button<State, Extras> for HelpSupportLinkButton {
fn label(&self) -> Option<&'static str> { fn label(&self) -> Option<String> {
Some("Get help") Some("Get help".into())
} }
fn url(&self) -> Option<&'static str> { fn url(&self) -> Option<String> {
Some("https://discord.gg/9daSsrfTmE") Some("https://discord.gg/9daSsrfTmE".into())
} }
} }
@@ -60,12 +66,12 @@ pub struct HelpWebsiteLinkButton;
#[async_trait] #[async_trait]
impl Button<State, Extras> for HelpWebsiteLinkButton { impl Button<State, Extras> for HelpWebsiteLinkButton {
fn label(&self) -> Option<&'static str> { fn label(&self) -> Option<String> {
Some("Website") Some("Website".into())
} }
fn url(&self) -> Option<&'static str> { fn url(&self) -> Option<String> {
Some("https://payphone.lat/") Some("https://payphone.lat/".into())
} }
} }
@@ -74,12 +80,12 @@ pub struct HelpDonateLinkButton;
#[async_trait] #[async_trait]
impl Button<State, Extras> for HelpDonateLinkButton { impl Button<State, Extras> for HelpDonateLinkButton {
fn label(&self) -> Option<&'static str> { fn label(&self) -> Option<String> {
Some("Donate") Some("Donate".into())
} }
fn url(&self) -> Option<&'static str> { fn url(&self) -> Option<String> {
Some("https://ko-fi.com/payphonedev") Some("https://ko-fi.com/payphonedev".into())
} }
} }
@@ -88,11 +94,11 @@ pub struct CodeOfConductLinkButton;
#[async_trait] #[async_trait]
impl Button<State, Extras> for CodeOfConductLinkButton { impl Button<State, Extras> for CodeOfConductLinkButton {
fn label(&self) -> Option<&'static str> { fn label(&self) -> Option<String> {
Some("Code of Conduct") Some("Code of Conduct".into())
} }
fn url(&self) -> Option<&'static str> { fn url(&self) -> Option<String> {
Some("https://payphone.lat/code-of-conduct") Some("https://payphone.lat/code-of-conduct".into())
} }
} }
+31 -65
View File
@@ -66,8 +66,7 @@ impl Command<State, Extras> for CallCommand {
.await .await
.inspect_err(|e| { .inspect_err(|e| {
log::error!("Failed to get or create channel: {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()) { if channel.is_searching || self.channel_lock.contains(&ctx.event.channel_id.get()) {
ctx.send() 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.", "☎️ You are already searching for a call! Use `{}hangup` to hang up the phone.",
ctx.prefix ctx.prefix
)) ))
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
return Ok(()); return Ok(());
} }
@@ -85,27 +83,21 @@ impl Command<State, Extras> for CallCommand {
ctx.send() 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)) .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 .await
.map_err(|_| CommandError::MessageSendingFailed)?; ?;
return Ok(()); return Ok(());
} }
self.channel_lock self.channel_lock.insert(ctx.event.channel_id.get()).bye();
.insert_async(ctx.event.channel_id.get())
.await
.bye();
let call = Call::start(&channel, &ctx.rt.state.db) let call = Call::start(&channel, &ctx.rt.state.db)
.await .await
.inspect_err(|e| { .inspect_err(|e| {
log::error!("Failed to start call: {e:?}"); log::error!("Failed to start call: {e:?}");
self.channel_lock.remove(&ctx.event.channel_id.get()); self.channel_lock.remove(&ctx.event.channel_id.get());
}) })?;
.map_err(|_| CommandError::DatabaseFailed)?;
self.channel_lock self.channel_lock.remove(&ctx.event.channel_id.get());
.remove_async(&ctx.event.channel_id.get())
.await;
if let Some(call) = call { if let Some(call) = call {
ctx.send() ctx.send()
@@ -130,8 +122,7 @@ impl Command<State, Extras> for CallCommand {
get_string_tips(ctx.prefix), get_string_tips(ctx.prefix),
get_string_call_searching(ctx.prefix) get_string_call_searching(ctx.prefix)
)) ))
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
} }
Ok(()) Ok(())
@@ -168,8 +159,7 @@ impl Command<State, Extras> for SkipCommand {
.await .await
.inspect_err(|e| { .inspect_err(|e| {
log::error!("Failed to get or create channel: {e:?}"); log::error!("Failed to get or create channel: {e:?}");
}) })?;
.map_err(|_| CommandError::DatabaseFailed)?;
if channel.call_id.is_none() { if channel.call_id.is_none() {
ctx.send() ctx.send()
@@ -177,8 +167,7 @@ impl Command<State, Extras> for SkipCommand {
"❌ You're not on a call! Use `{}call` to start one.", "❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix ctx.prefix
)) ))
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
return Ok(()); 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.", "☎️ You're already searching for a call! Use `{}hangup` to cancel the search.",
ctx.prefix ctx.prefix
)) ))
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
return Ok(()); return Ok(());
} }
let call = Call::get_by_id(channel.call_id.unwrap(), &ctx.rt.state.db) let call = Call::get_by_id(channel.call_id.unwrap(), &ctx.rt.state.db)
.await .await
.inspect_err(|e| log::error!("Failed to get call: {e:?}")) .inspect_err(|e| log::error!("Failed to get call: {e:?}"))?
.map_err(|_| CommandError::DatabaseFailed)?
.ok_or(CommandError::DatabaseInconsistentState)?; .ok_or(CommandError::DatabaseInconsistentState)?;
call.hangup(&ctx.rt.state.db) call.hangup(&ctx.rt.state.db)
.await .await
.inspect_err(|e| log::error!("Failed to hang up call: {e:?}")) .inspect_err(|e| log::error!("Failed to hang up call: {e:?}"))?;
.map_err(|_| CommandError::DatabaseFailed)?;
let other_channel_id = call.other_party_channel_id(ctx.event.channel_id.get()); 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 .await
.inspect_err(|e| { .inspect_err(|e| {
log::error!("Failed to send message to other party: {e:?}"); log::error!("Failed to send message to other party: {e:?}");
}) })?;
.map_err(|_| CommandError::MessageSendingFailed)?;
let call = Call::start(&channel, &ctx.rt.state.db) let call = Call::start(&channel, &ctx.rt.state.db)
.await .await
.inspect_err(|e| { .inspect_err(|e| {
log::error!("Failed to start (skipped) call: {e:?}"); log::error!("Failed to start (skipped) call: {e:?}");
}) })?;
.map_err(|_| CommandError::DatabaseFailed)?;
if let Some(call) = call { if let Some(call) = call {
ctx.send() ctx.send()
@@ -248,8 +232,7 @@ impl Command<State, Extras> for SkipCommand {
} else { } else {
ctx.send() ctx.send()
.content("☎️ Skipped! Searching for a call...") .content("☎️ Skipped! Searching for a call...")
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
} }
Ok(()) Ok(())
@@ -280,16 +263,14 @@ impl Command<State, Extras> for HangupCommand {
) -> Result<(), CommandError> { ) -> Result<(), CommandError> {
let Some(channel) = Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db) let Some(channel) = Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db)
.await .await
.inspect_err(|e| log::error!("Failed to get channel: {e:?}")) .inspect_err(|e| log::error!("Failed to get channel: {e:?}"))?
.map_err(|_| CommandError::DatabaseFailed)?
else { else {
ctx.send() ctx.send()
.content(format!( .content(format!(
"❌ You're not on a call! Use `{}call` to start one.", "❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix ctx.prefix
)) ))
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
return Ok(()); return Ok(());
}; };
@@ -300,13 +281,11 @@ impl Command<State, Extras> for HangupCommand {
.await .await
.inspect_err(|e| { .inspect_err(|e| {
log::error!("Failed to cancel search: {e:?}"); log::error!("Failed to cancel search: {e:?}");
}) })?;
.map_err(|_| CommandError::DatabaseFailed)?;
ctx.send() ctx.send()
.content(format!("☎️ {}", get_string_call_no_answer(ctx.prefix))) .content(format!("☎️ {}", get_string_call_no_answer(ctx.prefix)))
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
return Ok(()); return Ok(());
} }
@@ -314,21 +293,16 @@ impl Command<State, Extras> for HangupCommand {
if let Some(call_id) = channel.call_id { if let Some(call_id) = channel.call_id {
let Some(call) = Call::get_by_id(call_id, &ctx.rt.state.db) let Some(call) = Call::get_by_id(call_id, &ctx.rt.state.db)
.await .await
.inspect_err(|e| log::error!("Failed to get call: {e:?}")) .inspect_err(|e| log::error!("Failed to get call: {e:?}"))?
.map_err(|_| CommandError::DatabaseFailed)?
else { else {
ctx.send() ctx.send().content("❌ Call not found.").await?;
.content("❌ Call not found.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
return Err(CommandError::DatabaseInconsistentState); return Err(CommandError::DatabaseInconsistentState);
}; };
call.hangup(&ctx.rt.state.db) call.hangup(&ctx.rt.state.db)
.await .await
.inspect_err(|e| log::error!("Failed to hang up call: {e:?}")) .inspect_err(|e| log::error!("Failed to hang up call: {e:?}"))?;
.map_err(|_| CommandError::DatabaseFailed)?;
ctx.send() ctx.send()
.content(format!( .content(format!(
@@ -345,16 +319,14 @@ impl Command<State, Extras> for HangupCommand {
"☎️ {}", "☎️ {}",
get_string_call_hangup_other_party(ctx.prefix) get_string_call_hangup_other_party(ctx.prefix)
)) ))
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
} else { } else {
ctx.send() ctx.send()
.content(format!( .content(format!(
"❌ You're not on a call! Use `{}call` to start one.", "❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix ctx.prefix
)) ))
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
return Ok(()); return Ok(());
} }
@@ -391,8 +363,7 @@ impl Command<State, Extras> for FriendRequestCommand {
) -> Result<(), CommandError> { ) -> Result<(), CommandError> {
let channel = Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db) let channel = Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db)
.await .await
.inspect_err(|e| log::error!("Failed to get channel: {e:?}")) .inspect_err(|e| log::error!("Failed to get channel: {e:?}"))?;
.map_err(|_| CommandError::DatabaseFailed)?;
let Some(channel) = channel else { let Some(channel) = channel else {
ctx.send() ctx.send()
@@ -400,8 +371,7 @@ impl Command<State, Extras> for FriendRequestCommand {
"❌ You're not on a call! Use `{}call` to start one.", "❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix ctx.prefix
)) ))
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
return Ok(()); return Ok(());
}; };
@@ -409,16 +379,14 @@ impl Command<State, Extras> for FriendRequestCommand {
let call = if let Some(call_id) = channel.call_id { let call = if let Some(call_id) = channel.call_id {
Call::get_by_id(call_id, &ctx.rt.state.db) Call::get_by_id(call_id, &ctx.rt.state.db)
.await .await
.inspect_err(|e| log::error!("Failed to get call: {e:?}")) .inspect_err(|e| log::error!("Failed to get call: {e:?}"))?
.map_err(|_| CommandError::DatabaseFailed)?
} else { } else {
ctx.send() ctx.send()
.content(format!( .content(format!(
"❌ You're not on a call! Use `{}call` to start one.", "❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix ctx.prefix
)) ))
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
return Ok(()); return Ok(());
}; };
@@ -426,8 +394,7 @@ impl Command<State, Extras> for FriendRequestCommand {
let Some(call) = call else { let Some(call) = call else {
ctx.send() ctx.send()
.content("❌ Oops! We could not find that call.") .content("❌ Oops! We could not find that call.")
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
return Err(CommandError::DatabaseInconsistentState); return Err(CommandError::DatabaseInconsistentState);
}; };
@@ -450,12 +417,11 @@ impl Command<State, Extras> for FriendRequestCommand {
) )
) )
.await .await
.map_err(|_| CommandError::MessageSendingFailed)?; ?;
ctx.send() ctx.send()
.content("📬 Asked the other party to send you a friend request!") .content("📬 Asked the other party to send you a friend request!")
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
Ok(()) Ok(())
} }
+8 -8
View File
@@ -4,12 +4,12 @@ use crate::{extras::Extras, framework::interactions::components::Button, state::
pub struct CodeOfConductButton; pub struct CodeOfConductButton;
impl Button<State, Extras> for CodeOfConductButton { impl Button<State, Extras> for CodeOfConductButton {
fn label(&self) -> Option<&'static str> { fn label(&self) -> Option<String> {
Some("Code of Conduct") Some("Code of Conduct".into())
} }
fn url(&self) -> Option<&'static str> { fn url(&self) -> Option<String> {
Some("https://payphone.lat/code-of-conduct") Some("https://payphone.lat/code-of-conduct".into())
} }
} }
@@ -17,11 +17,11 @@ impl Button<State, Extras> for CodeOfConductButton {
pub struct NeedHelpButton; pub struct NeedHelpButton;
impl Button<State, Extras> for NeedHelpButton { impl Button<State, Extras> for NeedHelpButton {
fn label(&self) -> Option<&'static str> { fn label(&self) -> Option<String> {
Some("Need Help?") Some("Need Help?".into())
} }
fn url(&self) -> Option<&'static str> { fn url(&self) -> Option<String> {
Some("https://discord.gg/9daSsrfTmE") 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> { 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) let incidents = UserIncident::get_for_user(ctx.event.author.id.get(), &ctx.rt.state.db)
.await .await
.inspect_err(|e| log::error!("Failed to get user incidents: {e}")) .inspect_err(|e| log::error!("Failed to get user incidents: {e}"))?;
.map_err(|_| CommandError::DatabaseFailed)?;
if incidents.iter().any(|i| i.is_active()) { if incidents.iter().any(|i| i.is_active()) {
Ok(false) Ok(false)
@@ -37,8 +36,7 @@ impl Permission<State, Extras> for NotBannedPermission {
.await .await
.inspect_err(|e| { .inspect_err(|e| {
log::error!("Failed to send message: {e}"); log::error!("Failed to send message: {e}");
}) })?;
.map_err(|_| CommandError::MessageSendingFailed)?;
Ok(()) Ok(())
} }
+12 -18
View File
@@ -6,7 +6,13 @@ use twilight_util::builder::embed::{
}; };
use crate::{ 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)] #[derive(Debug)]
@@ -31,33 +37,22 @@ impl Command<State, Extras> for LeaderboardCommand {
ctx: CommandContext<'_, State, Extras>, ctx: CommandContext<'_, State, Extras>,
_args: &str, _args: &str,
) -> Result<(), CommandError> { ) -> Result<(), CommandError> {
let mut redis = ctx let mut redis = ctx.rt.state.redis.get().await?;
.rt
.state
.redis
.get()
.await
.map_err(CommandError::RedisPoolFailed)?;
let top: Vec<(u64, f64)> = redis let top: Vec<(u64, f64)> = redis
.zrevrange_withscores(KEY_LEADERBOARD_MONTHLY, 0, 9) .zrevrange_withscores(KEY_LEADERBOARD_MONTHLY, 0, 9)
.await .await?;
.map_err(CommandError::RedisFailed)?;
log::trace!("Top users for leaderboard: {top:?}"); log::trace!("Top users for leaderboard: {top:?}");
let current_user_rank: Option<usize> = redis let current_user_rank: Option<usize> = redis
.zrevrank(KEY_LEADERBOARD_MONTHLY, ctx.event.author.id.get()) .zrevrank(KEY_LEADERBOARD_MONTHLY, ctx.event.author.id.get())
.await .await?;
.map_err(CommandError::RedisFailed)?;
let mut users = Vec::new(); let mut users = Vec::new();
for (user_id, score) in top { for (user_id, score) in top {
let Some(user) = User::get_by_id(user_id, &ctx.rt.state.db) let Some(user) = User::get_by_id(user_id, &ctx.rt.state.db).await? else {
.await
.map_err(|_| CommandError::DatabaseFailed)?
else {
log::trace!("User ID {user_id} not found for leaderboard"); log::trace!("User ID {user_id} not found for leaderboard");
continue; continue;
}; };
@@ -130,8 +125,7 @@ impl Command<State, Extras> for LeaderboardCommand {
ctx.send() ctx.send()
.embed(embed.build()) .embed(embed.build())
.await .await
.inspect_err(|e| log::error!("Failed to send leaderboard embed: {e}")) .inspect_err(|e| log::error!("Failed to send leaderboard embed: {e}"))?;
.map_err(|_| CommandError::MessageSendingFailed)?;
Ok(()) Ok(())
} }
+3 -10
View File
@@ -22,10 +22,7 @@ use crate::{
/// [`Result<User, ArgumentParser>`] - The user from the DB, or an [`ArgumentParsingError`] ready /// [`Result<User, ArgumentParser>`] - The user from the DB, or an [`ArgumentParsingError`] ready
/// to be returned by the parser. /// to be returned by the parser.
async fn get_user_by_id(id: u64, db: &Session) -> Result<User, ArgumentParsingError> { async fn get_user_by_id(id: u64, db: &Session) -> Result<User, ArgumentParsingError> {
let Some(user) = User::get_by_id(id, db) let Some(user) = User::get_by_id(id, db).await? else {
.await
.map_err(|_| ArgumentParsingError::DatabaseFailed)?
else {
return Err(ArgumentParsingError::InvalidArgument); return Err(ArgumentParsingError::InvalidArgument);
}; };
Ok(user) Ok(user)
@@ -49,8 +46,7 @@ async fn user_from_reply_or_command_executor(
if referenced.author.bot { if referenced.author.bot {
if let Some(message) = if let Some(message) =
Message::get_by_propagation_message_id(referenced.id.get(), &ctx.rt.state.db) Message::get_by_propagation_message_id(referenced.id.get(), &ctx.rt.state.db)
.await .await?
.map_err(|_| ArgumentParsingError::DatabaseFailed)?
{ {
return get_user_by_id(message.author_id, &ctx.rt.state.db).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 { } else {
// The argument is (probably) a username. // The argument is (probably) a username.
let Some(db_user) = User::get_by_name(identifier.0, &ctx.rt.state.db) let Some(db_user) = User::get_by_name(identifier.0, &ctx.rt.state.db).await? else {
.await
.map_err(|_| ArgumentParsingError::DatabaseFailed)?
else {
// Check in the message's reply, and if not use the command executor. // Check in the message's reply, and if not use the command executor.
user = user_from_reply_or_command_executor(ctx).await?; user = user_from_reply_or_command_executor(ctx).await?;
+11 -29
View File
@@ -1,7 +1,6 @@
use async_trait::async_trait; use async_trait::async_trait;
use crate::{ use crate::{
database::models::UserIncident,
extras::Extras, extras::Extras,
framework::{ framework::{
commands::{ commands::{
@@ -14,10 +13,10 @@ use crate::{
}, },
groups::moderation::{ groups::moderation::{
arguments::UserArgument, arguments::UserArgument,
get_incident_page,
permissions::{BotModeratorPermission, BotOwnerPermission}, permissions::{BotModeratorPermission, BotOwnerPermission},
}, },
state::State, state::State,
utils::Bye,
}; };
#[derive(Debug)] #[derive(Debug)]
@@ -58,14 +57,11 @@ impl Command<State, Extras> for ModeratorCommand {
Ok(arg) => arg, Ok(arg) => arg,
Err(e) => match e { Err(e) => match e {
ArgumentParsingError::InvalidArgument => { ArgumentParsingError::InvalidArgument => {
ctx.send() ctx.send().content("❌ User not found in DB.").await?;
.content("❌ User not found in DB.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
return Ok(()); return Ok(());
} }
ArgumentParsingError::DatabaseFailed => { ArgumentParsingError::DatabaseFailed(e) => {
return Err(CommandError::DatabaseFailed); return Err(CommandError::DatabaseFailed(e));
} }
e => { e => {
unreachable!("Unexpected error: {e}"); unreachable!("Unexpected error: {e}");
@@ -75,9 +71,7 @@ impl Command<State, Extras> for ModeratorCommand {
user.is_moderator = !user.is_moderator; user.is_moderator = !user.is_moderator;
user.insert(&ctx.rt.state.db) user.insert(&ctx.rt.state.db).await?;
.await
.map_err(|_| CommandError::DatabaseFailed)?;
ctx.send() ctx.send()
.content(format!( .content(format!(
@@ -89,8 +83,7 @@ impl Command<State, Extras> for ModeratorCommand {
"**is no longer** a moderator" "**is no longer** a moderator"
} }
)) ))
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
Ok(()) Ok(())
} }
@@ -126,14 +119,11 @@ impl Command<State, Extras> for IncidentsCommand {
Ok(Arg(user)) => user, Ok(Arg(user)) => user,
Err(e) => match e { Err(e) => match e {
ArgumentParsingError::InvalidArgument => { ArgumentParsingError::InvalidArgument => {
ctx.send() ctx.send().content("❌ User not found in DB.").await?;
.content("❌ User not found in DB.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
return Ok(()); return Ok(());
} }
ArgumentParsingError::DatabaseFailed => { ArgumentParsingError::DatabaseFailed(e) => {
return Err(CommandError::DatabaseFailed); return Err(CommandError::DatabaseFailed(e));
} }
e => { e => {
unreachable!("Unexpected error: {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) let message = get_incident_page(user.id, &ctx.rt.state.db, 0).await?;
.await
.map_err(|_| CommandError::DatabaseFailed)?;
ctx.send() ctx.send_from_builder(message).await?;
.content(format!(
"Great! The user fetched from the DB is {}",
user.name
))
.await
.bye();
Ok(()) 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 arguments;
pub mod commands; pub mod commands;
pub mod components;
pub(super) mod embeds;
pub mod permissions; 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> { ) -> Result<(), CommandError> {
ctx.send() ctx.send()
.content("⛔ Not enough aura to run this command.") .content("⛔ Not enough aura to run this command.")
.await .await?;
.map_err(|_| CommandError::MessageSendingFailed)?;
Ok(()) Ok(())
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct BotModeratorPermission; pub struct BotModeratorPermission;
@@ -45,7 +43,7 @@ impl Permission<State, Extras> for BotModeratorPermission {
ctx.send() 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.") .content("⛔ You're not a Payphone moderator.\n-# If you need to check your incidents, contact a Payphone moderator in the official server.")
.await .await
.map_err(|_| CommandError::MessageSendingFailed)?; ?;
Ok(()) Ok(())
} }
+15 -13
View File
@@ -1,9 +1,18 @@
use async_trait::async_trait; use async_trait::async_trait;
use crate::{ use crate::{
constants::DEFAULT_PREFIX, database::models::Server, discord::sanitizing::SanitizeDiscordMarkdown, extras::Extras, framework::commands::{ constants::DEFAULT_PREFIX,
arguments::{Arg, Argument, GreedyString, ParseArguments}, context::CommandContext, permissions::Permission, Command, CommandError database::models::Server,
}, groups::servers::permissions::{GuildOnlyPermission, ServerModeratorPermission}, state::State 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)] #[derive(Debug)]
@@ -55,18 +64,14 @@ impl Command<State, Extras> for PrefixCommand {
&ctx.rt.http, &ctx.rt.http,
) )
.await .await
.inspect_err(|e| log::error!("Failed to get or create server: {e}")) .inspect_err(|e| log::error!("Failed to get or create server: {e}"))?;
.map_err(|_| CommandError::DatabaseFailed)?;
if prefix.is_empty() { if prefix.is_empty() {
prefix = DEFAULT_PREFIX; prefix = DEFAULT_PREFIX;
} }
server.prefix = prefix.to_string(); server.prefix = prefix.to_string();
server server.upsert(&ctx.rt.state.db).await?;
.upsert(&ctx.rt.state.db)
.await
.map_err(|_| CommandError::DatabaseFailed)?;
ctx.send() ctx.send()
.content(format!( .content(format!(
@@ -74,10 +79,7 @@ impl Command<State, Extras> for PrefixCommand {
prefix.sanitize(false) prefix.sanitize(false)
)) ))
.await .await
.map_err(|e| { .inspect_err(|e| log::error!("Failed to send prefix update message: {e}"))?;
log::error!("Failed to send prefix update message: {e}");
CommandError::MessageSendingFailed
})?;
Ok(()) Ok(())
} }
+2 -4
View File
@@ -49,11 +49,9 @@ impl Permission<State, Extras> for ServerModeratorPermission {
.rt .rt
.http .http
.guild_member(guild_id, ctx.event.author.id) .guild_member(guild_id, ctx.event.author.id)
.await .await?
.map_err(CommandError::DiscordAPIFailed)?
.model() .model()
.await .await?;
.map_err(CommandError::DiscordDeserializationFailed)?;
let Some(everyone_role) = ctx.rt.cache.role(guild_id.cast()) else { let Some(everyone_role) = ctx.rt.cache.role(guild_id.cast()) else {
log::warn!("Could not get @everyone role for guild ID {guild_id}!"); log::warn!("Could not get @everyone role for guild ID {guild_id}!");