Compare commits

...

6 Commits

Author SHA1 Message Date
jude
1007b75069 downgrade some stuff 2022-05-13 14:38:36 +01:00
jude
0e7a4d02de ? 2022-05-13 14:21:34 +01:00
jude
37e5c50800 added message content intent 2022-05-13 14:11:39 +01:00
jude
88255032de update for new database models 2022-05-13 10:03:45 +01:00
b88d046846 block mentions in todo command 2021-11-15 07:55:37 +00:00
f9c110ffb7 removed unreleased code. fixed offset command 2021-11-07 23:36:07 +00:00
10 changed files with 703 additions and 868 deletions

1247
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/jellywx/serenity", branch = "jellywx-attachment_option", 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,10 +8,9 @@ use serenity::{
channel::{Channel, GuildChannel},
guild::Guild,
id::{ChannelId, GuildId, UserId},
interactions::ButtonStyle,
misc::Mentionable,
webhook::Webhook,
},
prelude::Mentionable,
Result as SerenityResult,
};
@ -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 {
@ -771,7 +770,7 @@ INSERT INTO reminders (
`embed_color`,
`channel_id`,
`utc_time`,
`interval`,
`interval_seconds`,
`set_by`,
`expires`
) VALUES (
@ -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);
}
}
@ -1410,7 +1393,7 @@ INSERT INTO reminders (
channel_id,
`utc_time`,
expires,
`interval`,
`interval_seconds`,
set_by
) VALUES (
?,

View File

@ -274,7 +274,12 @@ DELETE FROM todos WHERE user_id = (SELECT id FROM users WHERE user = ?) AND guil
self.add(extra, pool).await.unwrap();
let _ = msg.channel_id.say(&ctx, content).await;
let _ = msg
.channel_id
.send_message(&ctx, |m| {
m.content(content).allowed_mentions(|m| m.empty_parse())
})
.await;
}
SubCommand::Remove => {
@ -286,7 +291,12 @@ DELETE FROM todos WHERE user_id = (SELECT id FROM users WHERE user = ?) AND guil
1,
);
let _ = msg.channel_id.say(&ctx, content).await;
let _ = msg
.channel_id
.send_message(&ctx, |m| {
m.content(content).allowed_mentions(|m| m.empty_parse())
})
.await;
} else {
let _ = msg
.channel_id

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

@ -11,15 +11,15 @@ mod time_parser;
use serenity::{
async_trait,
cache::Cache,
client::{bridge::gateway::GatewayIntents, Client},
client::Client,
futures::TryFutureExt,
http::{client::Http, CacheHttp},
model::{
channel::GuildChannel,
channel::Message,
guild::{Guild, GuildUnavailable},
guild::Guild,
id::{GuildId, UserId},
interactions::{Interaction, InteractionData, InteractionType},
interactions::Interaction,
},
prelude::{Context, EventHandler, TypeMapKey},
utils::shard_id,
@ -46,9 +46,10 @@ use dashmap::DashMap;
use tokio::sync::RwLock;
use crate::models::reminder::{Reminder, ReminderAction};
use chrono::Utc;
use chrono_tz::Tz;
use serenity::model::gateway::GatewayIntents;
use serenity::model::guild::UnavailableGuild;
use serenity::model::prelude::{
InteractionApplicationCommandCallbackDataFlags, InteractionResponseType,
};
@ -187,13 +188,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 +215,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(),
)
@ -234,7 +234,7 @@ DELETE FROM channels WHERE channel = ?
async fn guild_delete(
&self,
ctx: Context,
deleted_guild: GuildUnavailable,
deleted_guild: UnavailableGuild,
_guild: Option<Guild>,
) {
let pool = ctx
@ -268,12 +268,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 +341,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 +539,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);
@ -40,7 +37,7 @@ pub struct Reminder {
pub uid: String,
pub channel: u64,
pub utc_time: NaiveDateTime,
pub interval: Option<u32>,
pub interval_seconds: Option<u32>,
pub expires: Option<NaiveDateTime>,
pub enabled: bool,
pub content: String,
@ -60,7 +57,7 @@ SELECT
reminders.uid,
channels.channel,
reminders.utc_time,
reminders.interval,
reminders.interval_seconds,
reminders.expires,
reminders.enabled,
reminders.content,
@ -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,
@ -141,7 +101,7 @@ SELECT
reminders.uid,
channels.channel,
reminders.utc_time,
reminders.interval,
reminders.interval_seconds,
reminders.expires,
reminders.enabled,
reminders.content,
@ -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
@ -197,7 +157,7 @@ SELECT
reminders.uid,
channels.channel,
reminders.utc_time,
reminders.interval,
reminders.interval_seconds,
reminders.expires,
reminders.enabled,
reminders.content,
@ -229,7 +189,7 @@ SELECT
reminders.uid,
channels.channel,
reminders.utc_time,
reminders.interval,
reminders.interval_seconds,
reminders.expires,
reminders.enabled,
reminders.content,
@ -262,7 +222,7 @@ SELECT
reminders.uid,
channels.channel,
reminders.utc_time,
reminders.interval,
reminders.interval_seconds,
reminders.expires,
reminders.enabled,
reminders.content,
@ -304,7 +264,7 @@ WHERE
TimeDisplayType::Relative => format!("<t:{}:R>", self.utc_time.timestamp()),
};
if let Some(interval) = self.interval {
if let Some(interval) = self.interval_seconds {
format!(
"'{}' *{}* **{}**, repeating every **{}** (set by {})",
self.display_content(),
@ -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 {