added count to del. changed inner joins to left outers. moved all consts and lazies into consts.rs. more formatting fixes

This commit is contained in:
jude 2020-10-11 17:41:26 +01:00
parent 1f41343e2e
commit 47ad3f3822
4 changed files with 104 additions and 50 deletions

View File

@ -14,8 +14,6 @@ use serenity::{
}, },
}; };
use regex::Regex;
use chrono_tz::Tz; use chrono_tz::Tz;
use chrono::offset::Utc; use chrono::offset::Utc;
@ -31,19 +29,16 @@ use crate::{
SQLPool, SQLPool,
FrameworkCtx, FrameworkCtx,
framework::SendIterator, framework::SendIterator,
consts::{
REGEX_ALIAS,
REGEX_CHANNEL,
REGEX_COMMANDS,
REGEX_ROLE,
},
}; };
use std::iter; use std::iter;
lazy_static! {
static ref REGEX_CHANNEL: Regex = Regex::new(r#"^\s*<#(\d+)>\s*$"#).unwrap();
static ref REGEX_ROLE: Regex = Regex::new(r#"<@&([0-9]+)>"#).unwrap();
static ref REGEX_COMMANDS: Regex = Regex::new(r#"([a-z]+)"#).unwrap();
static ref REGEX_ALIAS: Regex = Regex::new(r#"(?P<name>[\S]{1,12})(?:(?: (?P<cmd>.*)$)|$)"#).unwrap();
}
#[command] #[command]
#[supports_dm(false)] #[supports_dm(false)]
@ -82,7 +77,6 @@ async fn timezone(ctx: &Context, msg: &Message, args: String) -> CommandResult {
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data"); .get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let mut user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap(); let mut user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
let guild_data = GuildData::from_guild(msg.guild(&ctx).await.unwrap(), &pool).await.unwrap();
if !args.is_empty() { if !args.is_empty() {
match args.parse::<Tz>() { match args.parse::<Tz>() {
@ -106,7 +100,7 @@ async fn timezone(ctx: &Context, msg: &Message, args: String) -> CommandResult {
} }
else { else {
let content = user_data.response(&pool, "timezone/no_argument").await let content = user_data.response(&pool, "timezone/no_argument").await
.replace("{prefix}", &guild_data.prefix) .replace("{prefix}", &GuildData::prefix_from_id(msg.guild_id, &pool).await)
.replacen("{timezone}", &user_data.timezone, 1); .replacen("{timezone}", &user_data.timezone, 1);
let _ = msg.channel_id.say(&ctx, content).await; let _ = msg.channel_id.say(&ctx, content).await;

View File

@ -23,6 +23,13 @@ use serenity::{
use tokio::process::Command; use tokio::process::Command;
use crate::{ use crate::{
consts::{
REGEX_CHANNEL,
REGEX_CHANNEL_USER,
MIN_INTERVAL,
MAX_TIME,
CHARACTERS,
},
models::{ models::{
ChannelData, ChannelData,
GuildData, GuildData,
@ -71,18 +78,6 @@ use regex::Regex;
use serde_json::json; use serde_json::json;
lazy_static! {
static ref REGEX_CHANNEL: Regex = Regex::new(r#"^\s*<#(\d+)>\s*$"#).unwrap();
static ref REGEX_CHANNEL_USER: Regex = Regex::new(r#"^\s*<(#|@)(?:!)?(\d+)>\s*$"#).unwrap();
static ref MIN_INTERVAL: i64 = env::var("MIN_INTERVAL").ok().map(|inner| inner.parse::<i64>().ok()).flatten().unwrap_or(600);
static ref MAX_TIME: i64 = env::var("MAX_TIME").ok().map(|inner| inner.parse::<i64>().ok()).flatten().unwrap_or(60*60*24*365*50);
}
static CHARACTERS: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
#[command] #[command]
#[supports_dm(false)] #[supports_dm(false)]
@ -330,7 +325,7 @@ SELECT
reminders.id, reminders.time, messages.content, channels.channel reminders.id, reminders.time, messages.content, channels.channel
FROM FROM
reminders reminders
INNER JOIN LEFT OUTER JOIN
channels channels
ON ON
channels.id = reminders.channel_id channels.id = reminders.channel_id
@ -392,14 +387,14 @@ SELECT
reminders.id, reminders.time, messages.content, channels.channel reminders.id, reminders.time, messages.content, channels.channel
FROM FROM
reminders reminders
INNER JOIN LEFT OUTER JOIN
channels channels
ON ON
reminders.channel_id = channels.id channels.id = reminders.channel_id
INNER JOIN INNER JOIN
messages messages
ON ON
reminders.message_id = messages.id messages.id = reminders.message_id
WHERE WHERE
channels.guild_id = (SELECT id FROM guilds WHERE guild = ?) channels.guild_id = (SELECT id FROM guilds WHERE guild = ?)
", guild_id) ", guild_id)
@ -467,17 +462,30 @@ WHERE
.collect::<Vec<String>>(); .collect::<Vec<String>>();
if parts.len() == valid_parts.len() { if parts.len() == valid_parts.len() {
let joined = valid_parts.join(",");
let count_row = sqlx::query!(
"
SELECT COUNT(1) AS count FROM reminders WHERE FIND_IN_SET(id, ?)
", joined)
.fetch_one(&pool)
.await
.unwrap();
sqlx::query!( sqlx::query!(
" "
DELETE FROM reminders WHERE FIND_IN_SET(id, ?) DELETE FROM reminders WHERE FIND_IN_SET(id, ?)
", valid_parts.join(",")) ", joined)
.execute(&pool) .execute(&pool)
.await .await
.unwrap(); .unwrap();
// TODO add deletion events to event list // TODO add deletion events to event list
let _ = msg.channel_id.say(&ctx, user_data.response(&pool, "del/count").await).await; let content = user_data.response(&pool, "del/count").await
.replacen("{}", &count_row.count.to_string(), 1);
let _ = msg.channel_id.say(&ctx, content).await;
} }
} }
@ -599,6 +607,7 @@ custom_error!{ReminderError
InvalidTag = "Invalid reminder scope", InvalidTag = "Invalid reminder scope",
NotEnoughArgs = "Not enough args", NotEnoughArgs = "Not enough args",
InvalidTime = "Invalid time provided", InvalidTime = "Invalid time provided",
NeedSubscription = "Subscription required and not found",
DiscordError = "Bad response received from Discord" DiscordError = "Bad response received from Discord"
} }
@ -618,6 +627,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::NeedSubscription => "interval/donor",
Self::DiscordError => "remind/no_webhook", Self::DiscordError => "remind/no_webhook",
}.to_string() }.to_string()
} }
@ -625,6 +635,7 @@ impl ToResponse for ReminderError {
fn to_response_natural(&self) -> String { fn to_response_natural(&self) -> String {
match self { match self {
Self::LongTime => "natural/long_time".to_string(), Self::LongTime => "natural/long_time".to_string(),
Self::InvalidTime => "natural/invalid_time".to_string(),
_ => self.to_response(), _ => self.to_response(),
} }
} }
@ -709,6 +720,9 @@ async fn remind_command(ctx: &Context, msg: &Message, args: String, command: Rem
Err(ReminderError::NotEnoughArgs) Err(ReminderError::NotEnoughArgs)
} }
} }
else if command == RemindCommand::Interval {
Err(ReminderError::NeedSubscription)
}
else { else {
let content = args_iter.collect::<Vec<&str>>().join(" "); let content = args_iter.collect::<Vec<&str>>().join(" ");
@ -769,6 +783,7 @@ async fn remind_command(ctx: &Context, msg: &Message, args: String, command: Rem
let offset = time_parser.map(|tp| tp.displacement().ok()).flatten().unwrap_or(0) as u64; let offset = time_parser.map(|tp| tp.displacement().ok()).flatten().unwrap_or(0) as u64;
let str_response = user_data.response(&pool, &response.to_response()).await let str_response = user_data.response(&pool, &response.to_response()).await
.replace("{prefix}", &GuildData::prefix_from_id(msg.guild_id, &pool).await)
.replacen("{location}", &scope_id.mention(), 1) .replacen("{location}", &scope_id.mention(), 1)
.replacen("{offset}", &shorthand_displacement(offset), 1) .replacen("{offset}", &shorthand_displacement(offset), 1)
.replacen("{min_interval}", &MIN_INTERVAL.to_string(), 1) .replacen("{min_interval}", &MIN_INTERVAL.to_string(), 1)
@ -887,6 +902,7 @@ async fn natural(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let offset = timestamp as u64 - since_epoch.as_secs(); let offset = timestamp as u64 - since_epoch.as_secs();
let str_response = user_data.response(&pool, &res.to_response_natural()).await let str_response = user_data.response(&pool, &res.to_response_natural()).await
.replace("{prefix}", &GuildData::prefix_from_id(msg.guild_id, &pool).await)
.replacen("{location}", &location_id.mention(), 1) .replacen("{location}", &location_id.mention(), 1)
.replacen("{offset}", &shorthand_displacement(offset), 1) .replacen("{offset}", &shorthand_displacement(offset), 1)
.replacen("{min_interval}", &MIN_INTERVAL.to_string(), 1) .replacen("{min_interval}", &MIN_INTERVAL.to_string(), 1)
@ -1004,7 +1020,7 @@ async fn create_reminder<T: TryInto<i64>, S: ToString + Type<MySql> + Encode<MyS
let unix_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64; let unix_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
if time > unix_time { if time >= unix_time {
if time > unix_time + *MAX_TIME { if time > unix_time + *MAX_TIME {
Err(ReminderError::LongTime) Err(ReminderError::LongTime)
} }
@ -1032,6 +1048,10 @@ INSERT INTO reminders (uid, message_id, channel_id, time, `interval`, method, se
Ok(()) Ok(())
} }
} }
else if time < 0 {
// case required for if python returns -1
Err(ReminderError::InvalidTime)
}
else { else {
Err(ReminderError::PastTime) Err(ReminderError::PastTime)
} }

View File

@ -4,3 +4,43 @@ pub const MAX_MESSAGE_LENGTH: usize = 2048;
pub const DAY: u64 = 86_400; pub const DAY: u64 = 86_400;
pub const HOUR: u64 = 3_600; pub const HOUR: u64 = 3_600;
pub const MINUTE: u64 = 60; pub const MINUTE: u64 = 60;
pub const CHARACTERS: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
use std::{
iter::FromIterator,
env,
collections::HashSet,
};
use lazy_static;
use regex::Regex;
lazy_static! {
pub static ref SUBSCRIPTION_ROLES: HashSet<u64> = HashSet::from_iter(env::var("SUBSCRIPTION_ROLES")
.map(
|var| var
.split(',')
.filter_map(|item| {
item.parse::<u64>().ok()
})
.collect::<Vec<u64>>()
).unwrap_or_else(|_| vec![]));
pub static ref CNC_GUILD: Option<u64> = env::var("CNC_GUILD").map(|var| var.parse::<u64>().ok()).ok().flatten();
pub static ref REGEX_CHANNEL: Regex = Regex::new(r#"^\s*<#(\d+)>\s*$"#).unwrap();
pub static ref REGEX_ROLE: Regex = Regex::new(r#"<@&([0-9]+)>"#).unwrap();
pub static ref REGEX_COMMANDS: Regex = Regex::new(r#"([a-z]+)"#).unwrap();
pub static ref REGEX_ALIAS: Regex = Regex::new(r#"(?P<name>[\S]{1,12})(?:(?: (?P<cmd>.*)$)|$)"#).unwrap();
pub static ref REGEX_CHANNEL_USER: Regex = Regex::new(r#"^\s*<(#|@)(?:!)?(\d+)>\s*$"#).unwrap();
pub static ref MIN_INTERVAL: i64 = env::var("MIN_INTERVAL").ok().map(|inner| inner.parse::<i64>().ok()).flatten().unwrap_or(600);
pub static ref MAX_TIME: i64 = env::var("MAX_TIME").ok().map(|inner| inner.parse::<i64>().ok()).flatten().unwrap_or(60*60*24*365*50);
}

View File

@ -9,7 +9,10 @@ mod consts;
use serenity::{ use serenity::{
cache::Cache, cache::Cache,
http::CacheHttp, http::{
CacheHttp,
client::Http,
},
client::{ client::{
bridge::gateway::GatewayIntents, bridge::gateway::GatewayIntents,
Client, Client,
@ -43,6 +46,7 @@ use crate::{
framework::RegexFramework, framework::RegexFramework,
consts::{ consts::{
PREFIX, DAY, HOUR, MINUTE, PREFIX, DAY, HOUR, MINUTE,
SUBSCRIPTION_ROLES, CNC_GUILD,
}, },
commands::{ commands::{
info_cmds, info_cmds,
@ -51,7 +55,9 @@ use crate::{
moderation_cmds, moderation_cmds,
}, },
}; };
use num_integer::Integer; use num_integer::Integer;
use serenity::futures::TryFutureExt;
struct SQLPool; struct SQLPool;
@ -77,7 +83,11 @@ static THEME_COLOR: u32 = 0x8fb677;
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
dotenv()?; dotenv()?;
let framework = RegexFramework::new(env::var("CLIENT_ID").expect("Missing CLIENT_ID from environment").parse()?) let token = env::var("DISCORD_TOKEN").expect("Missing DISCORD_TOKEN from environment");
let http = Http::new_with_token(&token);
let framework = RegexFramework::new(http.get_current_user().map_ok(|user| user.id.as_u64().to_owned()).await?)
.ignore_bots(true) .ignore_bots(true)
.default_prefix(&env::var("DEFAULT_PREFIX").unwrap_or_else(|_| PREFIX.to_string())) .default_prefix(&env::var("DEFAULT_PREFIX").unwrap_or_else(|_| PREFIX.to_string()))
@ -122,7 +132,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let framework_arc = Arc::new(Box::new(framework) as Box<dyn Framework + Send + Sync>); let framework_arc = Arc::new(Box::new(framework) as Box<dyn Framework + Send + Sync>);
let mut client = Client::new(&env::var("DISCORD_TOKEN").expect("Missing DISCORD_TOKEN from environment")) let mut client = Client::new(&token)
.intents(GatewayIntents::GUILD_MESSAGES | GatewayIntents::GUILDS | GatewayIntents::DIRECT_MESSAGES) .intents(GatewayIntents::GUILD_MESSAGES | GatewayIntents::GUILDS | GatewayIntents::DIRECT_MESSAGES)
.framework_arc(framework_arc.clone()) .framework_arc(framework_arc.clone())
.await.expect("Error occurred creating client"); .await.expect("Error occurred creating client");
@ -144,23 +154,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
pub async fn check_subscription(cache_http: impl CacheHttp, user_id: impl Into<UserId>) -> bool { pub async fn check_subscription(cache_http: impl CacheHttp, user_id: impl Into<UserId>) -> bool {
let role_ids = env::var("SUBSCRIPTION_ROLES")
.map(
|var| var
.split(',')
.filter_map(|item| {
item.parse::<u64>().ok()
})
.collect::<Vec<u64>>()
);
if let Some(subscription_guild) = env::var("CNC_GUILD").map(|var| var.parse::<u64>().ok()).ok().flatten() { if let Some(subscription_guild) = *CNC_GUILD {
if let Ok(role_ids) = role_ids { let guild_member = GuildId(subscription_guild).member(cache_http, user_id).await;
// todo remove unwrap and propagate error
let guild_member = GuildId(subscription_guild).member(cache_http, user_id).await.unwrap();
for role in guild_member.roles { if let Ok(member) = guild_member {
if role_ids.contains(role.as_u64()) { for role in member.roles {
if SUBSCRIPTION_ROLES.contains(role.as_u64()) {
return true return true
} }
} }