updated serenity to latest current. interval and remind commands are now operationally identical using one regex. interval accepts an optional third parameter which is an expiration point

This commit is contained in:
jellywx 2021-01-03 14:48:18 +00:00
parent c7c3b14c2d
commit 99c4a23bf0
5 changed files with 204 additions and 196 deletions

7
Cargo.lock generated
View File

@ -1316,7 +1316,7 @@ dependencies = [
[[package]] [[package]]
name = "reminder_rs" name = "reminder_rs"
version = "1.3.5" version = "1.4.0"
dependencies = [ dependencies = [
"Inflector", "Inflector",
"async-trait", "async-trait",
@ -1539,8 +1539,8 @@ dependencies = [
[[package]] [[package]]
name = "serenity" name = "serenity"
version = "0.9.0-rc.3" version = "0.9.3"
source = "git+https://github.com/jellywx/serenity?branch=jellywx-member_permissions#fc0af6a865d2cfdeeefbb02d297950bc34c0d87b" source = "git+https://github.com/serenity-rs/serenity?branch=current#0b1fc2737efebde01f6f3b781bcdfc83a30e908e"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"async-tungstenite", "async-tungstenite",
@ -1550,6 +1550,7 @@ dependencies = [
"chrono", "chrono",
"flate2", "flate2",
"futures", "futures",
"percent-encoding",
"reqwest", "reqwest",
"serde", "serde",
"serde_json", "serde_json",

View File

@ -1,6 +1,6 @@
[package] [package]
name = "reminder_rs" name = "reminder_rs"
version = "1.3.5" version = "1.4.0"
authors = ["jellywx <judesouthworth@pm.me>"] authors = ["jellywx <judesouthworth@pm.me>"]
edition = "2018" edition = "2018"
@ -25,8 +25,8 @@ Inflector = "0.11"
levenshtein = "1.0" levenshtein = "1.0"
[dependencies.serenity] [dependencies.serenity]
git = "https://github.com/jellywx/serenity" git = "https://github.com/serenity-rs/serenity"
branch = "jellywx-member_permissions" branch = "current"
default-features = false default-features = false
features = ["builder", "client", "framework", "cache", "gateway", "http", "model", "utils", "rustls_backend", "collector"] features = ["builder", "client", "framework", "cache", "gateway", "http", "model", "utils", "rustls_backend", "collector"]

View File

@ -3,7 +3,12 @@ use regex_command_attr::command;
use serenity::{ use serenity::{
client::Context, client::Context,
framework::Framework, framework::Framework,
model::{channel::Message, channel::ReactionType, id::ChannelId, id::RoleId}, model::{
channel::ReactionType,
channel::{Channel, Message},
id::ChannelId,
id::RoleId,
},
}; };
use chrono_tz::{Tz, TZ_VARIANTS}; use chrono_tz::{Tz, TZ_VARIANTS};
@ -312,10 +317,12 @@ async fn language(ctx: &Context, msg: &Message, args: String) {
.all_languages() .all_languages()
.map(|(k, _)| ReactionType::Unicode(lm.get(k, "flag").to_string())); .map(|(k, _)| ReactionType::Unicode(lm.get(k, "flag").to_string()));
let can_react = if let Some(guild) = msg.guild(&ctx).await { let can_react = if let Some(Channel::Guild(channel)) = msg.channel(&ctx).await {
guild channel
.user_permissions_in(msg.channel_id, ctx.cache.current_user().await) .permissions_for_user(&ctx, ctx.cache.current_user().await)
.add_reactions() .await
.map(|p| p.add_reactions())
.unwrap_or(false)
} else { } else {
true true
}; };
@ -367,11 +374,14 @@ async fn language(ctx: &Context, msg: &Message, args: String) {
} }
} }
if let Some(guild) = msg.guild(&ctx).await { if let Some(Channel::Guild(channel)) = msg.channel(&ctx).await {
let perms = let has_perms = channel
guild.user_permissions_in(msg.channel_id, ctx.cache.current_user().await); .permissions_for_user(&ctx, ctx.cache.current_user().await)
.await
.map(|p| p.manage_messages())
.unwrap_or(false);
if perms.manage_messages() { if has_perms {
let _ = sent_msg.delete_reactions(&ctx).await; let _ = sent_msg.delete_reactions(&ctx).await;
} }
} }

View File

@ -19,8 +19,8 @@ use crate::{
check_subscription_on_message, command_help, check_subscription_on_message, command_help,
consts::{ consts::{
CHARACTERS, DAY, HOUR, LOCAL_TIMEZONE, MAX_TIME, MINUTE, MIN_INTERVAL, PYTHON_LOCATION, CHARACTERS, DAY, HOUR, LOCAL_TIMEZONE, MAX_TIME, MINUTE, MIN_INTERVAL, PYTHON_LOCATION,
REGEX_CHANNEL, REGEX_CHANNEL_USER, REGEX_CONTENT_SUBSTITUTION, REGEX_INTERVAL_COMMAND, REGEX_CHANNEL, REGEX_CHANNEL_USER, REGEX_CONTENT_SUBSTITUTION, REGEX_REMIND_COMMAND,
REGEX_REMIND_COMMAND, THEME_COLOR, THEME_COLOR,
}, },
framework::SendIterator, framework::SendIterator,
get_ctx_data, get_ctx_data,
@ -818,6 +818,7 @@ enum ReminderError {
InvalidTag, InvalidTag,
NotEnoughArgs, NotEnoughArgs,
InvalidTime, InvalidTime,
InvalidExpiration,
NeedSubscription, NeedSubscription,
DiscordError(String), DiscordError(String),
} }
@ -846,6 +847,7 @@ impl ToResponse for ReminderError {
Self::InvalidTag => "remind/invalid_tag", Self::InvalidTag => "remind/invalid_tag",
Self::NotEnoughArgs => "remind/no_argument", Self::NotEnoughArgs => "remind/no_argument",
Self::InvalidTime => "remind/invalid_time", Self::InvalidTime => "remind/invalid_time",
Self::InvalidExpiration => "interval/invalid_expiration",
Self::NeedSubscription => "interval/donor", Self::NeedSubscription => "interval/donor",
Self::DiscordError(_) => "remind/generic_error", Self::DiscordError(_) => "remind/generic_error",
} }
@ -1010,33 +1012,10 @@ fn parse_mention_list(mentions: &str) -> Vec<ReminderScope> {
async fn remind_command(ctx: &Context, msg: &Message, args: String, command: RemindCommand) { async fn remind_command(ctx: &Context, msg: &Message, args: String, command: RemindCommand) {
let (pool, lm) = get_ctx_data(&ctx).await; let (pool, lm) = get_ctx_data(&ctx).await;
let user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap(); let timezone = UserData::timezone_of(&msg.author, &pool).await;
let language = UserData::language_of(&msg.author, &pool).await;
if command == RemindCommand::Interval { match REGEX_REMIND_COMMAND.captures(&args) {
if !check_subscription_on_message(&ctx, msg).await {
// breaker
let _ = msg
.channel_id
.say(
&ctx,
lm.get(&user_data.language, "interval/donor").replace(
"{prefix}",
&GuildData::prefix_from_id(msg.guild_id, &pool).await,
),
)
.await;
return;
}
}
let captures = match command {
RemindCommand::Remind => REGEX_REMIND_COMMAND.captures(&args),
RemindCommand::Interval => REGEX_INTERVAL_COMMAND.captures(&args),
};
match captures {
Some(captures) => { Some(captures) => {
let parsed = parse_mention_list(captures.name("mentions").unwrap().as_str()); let parsed = parse_mention_list(captures.name("mentions").unwrap().as_str());
@ -1046,144 +1025,160 @@ async fn remind_command(ctx: &Context, msg: &Message, args: String, command: Rem
parsed parsed
}; };
let time_parser = TimeParser::new( let time_parser = TimeParser::new(captures.name("time").unwrap().as_str(), timezone);
captures.name("time").unwrap().as_str(),
user_data.timezone(), let expires_parser = captures
); .name("expires")
.map(|mat| TimeParser::new(mat.as_str(), timezone));
let interval_parser = captures let interval_parser = captures
.name("interval") .name("interval")
.map(|mat| TimeParser::new(mat.as_str(), user_data.timezone())) .map(|mat| TimeParser::new(mat.as_str(), timezone))
.map(|parser| parser.displacement()) .map(|parser| parser.displacement())
.transpose(); .transpose();
if let Ok(interval) = interval_parser { if let Ok(interval) = interval_parser {
let content_res = Content::build( if interval.is_some() && !check_subscription_on_message(&ctx, msg).await {
captures.name("content").map(|mat| mat.as_str()).unwrap(), // no patreon
msg, let _ = msg
) .channel_id
.await; .say(
&ctx,
lm.get(&language, "interval/donor").replace(
"{prefix}",
&GuildData::prefix_from_id(msg.guild_id, &pool).await,
),
)
.await;
} else {
let content_res = Content::build(
captures.name("content").map(|mat| mat.as_str()).unwrap(),
msg,
)
.await;
match content_res { match content_res {
Ok(mut content) => { Ok(mut content) => {
let mut ok_locations = vec![]; let mut ok_locations = vec![];
let mut err_locations = vec![]; let mut err_locations = vec![];
let mut err_types = HashSet::new(); let mut err_types = HashSet::new();
for scope in scopes { for scope in scopes {
let res = create_reminder( let res = create_reminder(
&ctx, &ctx,
&pool, &pool,
msg.author.id, msg.author.id,
msg.guild_id, msg.guild_id,
&scope, &scope,
&time_parser, &time_parser,
interval, expires_parser.as_ref().clone(),
&mut content, interval,
) &mut content,
.await;
if let Err(e) = res {
err_locations.push(scope);
err_types.insert(e);
} else {
ok_locations.push(scope);
}
}
let success_part = match ok_locations.len() {
0 => "".to_string(),
1 => lm
.get(&user_data.language, "remind/success")
.replace("{location}", &ok_locations[0].mention())
.replace(
"{offset}",
&shorthand_displacement(
time_parser.displacement().unwrap() as u64
),
),
n => lm
.get(&user_data.language, "remind/success_bulk")
.replace("{number}", &n.to_string())
.replace(
"{location}",
&ok_locations
.iter()
.map(|l| l.mention())
.collect::<Vec<String>>()
.join(", "),
) )
.replace( .await;
"{offset}",
&shorthand_displacement(
time_parser.displacement().unwrap() as u64
),
),
};
let error_part = format!( if let Err(e) = res {
"{}\n{}", err_locations.push(scope);
match err_locations.len() { err_types.insert(e);
} else {
ok_locations.push(scope);
}
}
let success_part = match ok_locations.len() {
0 => "".to_string(), 0 => "".to_string(),
1 => lm 1 => lm
.get(&user_data.language, "remind/issue") .get(&language, "remind/success")
.replace("{location}", &err_locations[0].mention()), .replace("{location}", &ok_locations[0].mention())
.replace(
"{offset}",
&shorthand_displacement(
time_parser.displacement().unwrap() as u64,
),
),
n => lm n => lm
.get(&user_data.language, "remind/issue_bulk") .get(&language, "remind/success_bulk")
.replace("{number}", &n.to_string()) .replace("{number}", &n.to_string())
.replace( .replace(
"{location}", "{location}",
&err_locations &ok_locations
.iter() .iter()
.map(|l| l.mention()) .map(|l| l.mention())
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", "), .join(", "),
)
.replace(
"{offset}",
&shorthand_displacement(
time_parser.displacement().unwrap() as u64,
),
), ),
}, };
err_types
.iter()
.map(|err| match err {
ReminderError::DiscordError(s) => lm
.get(&user_data.language, err.to_response())
.replace("{error}", &s),
_ => lm.get(&user_data.language, err.to_response()).to_string(), let error_part = format!(
}) "{}\n{}",
.collect::<Vec<String>>() match err_locations.len() {
.join("\n") 0 => "".to_string(),
); 1 => lm
.get(&language, "remind/issue")
.replace("{location}", &err_locations[0].mention()),
n => lm
.get(&language, "remind/issue_bulk")
.replace("{number}", &n.to_string())
.replace(
"{location}",
&err_locations
.iter()
.map(|l| l.mention())
.collect::<Vec<String>>()
.join(", "),
),
},
err_types
.iter()
.map(|err| match err {
ReminderError::DiscordError(s) => lm
.get(&language, err.to_response())
.replace("{error}", &s),
let _ = msg _ => lm.get(&language, err.to_response()).to_string(),
.channel_id })
.send_message(&ctx, |m| { .collect::<Vec<String>>()
m.embed(|e| { .join("\n")
e.title( );
lm.get(&user_data.language, "remind/title")
.replace("{number}", &ok_locations.len().to_string()),
)
.description(format!("{}\n\n{}", success_part, error_part))
.color(*THEME_COLOR)
})
})
.await;
}
Err(content_error) => { let _ = msg
let _ = msg .channel_id
.channel_id .send_message(&ctx, |m| {
.send_message(ctx, |m| { m.embed(|e| {
m.embed(move |e| { e.title(
e.title( lm.get(&language, "remind/title").replace(
lm.get(&user_data.language, "remind/title") "{number}",
.replace("{number}", "0"), &ok_locations.len().to_string(),
) ),
.description( )
lm.get(&user_data.language, content_error.to_response()), .description(format!("{}\n\n{}", success_part, error_part))
) .color(*THEME_COLOR)
.color(*THEME_COLOR) })
}) })
}) .await;
.await; }
Err(content_error) => {
let _ = msg
.channel_id
.send_message(ctx, |m| {
m.embed(move |e| {
e.title(
lm.get(&language, "remind/title")
.replace("{number}", "0"),
)
.description(lm.get(&language, content_error.to_response()))
.color(*THEME_COLOR)
})
})
.await;
}
} }
} }
} else { } else {
@ -1191,12 +1186,9 @@ async fn remind_command(ctx: &Context, msg: &Message, args: String, command: Rem
.channel_id .channel_id
.send_message(ctx, |m| { .send_message(ctx, |m| {
m.embed(move |e| { m.embed(move |e| {
e.title( e.title(lm.get(&language, "remind/title").replace("{number}", "0"))
lm.get(&user_data.language, "remind/title") .description(lm.get(&language, "interval/invalid_interval"))
.replace("{number}", "0"), .color(*THEME_COLOR)
)
.description(lm.get(&user_data.language, "interval/invalid_interval"))
.color(*THEME_COLOR)
}) })
}) })
.await; .await;
@ -1208,11 +1200,11 @@ async fn remind_command(ctx: &Context, msg: &Message, args: String, command: Rem
match command { match command {
RemindCommand::Remind => { RemindCommand::Remind => {
command_help(ctx, msg, lm, &prefix, &user_data.language, "remind").await command_help(ctx, msg, lm, &prefix, &language, "remind").await
} }
RemindCommand::Interval => { RemindCommand::Interval => {
command_help(ctx, msg, lm, &prefix, &user_data.language, "interval").await command_help(ctx, msg, lm, &prefix, &language, "interval").await
} }
} }
} }
@ -1336,6 +1328,7 @@ async fn natural(ctx: &Context, msg: &Message, args: String) {
msg.guild_id, msg.guild_id,
&scope, &scope,
timestamp, timestamp,
None,
interval, interval,
&mut content, &mut content,
) )
@ -1463,6 +1456,7 @@ async fn create_reminder<'a, U: Into<u64>, T: TryInto<i64>>(
guild_id: Option<GuildId>, guild_id: Option<GuildId>,
scope_id: &ReminderScope, scope_id: &ReminderScope,
time_parser: T, time_parser: T,
expires_parser: Option<T>,
interval: Option<i64>, interval: Option<i64>,
content: &mut Content, content: &mut Content,
) -> Result<(), ReminderError> { ) -> Result<(), ReminderError> {
@ -1527,42 +1521,45 @@ async fn create_reminder<'a, U: Into<u64>, T: TryInto<i64>>(
} else { } else {
match time_parser.try_into() { match time_parser.try_into() {
Ok(time_pre) => { Ok(time_pre) => {
let time = time_pre + nudge as i64; match expires_parser.map(|t| t.try_into()).transpose() {
Ok(expires) => {
let time = time_pre + nudge as i64;
let unix_time = SystemTime::now() let unix_time = SystemTime::now()
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
.unwrap() .unwrap()
.as_secs() as i64; .as_secs() as i64;
if time >= unix_time - 10 { if time >= unix_time - 10 {
if time > unix_time + *MAX_TIME { if time > unix_time + *MAX_TIME {
Err(ReminderError::LongTime) Err(ReminderError::LongTime)
} else { } else {
sqlx::query!( sqlx::query!(
" "
INSERT INTO messages (content, tts, attachment, attachment_name) VALUES (?, ?, ?, ?) INSERT INTO messages (content, tts, attachment, attachment_name) VALUES (?, ?, ?, ?)
", ",
content.content, content.content,
content.tts, content.tts,
content.attachment, content.attachment,
content.attachment_name, content.attachment_name,
) )
.execute(&pool.clone()) .execute(&pool.clone())
.await .await
.unwrap(); .unwrap();
sqlx::query!( sqlx::query!(
" "
INSERT INTO reminders (uid, message_id, channel_id, time, `interval`, method, set_by) VALUES INSERT INTO reminders (uid, message_id, channel_id, time, expires, `interval`, method, set_by) VALUES
(?, (?,
(SELECT id FROM messages WHERE content = ? ORDER BY id DESC LIMIT 1), (SELECT id FROM messages WHERE content = ? ORDER BY id DESC LIMIT 1),
?, ?, ?, 'remind', ?, ?, ?, ?, 'remind',
(SELECT id FROM users WHERE user = ? LIMIT 1)) (SELECT id FROM users WHERE user = ? LIMIT 1))
", ",
generate_uid(), generate_uid(),
content.content, content.content,
db_channel_id, db_channel_id,
time as u32, time as u32,
expires,
interval, interval,
user_id user_id
) )
@ -1570,13 +1567,17 @@ INSERT INTO reminders (uid, message_id, channel_id, time, `interval`, method, se
.await .await
.unwrap(); .unwrap();
Ok(()) Ok(())
}
} else if time < 0 {
// case required for if python returns -1
Err(ReminderError::InvalidTime)
} else {
Err(ReminderError::PastTime)
}
} }
} else if time < 0 {
// case required for if python returns -1 Err(_) => Err(ReminderError::InvalidExpiration),
Err(ReminderError::InvalidTime)
} else {
Err(ReminderError::PastTime)
} }
} }

View File

@ -50,11 +50,7 @@ lazy_static! {
pub static ref REGEX_CHANNEL_USER: Regex = Regex::new(r#"\s*<(#|@)(?:!)?(\d+)>\s*"#).unwrap(); pub static ref REGEX_CHANNEL_USER: Regex = Regex::new(r#"\s*<(#|@)(?:!)?(\d+)>\s*"#).unwrap();
pub static ref REGEX_REMIND_COMMAND: Regex = Regex::new( pub static ref REGEX_REMIND_COMMAND: Regex = Regex::new(
r#"(?P<mentions>(?:<@\d+>\s|<@!\d+>\s|<#\d+>\s)*)(?P<time>(?:(?:\d+)(?:s|m|h|d|:|/|-|))+|()) (?P<content>.*)"#) r#"(?P<mentions>(?:<@\d+>\s|<@!\d+>\s|<#\d+>\s)*)(?P<time>(?:(?:\d+)(?:s|m|h|d|:|/|-|))+)(?:\s+(?P<interval>(?:(?:\d+)(?:s|m|h|d|))+))?(?:\s+(?P<expires>(?:(?:\d+)(?:s|m|h|d|:|/|-|))+))?\s+(?P<content>.*)"#)
.unwrap();
pub static ref REGEX_INTERVAL_COMMAND: Regex = Regex::new(
r#"(?P<mentions>(?:<@\d+>\s|<@!\d+>\s|<#\d+>\s)*)(?P<time>(?:(?:\d+)(?:s|m|h|d|:|/|-|))+) (?P<interval>(?:(?:\d+)(?:s|m|h|d|))+) (?P<content>.*)"#)
.unwrap(); .unwrap();
pub static ref SUBSCRIPTION_ROLES: HashSet<u64> = HashSet::from_iter( pub static ref SUBSCRIPTION_ROLES: HashSet<u64> = HashSet::from_iter(