Compare commits
9 Commits
jude/restr
...
current
Author | SHA1 | Date | |
---|---|---|---|
|
5ae4baa2a6 | ||
|
6884adc5b2 | ||
|
6ade91e11b | ||
20f0fb1c20 | |||
|
4d14365f2b | ||
|
0f4df703eb | ||
|
a9edcec43c | ||
|
cc5f6d9d55 | ||
|
761d545496 |
14
Cargo.lock
generated
14
Cargo.lock
generated
@@ -1,6 +1,6 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "addr2line"
|
||||
@@ -524,6 +524,15 @@ dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cron-parser"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baa5650eabdaa360e2c240c2a5f544f10185b439cd76d748e44e3f28128a016b"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-channel"
|
||||
version = "0.5.13"
|
||||
@@ -2614,11 +2623,12 @@ checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
|
||||
|
||||
[[package]]
|
||||
name = "reminder-rs"
|
||||
version = "1.7.37"
|
||||
version = "1.7.40"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"chrono-tz",
|
||||
"cron-parser",
|
||||
"csv",
|
||||
"dotenv",
|
||||
"env_logger",
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "reminder-rs"
|
||||
version = "1.7.37"
|
||||
version = "1.7.40"
|
||||
authors = ["Jude Southworth <judesouthworth@pm.me>"]
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0 only"
|
||||
@@ -35,6 +35,7 @@ serenity = { version = "0.12", default-features = false, features = ["builder",
|
||||
oauth2 = "4"
|
||||
csv = "1.2"
|
||||
sd-notify = "0.4.1"
|
||||
cron-parser = "0.10"
|
||||
|
||||
[dependencies.extract_derive]
|
||||
path = "extract_derive"
|
||||
|
@@ -3,6 +3,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use chrono_tz::TZ_VARIANTS;
|
||||
use poise::serenity_prelude::AutocompleteChoice;
|
||||
|
||||
use crate::time_parser::cron_next_timestamp;
|
||||
use crate::{models::CtxData, time_parser::natural_parser, Context};
|
||||
|
||||
pub async fn timezone_autocomplete(ctx: Context<'_>, partial: &str) -> Vec<String> {
|
||||
@@ -42,7 +43,13 @@ pub async fn time_hint_autocomplete(ctx: Context<'_>, partial: &str) -> Vec<Auto
|
||||
if partial.is_empty() {
|
||||
vec![AutocompleteChoice::new("Start typing a time...".to_string(), "now".to_string())]
|
||||
} else {
|
||||
match natural_parser(partial, &ctx.timezone().await.to_string()).await {
|
||||
let timezone = ctx.timezone().await;
|
||||
let timestamp = match cron_next_timestamp(partial, timezone) {
|
||||
Some(ts) => Some(ts),
|
||||
None => natural_parser(partial, &timezone.to_string()).await,
|
||||
};
|
||||
|
||||
match timestamp {
|
||||
Some(timestamp) => match SystemTime::now().duration_since(UNIX_EPOCH) {
|
||||
Ok(now) => {
|
||||
let diff = timestamp - now.as_secs() as i64;
|
||||
|
@@ -75,8 +75,8 @@ Please select a unique name for your macro.",
|
||||
CreateEmbed::new()
|
||||
.title("Macro Recording Started")
|
||||
.description(
|
||||
"Run up to 5 commands, or type `/macro finish` to stop at any point.
|
||||
Any commands ran as part of recording will be inconsequential",
|
||||
"Run up to 5 commands to record in this macro. Use `/macro finish` to stop recording at any point.
|
||||
Any commands performed during recording won't take any actual action- they are only captured for the macro.",
|
||||
)
|
||||
.color(*THEME_COLOR),
|
||||
),
|
||||
|
57
src/hooks.rs
57
src/hooks.rs
@@ -1,4 +1,6 @@
|
||||
use poise::{CommandInteractionType, CreateReply};
|
||||
use crate::consts::THEME_COLOR;
|
||||
use poise::{serenity_prelude::CreateEmbed, CommandInteractionType, CreateReply};
|
||||
use serenity::builder::CreateEmbedFooter;
|
||||
|
||||
use crate::{consts::MACRO_MAX_COMMANDS, models::command_macro::RecordedCommand, Context, Error};
|
||||
|
||||
@@ -18,7 +20,18 @@ async fn macro_check(ctx: Context<'_>) -> bool {
|
||||
.send(
|
||||
CreateReply::default()
|
||||
.ephemeral(true)
|
||||
.content(format!("{} commands already recorded. Please use `/macro finish` to end recording.", MACRO_MAX_COMMANDS))
|
||||
.embed(CreateEmbed::new()
|
||||
.title("💾 Currently recording macro")
|
||||
.description(
|
||||
format!("{} commands already recorded. Please use `/macro finish` to end recording.", MACRO_MAX_COMMANDS),
|
||||
)
|
||||
.footer(
|
||||
CreateEmbedFooter::new(
|
||||
"Any commands performed during recording won't take any actual action- they are only captured for the macro"
|
||||
)
|
||||
)
|
||||
.color(*THEME_COLOR),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
@@ -28,9 +41,19 @@ async fn macro_check(ctx: Context<'_>) -> bool {
|
||||
|
||||
let _ = ctx
|
||||
.send(
|
||||
CreateReply::default()
|
||||
.ephemeral(true)
|
||||
.content("Command recorded to macro"),
|
||||
CreateReply::default().ephemeral(true).embed(
|
||||
CreateEmbed::new()
|
||||
.title("💾 Currently recording macro")
|
||||
.description(
|
||||
"Command recorded. Use `/macro finish` to end recording.",
|
||||
)
|
||||
.footer(
|
||||
CreateEmbedFooter::new(
|
||||
"Any commands performed during recording won't take any actual action- they are only captured for the macro"
|
||||
)
|
||||
)
|
||||
.color(*THEME_COLOR),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -38,8 +61,18 @@ async fn macro_check(ctx: Context<'_>) -> bool {
|
||||
None => {
|
||||
let _ = ctx
|
||||
.send(
|
||||
CreateReply::default().ephemeral(true).content(
|
||||
"This command is not supported in macros yet.",
|
||||
CreateReply::default().ephemeral(true).embed(
|
||||
CreateEmbed::new()
|
||||
.title("💾 Currently recording macro")
|
||||
.description(
|
||||
"This command is not supported in macros, so it hasn't been recorded. Use `/macro finish` to end recording.",
|
||||
)
|
||||
.footer(
|
||||
CreateEmbedFooter::new(
|
||||
"Any commands performed during recording won't take any actual action- they are only captured for the macro"
|
||||
)
|
||||
)
|
||||
.color(*THEME_COLOR),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
@@ -74,6 +107,7 @@ async fn check_self_permissions(ctx: Context<'_>) -> bool {
|
||||
return if permissions.send_messages()
|
||||
&& permissions.embed_links()
|
||||
&& manage_webhooks
|
||||
&& permissions.view_channel()
|
||||
{
|
||||
true
|
||||
} else {
|
||||
@@ -81,12 +115,13 @@ async fn check_self_permissions(ctx: Context<'_>) -> bool {
|
||||
.send(CreateReply::default().content(format!(
|
||||
"The bot appears to be missing some permissions:
|
||||
|
||||
{} **View Channels**
|
||||
{} **Send Message**
|
||||
{} **Embed Links**
|
||||
{} **Manage Webhooks**
|
||||
|
||||
Please check the bot's roles, and any channel overrides. Alternatively, giving the bot
|
||||
\"Administrator\" will bypass permission checks",
|
||||
Please check the bot's roles, and any channel overrides. Alternatively, giving the bot \"Administrator\" will bypass permission checks",
|
||||
if permissions.view_channel() { "✅" } else { "❌" },
|
||||
if permissions.send_messages() { "✅" } else { "❌" },
|
||||
if permissions.embed_links() { "✅" } else { "❌" },
|
||||
if manage_webhooks { "✅" } else { "❌" },
|
||||
@@ -100,9 +135,7 @@ Please check the bot's roles, and any channel overrides. Alternatively, giving t
|
||||
manage_webhooks
|
||||
}
|
||||
|
||||
None => {
|
||||
return true;
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -16,7 +16,7 @@ use crate::{
|
||||
},
|
||||
CtxData,
|
||||
},
|
||||
time_parser::natural_parser,
|
||||
time_parser::{cron_next_timestamp, natural_parser},
|
||||
utils::{check_guild_subscription, check_subscription},
|
||||
Context, Database, Error,
|
||||
};
|
||||
@@ -486,7 +486,10 @@ pub async fn create_reminder(
|
||||
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;
|
||||
let time = match cron_next_timestamp(&time, timezone) {
|
||||
Some(ts) => Some(ts),
|
||||
None => natural_parser(&time, &timezone.to_string()).await,
|
||||
};
|
||||
|
||||
match time {
|
||||
Some(time) => {
|
||||
|
@@ -34,8 +34,10 @@ use crate::{
|
||||
lazy_static! {
|
||||
pub static ref TIMEFROM_REGEX: Regex =
|
||||
Regex::new(r#"<<timefrom:(?P<time>\d+):(?P<format>.+)?>>"#).unwrap();
|
||||
pub static ref TIMENOW_REGEX: Regex =
|
||||
Regex::new(r#"<<timenow:(?P<timezone>(?:\w|/|_)+):(?P<format>.+)?>>"#).unwrap();
|
||||
pub static ref TIMENOW_REGEX: Regex = Regex::new(
|
||||
r#"<<timenow(?:(?P<sign>[+-])(?P<offset>\d+))?:(?P<timezone>(?:\w|/|_)+?):(?P<format>.+?)?>>"#
|
||||
)
|
||||
.unwrap();
|
||||
pub static ref LOG_TO_DATABASE: bool = env::var("LOG_TO_DATABASE").map_or(true, |v| v == "1");
|
||||
}
|
||||
|
||||
@@ -64,7 +66,7 @@ fn fmt_displacement(format: &str, seconds: u64) -> String {
|
||||
}
|
||||
|
||||
pub fn substitute(string: &str) -> String {
|
||||
let new = TIMEFROM_REGEX.replace(string, |caps: &Captures| {
|
||||
let new = TIMEFROM_REGEX.replace_all(string, |caps: &Captures| {
|
||||
let final_time = caps.name("time").map(|m| m.as_str().parse::<i64>().ok()).flatten();
|
||||
let format = caps.name("format").map(|m| m.as_str());
|
||||
|
||||
@@ -92,12 +94,26 @@ pub fn substitute(string: &str) -> String {
|
||||
});
|
||||
|
||||
TIMENOW_REGEX
|
||||
.replace(&new, |caps: &Captures| {
|
||||
.replace_all(&new, |caps: &Captures| {
|
||||
let timezone = caps.name("timezone").map(|m| m.as_str().parse::<Tz>().ok()).flatten();
|
||||
let format = caps.name("format").map(|m| m.as_str());
|
||||
let sign = caps.name("sign").map(|m| m.as_str());
|
||||
let offset = caps.name("offset").map(|m| m.as_str().parse::<i64>().ok()).flatten();
|
||||
|
||||
if let (Some(timezone), Some(format)) = (timezone, format) {
|
||||
let now = Utc::now().with_timezone(&timezone);
|
||||
let mut now = Utc::now().with_timezone(&timezone);
|
||||
if let (Some(sign), Some(offset)) = (sign, offset) {
|
||||
now = now
|
||||
.checked_add_signed(TimeDelta::seconds(
|
||||
offset * {
|
||||
match sign {
|
||||
"-" => -1,
|
||||
_ => 1,
|
||||
}
|
||||
},
|
||||
))
|
||||
.unwrap_or(now)
|
||||
}
|
||||
|
||||
now.format(format).to_string()
|
||||
} else {
|
||||
|
@@ -6,6 +6,8 @@ use std::{
|
||||
|
||||
use chrono::{DateTime, Datelike, Timelike, Utc};
|
||||
use chrono_tz::Tz;
|
||||
use cron_parser::parse;
|
||||
use std::str::FromStr;
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::consts::{LOCAL_TIMEZONE, PYTHON_LOCATION};
|
||||
@@ -219,3 +221,7 @@ pub async fn natural_parser(time: &str, timezone: &str) -> Option<i64> {
|
||||
})
|
||||
.and_then(|inner| if inner < 0 { None } else { Some(inner) })
|
||||
}
|
||||
|
||||
pub fn cron_next_timestamp(expr: &str, timezone: Tz) -> Option<i64> {
|
||||
parse(expr, &Utc::now().with_timezone(&timezone)).ok().map(|next| next.timestamp() as i64)
|
||||
}
|
||||
|
@@ -92,6 +92,8 @@ enum Error {
|
||||
SQLx(sqlx::Error),
|
||||
#[allow(unused)]
|
||||
Serenity(serenity::Error),
|
||||
#[allow(unused)]
|
||||
MissingDiscordPermission(&'static str),
|
||||
}
|
||||
|
||||
pub async fn initialize(
|
||||
|
@@ -305,7 +305,15 @@ pub async fn edit_reminder(
|
||||
Err(e) => {
|
||||
warn!("`create_database_channel` returned an error code: {:?}", e);
|
||||
|
||||
error.push("Failed to configure channel for reminders. Please check the bot permissions".to_string());
|
||||
// Provide more specific error messages based on the error type
|
||||
match e {
|
||||
crate::web::Error::MissingDiscordPermission(permission) => {
|
||||
error.push(format!("Please ensure the bot has the \"{}\" permission in the channel", permission));
|
||||
}
|
||||
_ => {
|
||||
error.push("Failed to configure channel for reminders. Please check the bot permissions".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -65,7 +65,16 @@ pub async fn create_reminder(
|
||||
if let Err(e) = channel {
|
||||
warn!("`create_database_channel` returned an error code: {:?}", e);
|
||||
|
||||
return Err(json!({"error": "Failed to configure channel for reminders."}));
|
||||
// Provide more specific error messages based on the error type
|
||||
let error_msg = match e {
|
||||
Error::MissingDiscordPermission(permission) => format!(
|
||||
"Please ensure the bot has the \"{}\" permission in the channel",
|
||||
permission
|
||||
),
|
||||
_ => "Failed to configure channel for reminders.".to_string(),
|
||||
};
|
||||
|
||||
return Err(json!({"error": error_msg}));
|
||||
}
|
||||
|
||||
let channel = channel.unwrap();
|
||||
|
@@ -10,6 +10,7 @@ use rocket::{
|
||||
use rocket_dyn_templates::Template;
|
||||
use secrecy::ExposeSecret;
|
||||
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
|
||||
use serenity::http::HttpError;
|
||||
use serenity::{
|
||||
all::CacheHttp,
|
||||
builder::CreateWebhook,
|
||||
@@ -404,9 +405,19 @@ pub(crate) async fn create_reminder(
|
||||
if let Err(e) = channel {
|
||||
warn!("`create_database_channel` returned an error code: {:?}", e);
|
||||
|
||||
return Err(
|
||||
json!({"error": "Failed to configure channel for reminders. Please check the bot permissions"}),
|
||||
);
|
||||
// Provide more specific error messages based on the error type
|
||||
let error_msg = match e {
|
||||
Error::MissingDiscordPermission(permission) => {
|
||||
format!(
|
||||
"Please ensure the bot has the \"{}\" permission in the channel",
|
||||
permission
|
||||
)
|
||||
}
|
||||
_ => "Failed to configure channel for reminders. Please check the bot permissions"
|
||||
.to_string(),
|
||||
};
|
||||
|
||||
return Err(json!({"error": error_msg}));
|
||||
}
|
||||
|
||||
let channel = channel.unwrap();
|
||||
@@ -716,13 +727,36 @@ async fn create_database_channel(
|
||||
|
||||
match row {
|
||||
Ok(row) => {
|
||||
let is_dm =
|
||||
channel.to_channel(&ctx).await.map_err(|e| Error::Serenity(e))?.private().is_some();
|
||||
let is_dm = channel
|
||||
.to_channel(&ctx)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
if let serenity::Error::Http(http_error) = &e {
|
||||
if let HttpError::UnsuccessfulRequest(response) = http_error {
|
||||
if response.error.code == 50001 {
|
||||
return Error::MissingDiscordPermission("View Channel");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Error::Serenity(e)
|
||||
})?
|
||||
.private()
|
||||
.is_some();
|
||||
if !is_dm && (row.webhook_token.is_none() || row.webhook_id.is_none()) {
|
||||
let webhook = channel
|
||||
.create_webhook(&ctx, CreateWebhook::new("Reminder").avatar(&*DEFAULT_AVATAR))
|
||||
.await
|
||||
.map_err(|e| Error::Serenity(e))?;
|
||||
.map_err(|e| match &e {
|
||||
serenity::Error::Http(HttpError::UnsuccessfulRequest(response)) => {
|
||||
match response.error.code {
|
||||
50001 => Error::MissingDiscordPermission("View Channel"),
|
||||
50013 => Error::MissingDiscordPermission("Manage Webhooks"),
|
||||
_ => Error::Serenity(e),
|
||||
}
|
||||
}
|
||||
_ => Error::Serenity(e),
|
||||
})?;
|
||||
|
||||
let token = webhook.token.unwrap();
|
||||
|
||||
@@ -747,7 +781,16 @@ async fn create_database_channel(
|
||||
let webhook = channel
|
||||
.create_webhook(&ctx, CreateWebhook::new("Reminder").avatar(&*DEFAULT_AVATAR))
|
||||
.await
|
||||
.map_err(|e| Error::Serenity(e))?;
|
||||
.map_err(|e| match &e {
|
||||
serenity::Error::Http(HttpError::UnsuccessfulRequest(response)) => {
|
||||
match response.error.code {
|
||||
50001 => Error::MissingDiscordPermission("View Channel"),
|
||||
50013 => Error::MissingDiscordPermission("Manage Webhooks"),
|
||||
_ => Error::Serenity(e),
|
||||
}
|
||||
}
|
||||
_ => Error::Serenity(e),
|
||||
})?;
|
||||
|
||||
let token = webhook.token.unwrap();
|
||||
|
||||
@@ -806,22 +849,15 @@ pub async fn todos_redirect(id: &str) -> Redirect {
|
||||
|
||||
#[get("/")]
|
||||
pub async fn dashboard_home(cookies: &CookieJar<'_>) -> DashboardPage {
|
||||
if cookies.get_private("userid").is_some() {
|
||||
match NamedFile::open(Path::new(path!("static/index.html"))).await {
|
||||
Ok(f) => DashboardPage::Ok(f),
|
||||
Err(e) => {
|
||||
warn!("Couldn't render dashboard: {:?}", e);
|
||||
|
||||
DashboardPage::NotConfigured(internal_server_error().await)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
DashboardPage::Unauthorised(Redirect::to("/login/discord"))
|
||||
}
|
||||
render_dashboard(cookies).await
|
||||
}
|
||||
|
||||
#[get("/<_..>")]
|
||||
pub async fn dashboard(cookies: &CookieJar<'_>) -> DashboardPage {
|
||||
render_dashboard(cookies).await
|
||||
}
|
||||
|
||||
async fn render_dashboard(cookies: &CookieJar<'_>) -> DashboardPage {
|
||||
if cookies.get_private("userid").is_some() {
|
||||
match NamedFile::open(Path::new(path!("static/index.html"))).await {
|
||||
Ok(f) => DashboardPage::Ok(f),
|
||||
|
@@ -19,6 +19,24 @@
|
||||
Fill out the "time" and "content" fields. If you wish, press on "Optional" to view other options
|
||||
for the reminder.
|
||||
</p>
|
||||
<p class="subtitle">Time</p>
|
||||
<p class="content">
|
||||
The bot will take a "best-guess" at what time you entered. It will favour UK date formats
|
||||
over US date formats (MM/DD/YY) where possible.
|
||||
<br>
|
||||
You can also use <code>cron</code>-like syntax to specify the time. For example, using
|
||||
<code>0 0 1 * *</code> will send the reminder at midnight on the first of the next month.
|
||||
For more information on cron syntax, see <a href="https://crontab.guru/">crontab.guru</a>.
|
||||
<br>
|
||||
<strong>Cron syntax is not repeating</strong>. Please use the optional "interval" field to specify a repetition interval.
|
||||
</p>
|
||||
<p class="subtitle">Pings</p>
|
||||
<p class="content">
|
||||
Roles and users can be pinged by including their @ mention in the "content" field.
|
||||
To ping a role, the role must be set as mentionable, and the bot must have permissions to mention the role.
|
||||
<br>
|
||||
Please note that when using the dashboard, roles can only be pinged in the "Content..." field and not the embed fields.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -37,4 +55,40 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="hero is-small">
|
||||
<div class="hero-body">
|
||||
<div class="container">
|
||||
<p class="title">Custom formatting rules</p>
|
||||
<p class="content">
|
||||
Reminder content can be customized using formatting rules.
|
||||
</p>
|
||||
<p class="subtitle">timefrom</p>
|
||||
<p class="content">
|
||||
The <code>timefrom</code> formatting rule will display a formatted difference
|
||||
between the time the reminder sends and a specified time.
|
||||
<br>
|
||||
For example, if the current time is 1755800000 (UNIX time), the format string
|
||||
<code><<timefrom:1755803600>></code> would display "1 hour"
|
||||
</p>
|
||||
<p class="subtitle">timenow</p>
|
||||
<p class="content">
|
||||
The <code>timenow</code> formatting rule displays the current time or an offset
|
||||
from the current time in a given timezone in a custom format.
|
||||
<br>
|
||||
For example, if the current time is 1755800000 (UNIX time), the format string
|
||||
<code><<timenow:UTC:%H:%M:%S>></code> would display "18:13:20"
|
||||
<br>
|
||||
Optionally, an offset can be provided to display a time from your current time.
|
||||
For example, if the current time is 1755800000 (UNIX time), the format string
|
||||
<code><<timenow+120:UTC:%H:%M:%S>></code> would display "18:15:20",
|
||||
or <code><<timenow-120:UTC:%H:%M:%S>></code> would display "18:11:20"
|
||||
<br>
|
||||
You can use this feature alongside Discord's timestamp formatting. The following
|
||||
will show the text "in 2 minutes" for all users as a Discord timestamp:
|
||||
<code><t:<<timenow+120:UTC:%s>>:R></code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{% endblock %}
|
||||
|
Reference in New Issue
Block a user