revamped natural to use a regex to match commands. natural now supports until parameter

This commit is contained in:
jellywx 2021-01-14 17:56:57 +00:00
parent 702743c108
commit 04232162f2
3 changed files with 178 additions and 208 deletions

View File

@ -1,11 +1,13 @@
use regex_command_attr::command;
use serenity::{
cache::Cache,
client::Context,
http::CacheHttp,
model::{
channel::GuildChannel,
channel::Message,
guild::Guild,
id::{ChannelId, GuildId, UserId},
misc::Mentionable,
webhook::Webhook,
@ -16,14 +18,13 @@ use serenity::{
use crate::{
check_subscription_on_message, command_help,
consts::{
CHARACTERS, DAY, HOUR, LOCAL_TIMEZONE, MAX_TIME, MINUTE, MIN_INTERVAL, PYTHON_LOCATION,
REGEX_CHANNEL, REGEX_CHANNEL_USER, REGEX_CONTENT_SUBSTITUTION, REGEX_REMIND_COMMAND,
THEME_COLOR,
CHARACTERS, DAY, HOUR, MAX_TIME, MINUTE, MIN_INTERVAL, REGEX_CHANNEL, REGEX_CHANNEL_USER,
REGEX_CONTENT_SUBSTITUTION, REGEX_NATURAL_COMMAND, REGEX_REMIND_COMMAND, THEME_COLOR,
},
framework::SendIterator,
get_ctx_data,
models::{ChannelData, GuildData, Timer, UserData},
time_parser::TimeParser,
time_parser::{natural_parser, TimeParser},
};
use chrono::{offset::TimeZone, NaiveDateTime};
@ -32,8 +33,6 @@ use rand::{rngs::OsRng, seq::IteratorRandom};
use sqlx::MySqlPool;
use std::str::from_utf8;
use num_integer::Integer;
use std::{
@ -45,10 +44,7 @@ use std::{
time::{SystemTime, UNIX_EPOCH},
};
use regex::{Captures, RegexBuilder};
use serenity::cache::Cache;
use serenity::model::guild::Guild;
use tokio::process::Command;
use regex::Captures;
fn shorthand_displacement(seconds: u64) -> String {
let (days, seconds) = seconds.div_rem(&DAY);
@ -1224,94 +1220,33 @@ async fn natural(ctx: &Context, msg: &Message, args: String) {
let user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
let send_str = lm.get(&user_data.language, "natural/send");
let to_str = lm.get(&user_data.language, "natural/to");
let every_str = lm.get(&user_data.language, "natural/every");
let mut args_iter = args.splitn(2, &send_str);
let (time_crop_opt, msg_crop_opt) = (args_iter.next(), args_iter.next().map(|m| m.trim()));
if let (Some(time_crop), Some(msg_crop)) = (time_crop_opt, msg_crop_opt) {
let python_call = Command::new(&*PYTHON_LOCATION)
.arg("-c")
.arg(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/dp.py")))
.arg(time_crop)
.arg(&user_data.timezone)
.arg(&*LOCAL_TIMEZONE)
.output()
.await;
if let Some(timestamp) = python_call
.ok()
.map(|inner| {
if inner.status.success() {
Some(from_utf8(&*inner.stdout).unwrap().parse::<i64>().unwrap())
} else {
None
}
})
.flatten()
match REGEX_NATURAL_COMMAND.captures(&args) {
Some(captures) => {
let location_ids = if let Some(mentions) = captures.name("mentions").map(|m| m.as_str())
{
let mut location_ids = vec![ReminderScope::Channel(msg.channel_id.as_u64().to_owned())];
let mut content = msg_crop;
let mut interval = None;
parse_mention_list(mentions)
} else {
vec![ReminderScope::Channel(msg.channel_id.into())]
};
if msg.guild_id.is_some() {
let re_match = RegexBuilder::new(&format!(r#"(?:\s*)(?P<msg>.*) {} (?P<mentions>((?:<@\d+>)|(?:<@!\d+>)|(?:<#\d+>)|(?:\s+))+)$"#, to_str))
.dot_matches_new_line(true)
.build()
.unwrap()
.captures(msg_crop);
if let Some(captures) = re_match {
content = captures.name("msg").unwrap().as_str();
let mentions = captures.name("mentions").unwrap().as_str();
location_ids = parse_mention_list(mentions);
}
}
if check_subscription_on_message(&ctx, &msg).await {
let re_match =
RegexBuilder::new(&format!(r#"(?P<msg>.*) {} (?P<interval>.*)$"#, every_str))
.dot_matches_new_line(true)
.build()
.unwrap()
.captures(content);
if let Some(captures) = re_match {
content = captures.name("msg").unwrap().as_str();
let interval_str = captures.name("interval").unwrap().as_str();
let python_call = Command::new(&*PYTHON_LOCATION)
.arg("-c")
.arg(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/dp.py")))
.arg(&format!("1 {}", interval_str))
.arg(&*LOCAL_TIMEZONE)
.arg(&*LOCAL_TIMEZONE)
.output()
.await;
interval = python_call
.ok()
.map(|inner| {
if inner.status.success() {
Some(
from_utf8(&*inner.stdout).unwrap().parse::<i64>().unwrap()
- since_epoch.as_secs() as i64,
)
let expires = if let Some(expires_crop) = captures.name("expires") {
natural_parser(expires_crop.as_str(), &user_data.timezone).await
} else {
None
}
})
.flatten();
}
}
};
let content_res = Content::build(&content, msg).await;
let interval = if let Some(interval_crop) = captures.name("interval") {
natural_parser(interval_crop.as_str(), &user_data.timezone)
.await
.map(|i| i - since_epoch.as_secs() as i64)
} else {
None
};
if let Some(timestamp) =
natural_parser(captures.name("time").unwrap().as_str(), &user_data.timezone).await
{
let content_res = Content::build(captures.name("msg").unwrap().as_str(), msg).await;
match content_res {
Ok(mut content) => {
@ -1329,8 +1264,8 @@ async fn natural(ctx: &Context, msg: &Message, args: String) {
msg.guild_id,
&scope,
timestamp,
None,
interval,
expires,
interval.clone(),
&mut content,
)
.await;
@ -1436,7 +1371,9 @@ async fn natural(ctx: &Context, msg: &Message, args: String) {
.say(&ctx, "DEV ERROR: Failed to invoke Python")
.await;
}
} else {
}
None => {
let prefix = GuildData::prefix_from_id(msg.guild_id, &pool).await;
let resp = lm
@ -1448,6 +1385,7 @@ async fn natural(ctx: &Context, msg: &Message, args: String) {
.send_message(&ctx, |m| m.embed(|e| e.description(resp)))
.await;
}
}
}
async fn create_reminder<'a, U: Into<u64>, T: TryInto<i64>>(

View File

@ -50,7 +50,13 @@ lazy_static! {
pub static ref REGEX_CHANNEL_USER: Regex = Regex::new(r#"\s*<(#|@)(?:!)?(\d+)>\s*"#).unwrap();
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|:|/|-|))+)(?:\s+(?P<interval>(?:(?:\d+)(?:s|m|h|d|))+))?(?:\s+(?P<expires>(?:(?:\d+)(?:s|m|h|d|:|/|-|))+))?\s+(?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_NATURAL_COMMAND: Regex = Regex::new(
r#"(?P<time>.*?) send (?P<msg>.*?)(?: every (?P<interval>.*?)(?: until (?P<expires>.*?))?)?(?: to (?P<mentions>((?:<@\d+>)|(?:<@!\d+>)|(?:<#\d+>)|(?:\s+))+))?$"#
)
.unwrap();
pub static ref SUBSCRIPTION_ROLES: HashSet<u64> = HashSet::from_iter(

View File

@ -2,9 +2,13 @@ use std::time::{SystemTime, UNIX_EPOCH};
use std::fmt::{Display, Formatter, Result as FmtResult};
use crate::consts::{LOCAL_TIMEZONE, PYTHON_LOCATION};
use chrono::TimeZone;
use chrono_tz::Tz;
use std::convert::TryFrom;
use std::str::from_utf8;
use tokio::process::Command;
#[derive(Debug)]
pub enum InvalidTime {
@ -172,3 +176,25 @@ impl TimeParser {
Ok(full)
}
}
pub(crate) async fn natural_parser(time: &str, timezone: &str) -> Option<i64> {
Command::new(&*PYTHON_LOCATION)
.arg("-c")
.arg(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/dp.py")))
.arg(time)
.arg(timezone)
.arg(&*LOCAL_TIMEZONE)
.output()
.await
.ok()
.map(|inner| {
if inner.status.success() {
Some(from_utf8(&*inner.stdout).unwrap().parse::<i64>().unwrap())
} else {
None
}
})
.flatten()
.map(|inner| if inner < 0 { None } else { Some(inner) })
.flatten()
}