Move all commands to their own files

This commit is contained in:
jude
2024-02-17 18:55:16 +00:00
parent eb92eacb90
commit 4823754955
51 changed files with 1757 additions and 1699 deletions

View File

@ -3,7 +3,10 @@ use poise::serenity_prelude::{model::id::GuildId, ResolvedValue};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{commands::reminder_cmds::create_reminder, ApplicationContext, Context, Error};
use crate::{
commands::remind::RemindOptions, models::reminder::create_reminder, ApplicationContext,
Context, Error,
};
#[derive(Serialize, Deserialize)]
#[serde(tag = "command_name")]
@ -81,17 +84,6 @@ impl RecordedCommand {
}
}
#[derive(Serialize, Deserialize, Default)]
pub struct RemindOptions {
time: String,
content: String,
channels: Option<String>,
interval: Option<String>,
expires: Option<String>,
tts: Option<bool>,
timezone: Option<Tz>,
}
pub struct CommandMacro {
pub guild_id: GuildId,
pub name: String,

View File

@ -1,23 +0,0 @@
use poise::serenity_prelude::model::id::ChannelId;
use serde::{Deserialize, Serialize};
use serde_repr::*;
#[derive(Serialize_repr, Deserialize_repr, Copy, Clone, Debug)]
#[repr(u8)]
pub enum TimeDisplayType {
Absolute = 0,
Relative = 1,
}
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
pub struct LookFlags {
pub show_disabled: bool,
pub channel_id: Option<ChannelId>,
pub time_display: TimeDisplayType,
}
impl Default for LookFlags {
fn default() -> Self {
Self { show_disabled: true, channel_id: None, time_display: TimeDisplayType::Relative }
}
}

View File

@ -2,21 +2,39 @@ pub mod builder;
pub mod content;
pub mod errors;
mod helper;
pub mod look_flags;
use std::hash::{Hash, Hasher};
use std::{
collections::HashSet,
hash::{Hash, Hasher},
};
use chrono::{DateTime, NaiveDateTime, Utc};
use chrono_tz::Tz;
use poise::serenity_prelude::{
model::id::{ChannelId, GuildId, UserId},
Cache,
use poise::{
serenity_prelude::{
model::id::{ChannelId, GuildId, UserId},
ButtonStyle, Cache, CreateActionRow, CreateButton, CreateEmbed, ReactionType,
},
CreateReply,
};
use sqlx::Executor;
use crate::{
models::reminder::look_flags::{LookFlags, TimeDisplayType},
Database,
commands::look::{LookFlags, TimeDisplayType},
component_models::{ComponentDataModel, UndoReminder},
consts::{REGEX_CHANNEL_USER, THEME_COLOR},
interval_parser::parse_duration,
models::{
reminder::{
builder::{MultiReminderBuilder, ReminderScope},
content::Content,
errors::ReminderError,
},
CtxData,
},
time_parser::natural_parser,
utils::{check_guild_subscription, check_subscription},
Context, Database, Error,
};
#[derive(Debug, Clone)]
@ -369,3 +387,195 @@ impl Reminder {
}
}
}
pub async fn create_reminder(
ctx: Context<'_>,
time: String,
content: String,
channels: Option<String>,
interval: Option<String>,
expires: Option<String>,
tts: Option<bool>,
timezone: Option<Tz>,
) -> Result<(), Error> {
fn parse_mention_list(mentions: &str) -> Vec<ReminderScope> {
REGEX_CHANNEL_USER
.captures_iter(mentions)
.map(|i| {
let pref = i.get(1).unwrap().as_str();
let id = i.get(2).unwrap().as_str().parse::<u64>().unwrap();
if pref == "#" {
ReminderScope::Channel(id)
} else {
ReminderScope::User(id)
}
})
.collect::<Vec<ReminderScope>>()
}
fn create_response(
successes: &HashSet<(Reminder, ReminderScope)>,
errors: &HashSet<ReminderError>,
time: i64,
) -> CreateEmbed {
let success_part = match successes.len() {
0 => "".to_string(),
n => format!(
"Reminder{s} for {locations} set for <t:{offset}:R>",
s = if n > 1 { "s" } else { "" },
locations =
successes.iter().map(|(_, l)| l.mention()).collect::<Vec<String>>().join(", "),
offset = time
),
};
let error_part = match errors.len() {
0 => "".to_string(),
n => format!(
"{n} reminder{s} failed to set:\n{errors}",
s = if n > 1 { "s" } else { "" },
n = n,
errors = errors.iter().map(|e| e.to_string()).collect::<Vec<String>>().join("\n")
),
};
CreateEmbed::default()
.title(format!(
"{n} Reminder{s} Set",
n = successes.len(),
s = if successes.len() > 1 { "s" } else { "" }
))
.description(format!("{}\n\n{}", success_part, error_part))
.color(*THEME_COLOR)
}
if interval.is_none() && expires.is_some() {
ctx.say("`expires` can only be used with `interval`").await?;
return Ok(());
}
let ephemeral =
ctx.guild_data().await.map_or(false, |gr| gr.map_or(false, |g| g.ephemeral_confirmations));
if ephemeral {
ctx.defer_ephemeral().await?;
} else {
ctx.defer().await?;
}
let user_data = ctx.author_data().await.unwrap();
let timezone = timezone.unwrap_or(ctx.timezone().await);
let time = natural_parser(&time, &timezone.to_string()).await;
match time {
Some(time) => {
let content = {
let tts = tts.unwrap_or(false);
Content { content, tts, attachment: None, attachment_name: None }
};
let scopes = {
let list = channels.map(|arg| parse_mention_list(&arg)).unwrap_or_default();
if list.is_empty() {
if ctx.guild_id().is_some() {
vec![ReminderScope::Channel(ctx.channel_id().get())]
} else {
vec![ReminderScope::User(ctx.author().id.get())]
}
} else {
list
}
};
let (processed_interval, processed_expires) = if let Some(repeat) = &interval {
if check_subscription(&ctx, ctx.author().id).await
|| (ctx.guild_id().is_some()
&& check_guild_subscription(&ctx, ctx.guild_id().unwrap()).await)
{
(
parse_duration(repeat)
.or_else(|_| parse_duration(&format!("1 {}", repeat)))
.ok(),
{
if let Some(arg) = &expires {
natural_parser(arg, &timezone.to_string()).await
} else {
None
}
},
)
} else {
ctx.send(CreateReply::default().content(
"`repeat` is only available to Patreon subscribers or self-hosted users",
))
.await?;
return Ok(());
}
} else {
(None, None)
};
if processed_interval.is_none() && interval.is_some() {
ctx.send(CreateReply::default().content(
"Repeat interval could not be processed. Try similar to `1 hour` or `4 days`",
))
.await?;
} else if processed_expires.is_none() && expires.is_some() {
ctx.send(
CreateReply::default().ephemeral(true).content(
"Expiry time failed to process. Please make it as clear as possible",
),
)
.await?;
} else {
let mut builder = MultiReminderBuilder::new(&ctx, ctx.guild_id())
.author(user_data)
.content(content)
.time(time)
.timezone(timezone)
.expires(processed_expires)
.interval(processed_interval);
builder.set_scopes(scopes);
let (errors, successes) = builder.build().await;
let embed = create_response(&successes, &errors, time);
if successes.len() == 1 {
let reminder = successes.iter().next().map(|(r, _)| r.id).unwrap();
let undo_button = ComponentDataModel::UndoReminder(UndoReminder {
user_id: ctx.author().id,
reminder_id: reminder,
});
ctx.send(CreateReply::default().embed(embed).components(vec![
CreateActionRow::Buttons(vec![
CreateButton::new(undo_button.to_custom_id())
.emoji(ReactionType::Unicode("🔕".to_string()))
.label("Cancel")
.style(ButtonStyle::Danger),
CreateButton::new_link("https://beta.reminder-bot.com/dashboard")
.emoji(ReactionType::Unicode("📝".to_string()))
.label("Edit"),
]),
]))
.await?;
} else {
ctx.send(CreateReply::default().embed(embed)).await?;
}
}
}
None => {
ctx.say("Time could not be processed").await?;
}
}
Ok(())
}