removed unreleased code. fixed offset command

This commit is contained in:
jellywx 2021-11-07 23:36:07 +00:00
parent 85a8ae625d
commit f9c110ffb7
9 changed files with 289 additions and 610 deletions

617
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
[package]
name = "reminder_rs"
version = "1.5.1"
version = "1.5.2"
authors = ["jellywx <judesouthworth@pm.me>"]
edition = "2018"
@ -22,11 +22,8 @@ serde_json = "1.0"
rand = "0.7"
Inflector = "0.11"
levenshtein = "1.0"
# serenity = { version = "0.10", features = ["collector"] }
serenity = { path = "/home/jude/serenity", features = ["collector", "unstable_discord_api"] }
serenity = { git = "https://github.com/serenity-rs/serenity", branch = "next", features = ["collector", "unstable_discord_api"] }
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "macros", "mysql", "bigdecimal", "chrono"]}
ring = "0.16"
base64 = "0.13.0"
[dependencies.regex_command_attr]
path = "./regex_command_attr"

View File

@ -35,7 +35,7 @@ async fn ping(ctx: &Context, msg: &Message, _args: String) {
}
async fn footer(ctx: &Context) -> impl FnOnce(&mut CreateEmbedFooter) -> &mut CreateEmbedFooter {
let shard_count = ctx.cache.shard_count().await;
let shard_count = ctx.cache.shard_count();
let shard = ctx.shard_id;
move |f| {
@ -145,7 +145,7 @@ async fn info(ctx: &Context, msg: &Message, _args: String) {
let desc = lm
.get(&language.await, "info")
.replacen("{user}", &current_user.await.name, 1)
.replacen("{user}", &current_user.name, 1)
.replace("{default_prefix}", &*DEFAULT_PREFIX)
.replace("{prefix}", &prefix.await);

View File

@ -7,7 +7,7 @@ use serenity::{
model::{
channel::Message,
id::{ChannelId, MessageId, RoleId},
interactions::ButtonStyle,
interactions::message_component::ButtonStyle,
},
};
@ -46,13 +46,11 @@ async fn blacklist(ctx: &Context, msg: &Message, args: String) {
let (channel, local) = match capture_opt {
Some(capture) => (
ChannelId(capture.as_str().parse::<u64>().unwrap())
.to_channel_cached(&ctx)
.await,
ChannelId(capture.as_str().parse::<u64>().unwrap()).to_channel_cached(&ctx),
false,
),
None => (msg.channel(&ctx).await, true),
None => (msg.channel(&ctx).await.ok(), true),
};
let mut channel_data = ChannelData::from_channel(channel.unwrap(), &pool)
@ -394,7 +392,7 @@ async fn restrict(ctx: &Context, msg: &Message, args: String) {
let (pool, lm) = get_ctx_data(&ctx).await;
let language = UserData::language_of(&msg.author, &pool).await;
let guild_data = GuildData::from_guild(msg.guild(&ctx).await.unwrap(), &pool)
let guild_data = GuildData::from_guild(msg.guild(&ctx).unwrap(), &pool)
.await
.unwrap();
@ -411,7 +409,7 @@ async fn restrict(ctx: &Context, msg: &Message, args: String) {
.unwrap(),
);
let role_opt = role_id.to_role_cached(&ctx).await;
let role_opt = role_id.to_role_cached(&ctx);
if let Some(role) = role_opt {
let _ = sqlx::query!(
@ -624,7 +622,7 @@ SELECT command FROM command_aliases WHERE guild_id = (SELECT id FROM guilds WHER
.get::<FrameworkCtx>().cloned().expect("Could not get FrameworkCtx from data");
let mut new_msg = msg.clone();
new_msg.content = format!("<@{}> {}", &ctx.cache.current_user_id().await, row.command);
new_msg.content = format!("<@{}> {}", &ctx.cache.current_user_id(), row.command);
new_msg.id = MessageId(0);
framework.dispatch(ctx.clone(), new_msg).await;

View File

@ -8,7 +8,6 @@ use serenity::{
channel::{Channel, GuildChannel},
guild::Guild,
id::{ChannelId, GuildId, UserId},
interactions::ButtonStyle,
misc::Mentionable,
webhook::Webhook,
},
@ -26,7 +25,7 @@ use crate::{
models::{
channel_data::ChannelData,
guild_data::GuildData,
reminder::{LookFlags, Reminder, ReminderAction},
reminder::{LookFlags, Reminder},
timer::Timer,
user_data::UserData,
CtxGuildData,
@ -153,7 +152,7 @@ async fn offset(ctx: &Context, msg: &Message, args: String) {
let parser = TimeParser::new(&args, user_data.timezone());
if let Ok(displacement) = parser.displacement() {
if let Some(guild) = msg.guild(&ctx).await {
if let Some(guild) = msg.guild(&ctx) {
let guild_data = GuildData::from_guild(guild, &pool).await.unwrap();
sqlx::query!(
@ -162,7 +161,7 @@ UPDATE reminders
INNER JOIN `channels`
ON `channels`.id = reminders.channel_id
SET
reminders.`utc_time` = reminders.`utc_time` + ?
reminders.`utc_time` = DATE_ADD(reminders.`utc_time`, INTERVAL ? SECOND)
WHERE channels.guild_id = ?
",
displacement,
@ -174,7 +173,7 @@ UPDATE reminders
} else {
sqlx::query!(
"
UPDATE reminders SET `utc_time` = `utc_time` + ? WHERE reminders.channel_id = ?
UPDATE reminders SET `utc_time` = DATE_ADD(`utc_time`, INTERVAL ? SECOND) WHERE reminders.channel_id = ?
",
displacement,
user_data.dm_channel
@ -263,7 +262,7 @@ async fn look(ctx: &Context, msg: &Message, args: String) {
let flags = LookFlags::from_string(&args);
let channel_opt = msg.channel_id.to_channel_cached(&ctx).await;
let channel_opt = msg.channel_id.to_channel_cached(&ctx);
let channel_id = if let Some(Channel::Guild(channel)) = channel_opt {
if Some(channel.guild_id) == msg.guild_id {
@ -1028,22 +1027,6 @@ async fn remind_command(ctx: &Context, msg: &Message, args: String, command: Rem
.description(format!("{}\n\n{}", success_part, error_part))
.color(*THEME_COLOR)
})
.components(|c| {
if ok_locations.len() == 1 {
c.create_action_row(|r| {
r.create_button(|b| {
b.style(ButtonStyle::Danger)
.label("Delete")
.custom_id(ok_reminders[0].signed_action(
msg.author.id,
ReminderAction::Delete,
))
})
});
}
c
})
})
.await;
}
@ -1321,7 +1304,7 @@ async fn create_reminder<'a, U: Into<u64>, T: TryInto<i64>>(
let user_id = user_id.into();
if let Some(g_id) = guild_id {
if let Some(guild) = g_id.to_guild_cached(&ctx).await {
if let Some(guild) = g_id.to_guild_cached(&ctx) {
content.substitute(guild);
}
}

View File

@ -312,10 +312,10 @@ impl Framework for RegexFramework {
guild: &Guild,
channel: &GuildChannel,
) -> SerenityResult<PermissionCheck> {
let user_id = ctx.cache.current_user_id().await;
let user_id = ctx.cache.current_user_id();
let guild_perms = guild.member_permissions(&ctx, user_id).await?;
let channel_perms = channel.permissions_for_user(ctx, user_id).await?;
let channel_perms = channel.permissions_for_user(ctx, user_id)?;
let basic_perms = channel_perms.send_messages();
@ -347,8 +347,8 @@ impl Framework for RegexFramework {
if (msg.author.bot && self.ignore_bots) || msg.content.is_empty() {
} else {
// Guild Command
if let (Some(guild), Some(Channel::Guild(channel))) =
(msg.guild(&ctx).await, msg.channel(&ctx).await)
if let (Some(guild), Ok(Channel::Guild(channel))) =
(msg.guild(&ctx), msg.channel(&ctx).await)
{
let data = ctx.data.read().await;

View File

@ -19,7 +19,7 @@ use serenity::{
channel::Message,
guild::{Guild, GuildUnavailable},
id::{GuildId, UserId},
interactions::{Interaction, InteractionData, InteractionType},
interactions::Interaction,
},
prelude::{Context, EventHandler, TypeMapKey},
utils::shard_id,
@ -46,7 +46,6 @@ use dashmap::DashMap;
use tokio::sync::RwLock;
use crate::models::reminder::{Reminder, ReminderAction};
use chrono::Utc;
use chrono_tz::Tz;
use serenity::model::prelude::{
@ -187,13 +186,12 @@ DELETE FROM channels WHERE channel = ?
}
if let Ok(token) = env::var("DISCORDBOTS_TOKEN") {
let shard_count = ctx.cache.shard_count().await;
let shard_count = ctx.cache.shard_count();
let current_shard_id = shard_id(guild_id, shard_count);
let guild_count = ctx
.cache
.guilds()
.await
.iter()
.filter(|g| shard_id(g.as_u64().to_owned(), shard_count) == current_shard_id)
.count() as u64;
@ -215,7 +213,7 @@ DELETE FROM channels WHERE channel = ?
.post(
format!(
"https://top.gg/api/bots/{}/stats",
ctx.cache.current_user_id().await.as_u64()
ctx.cache.current_user_id().as_u64()
)
.as_str(),
)
@ -268,12 +266,11 @@ DELETE FROM guilds WHERE guild = ?
async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
let (pool, lm) = get_ctx_data(&&ctx).await;
match interaction.kind {
InteractionType::ApplicationCommand => {}
InteractionType::MessageComponent => {
if let (Some(InteractionData::MessageComponent(data)), Some(member)) =
(interaction.clone().data, interaction.clone().member)
{
match interaction {
Interaction::MessageComponent(interaction) => {
if let Some(member) = interaction.clone().member {
let data = interaction.data.clone();
if data.custom_id.starts_with("timezone:") {
let mut user_data = UserData::from_user(&member.user, &ctx, &pool)
.await
@ -342,40 +339,6 @@ DELETE FROM guilds WHERE guild = ?
})
.await;
}
} else {
match Reminder::from_interaction(&ctx, member.user.id, data.custom_id).await
{
Ok((reminder, action)) => {
let response = match action {
ReminderAction::Delete => {
reminder.delete(&ctx).await;
"Reminder has been deleted"
}
};
let _ = interaction
.create_interaction_response(&ctx, |r| {
r.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|d| d
.content(response)
.flags(InteractionApplicationCommandCallbackDataFlags::EPHEMERAL)
)
})
.await;
}
Err(ie) => {
let _ = interaction
.create_interaction_response(&ctx, |r| {
r.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|d| d
.content(ie.to_string())
.flags(InteractionApplicationCommandCallbackDataFlags::EPHEMERAL)
)
})
.await;
}
}
}
}
}
@ -574,7 +537,7 @@ pub async fn check_subscription_on_message(
msg: &Message,
) -> bool {
check_subscription(&cache_http, &msg.author).await
|| if let Some(guild) = msg.guild(&cache_http).await {
|| if let Some(guild) = msg.guild(&cache_http) {
check_subscription(&cache_http, guild.owner_id).await
} else {
false

View File

@ -31,7 +31,7 @@ impl CtxGuildData for Context {
) -> Result<Arc<RwLock<GuildData>>, sqlx::Error> {
let guild_id = guild_id.into();
let guild = guild_id.to_guild_cached(&self.cache).await.unwrap();
let guild = guild_id.to_guild_cached(&self.cache).unwrap();
let guild_cache = self
.data

View File

@ -11,9 +11,6 @@ use crate::{
};
use num_integer::Integer;
use ring::hmac;
use std::convert::{TryFrom, TryInto};
use std::env;
fn longhand_displacement(seconds: u64) -> String {
let (days, seconds) = seconds.div_rem(&DAY);
@ -86,43 +83,6 @@ WHERE
.ok()
}
pub async fn from_id(ctx: &Context, id: u32) -> Option<Self> {
let pool = ctx.data.read().await.get::<SQLPool>().cloned().unwrap();
sqlx::query_as_unchecked!(
Self,
"
SELECT
reminders.id,
reminders.uid,
channels.channel,
reminders.utc_time,
reminders.interval,
reminders.expires,
reminders.enabled,
reminders.content,
reminders.embed_description,
users.user AS set_by
FROM
reminders
INNER JOIN
channels
ON
reminders.channel_id = channels.id
LEFT JOIN
users
ON
reminders.set_by = users.id
WHERE
reminders.id = ?
",
id
)
.fetch_one(&pool)
.await
.ok()
}
pub async fn from_channel<C: Into<ChannelId>>(
ctx: &Context,
channel_id: C,
@ -178,7 +138,7 @@ LIMIT
let pool = ctx.data.read().await.get::<SQLPool>().cloned().unwrap();
if let Some(guild_id) = guild_id {
let guild_opt = guild_id.to_guild_cached(&ctx).await;
let guild_opt = guild_id.to_guild_cached(&ctx);
if let Some(guild) = guild_opt {
let channels = guild
@ -327,127 +287,6 @@ WHERE
)
}
}
pub async fn from_interaction<U: Into<u64>>(
ctx: &Context,
member_id: U,
payload: String,
) -> Result<(Self, ReminderAction), InteractionError> {
let sections = payload.split(".").collect::<Vec<&str>>();
if sections.len() != 3 {
Err(InteractionError::InvalidFormat)
} else {
let action = ReminderAction::try_from(sections[0])
.map_err(|_| InteractionError::InvalidAction)?;
let reminder_id = u32::from_le_bytes(
base64::decode(sections[1])
.map_err(|_| InteractionError::InvalidBase64)?
.try_into()
.map_err(|_| InteractionError::InvalidSize)?,
);
if let Some(reminder) = Self::from_id(ctx, reminder_id).await {
if reminder.signed_action(member_id, action) == payload {
Ok((reminder, action))
} else {
Err(InteractionError::SignatureMismatch)
}
} else {
Err(InteractionError::NoReminder)
}
}
}
pub fn signed_action<U: Into<u64>>(&self, member_id: U, action: ReminderAction) -> String {
let s_key = hmac::Key::new(
hmac::HMAC_SHA256,
env::var("SECRET_KEY")
.expect("No SECRET_KEY provided")
.as_bytes(),
);
let mut context = hmac::Context::with_key(&s_key);
context.update(&self.id.to_le_bytes());
context.update(&member_id.into().to_le_bytes());
let signature = context.sign();
format!(
"{}.{}.{}",
action.to_string(),
base64::encode(self.id.to_le_bytes()),
base64::encode(&signature)
)
}
pub async fn delete(&self, ctx: &Context) {
let pool = ctx.data.read().await.get::<SQLPool>().cloned().unwrap();
sqlx::query!(
"
DELETE FROM reminders WHERE id = ?
",
self.id
)
.execute(&pool)
.await
.unwrap();
}
}
#[derive(Debug)]
pub enum InteractionError {
InvalidFormat,
InvalidBase64,
InvalidSize,
NoReminder,
SignatureMismatch,
InvalidAction,
}
impl ToString for InteractionError {
fn to_string(&self) -> String {
match self {
InteractionError::InvalidFormat => {
String::from("The interaction data was improperly formatted")
}
InteractionError::InvalidBase64 => String::from("The interaction data was invalid"),
InteractionError::InvalidSize => String::from("The interaction data was invalid"),
InteractionError::NoReminder => String::from("Reminder could not be found"),
InteractionError::SignatureMismatch => {
String::from("Only the user who did the command can use interactions")
}
InteractionError::InvalidAction => String::from("The action was invalid"),
}
}
}
#[derive(Clone, Copy)]
pub enum ReminderAction {
Delete,
}
impl ToString for ReminderAction {
fn to_string(&self) -> String {
match self {
Self::Delete => String::from("del"),
}
}
}
impl TryFrom<&str> for ReminderAction {
type Error = ();
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"del" => Ok(Self::Delete),
_ => Err(()),
}
}
}
enum TimeDisplayType {