28 Commits

Author SHA1 Message Date
b0a04bb289 Default channel command 2022-09-17 18:09:40 +01:00
eef1f6f3e8 Correct migration. Add guilds on interaction. Correct queries 2022-09-17 18:08:45 +01:00
3d08027325 Add migration for guild IDs to use discord ID 2022-09-17 18:08:45 +01:00
94bfd39085 Patch compilation against live schema 2022-09-17 13:05:50 +01:00
40cd5f8a36 Patch compilation against live schema 2022-09-17 13:03:52 +01:00
133b00a2ce Patch compilation against live schema 2022-09-17 12:52:03 +01:00
57336f5c81 Change macro list to use fields to prevent going over limit
Add length checks for name and description
2022-09-17 12:37:58 +01:00
b62d24c024 Add an autocomplete for time hints
Shows the approximate time until a reminder will send in the autocomplete area.
2022-09-12 17:49:10 +01:00
8f8235a86e Move macro commands to own module
Lots of code here
2022-09-12 16:45:00 +01:00
c8f646a8fa Override timezone per command
Timezone option that will override the timezone on a per-command basis
2022-09-11 18:59:46 +01:00
ecaa382a1e Add join message 2022-09-11 17:38:53 +01:00
8991198fd3 Use autocomplete to ensure content box is shown 2022-09-11 15:24:02 +01:00
f20b95a482 Upgrade poise. Combine remind/multiline into one command 2022-09-08 17:58:05 +01:00
8dd7dc6409 Added command for multiline reminders 2022-09-07 18:27:13 +01:00
c799d10727 Move extra processes to user data setup 2022-09-03 16:19:59 +01:00
ceb6fb7b12 bump version 2022-09-03 15:49:05 +01:00
6708abdb0f Merge pull request #10 from reminder-bot/jellywx/fix-dm-reminders
group by channel instead of guild
2022-09-03 15:44:00 +01:00
a38f6024c1 Migrate natural commands 2022-09-03 15:40:29 +01:00
7d8748e3ef group by channel instead of guild 2022-08-19 09:04:12 +01:00
bb3386c4e8 migration for $r commands 2022-08-14 16:22:00 +01:00
25b84880a5 Don't send non-interval disabled reminders
Skip the sending logic as some users use disabled one-time reminders as presets
2022-08-04 19:06:29 +01:00
7b6e967a5d Block/allow DM reminders
Only affects slash commands but this is sort of a non-issue post September
2022-07-29 19:22:15 +01:00
2781f2923e Restrict reminder selection to one-per-guild during fetch loop 2022-07-28 19:20:15 +01:00
03f08f0a18 Update deps. Drop limiter on reminder query 2022-07-27 21:42:09 +01:00
79c86d43f2 Changed return types to results 2022-07-24 20:06:37 +01:00
e19af54caf Import todo lists. Export other data. 2022-07-22 23:30:45 +01:00
f4213c6a83 Cache channel in todo list command
Channel was not being cached, placing channel todos into the server todo list.
2022-07-02 08:31:17 +01:00
f56db14720 Webhook command
Add a command to view the webhook, as some users wish to use the webhook to edit past reminders.
2022-06-17 17:15:48 +01:00
54 changed files with 2876 additions and 1499 deletions

1240
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,29 +1,30 @@
[package] [package]
name = "reminder_rs" name = "reminder_rs"
version = "1.6.0" version = "1.6.6"
authors = ["jellywx <judesouthworth@pm.me>"] authors = ["jellywx <judesouthworth@pm.me>"]
edition = "2018" edition = "2018"
[dependencies] [dependencies]
poise = "0.2" poise = "0.3"
dotenv = "0.15" dotenv = "0.15"
tokio = { version = "1", features = ["process", "full"] } tokio = { version = "1", features = ["process", "full"] }
reqwest = "0.11" reqwest = "0.11"
regex = "1.4" lazy-regex = "2.3.0"
regex = "1.6"
log = "0.4" log = "0.4"
env_logger = "0.8" env_logger = "0.9"
chrono = "0.4" chrono = "0.4"
chrono-tz = { version = "0.5", features = ["serde"] } chrono-tz = { version = "0.6", features = ["serde"] }
lazy_static = "1.4" lazy_static = "1.4"
num-integer = "0.1" num-integer = "0.1"
serde = "1.0" serde = "1.0"
serde_json = "1.0" serde_json = "1.0"
serde_repr = "0.1" serde_repr = "0.1"
rmp-serde = "0.15" rmp-serde = "1.1"
rand = "0.7" rand = "0.8"
levenshtein = "1.0" levenshtein = "1.0"
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "macros", "mysql", "bigdecimal", "chrono"]} sqlx = { version = "0.6", features = ["runtime-tokio-rustls", "macros", "mysql", "bigdecimal", "chrono"]}
base64 = "0.13.0" base64 = "0.13"
[dependencies.postman] [dependencies.postman]
path = "postman" path = "postman"

View File

@ -157,4 +157,9 @@ CREATE TABLE events (
FOREIGN KEY (reminder_id) REFERENCES reminders_new(id) ON DELETE SET NULL FOREIGN KEY (reminder_id) REFERENCES reminders_new(id) ON DELETE SET NULL
); );
DROP TABLE reminders;
DROP TABLE embed_fields;
RENAME TABLE reminders_new TO reminders;
RENAME TABLE embed_fields_new TO embed_fields;
SET FOREIGN_KEY_CHECKS = 1; SET FOREIGN_KEY_CHECKS = 1;

View File

@ -0,0 +1,92 @@
SET foreign_key_checks = 0;
START TRANSACTION;
-- drop existing constraints
ALTER TABLE channels DROP FOREIGN KEY `channels_ibfk_1`;
ALTER TABLE command_aliases DROP FOREIGN KEY `command_aliases_ibfk_1`;
ALTER TABLE events DROP FOREIGN KEY `events_ibfk_1`;
ALTER TABLE guild_users DROP FOREIGN KEY `guild_users_ibfk_1`;
ALTER TABLE macro DROP FOREIGN KEY `macro_ibfk_1`;
ALTER TABLE roles DROP FOREIGN KEY `roles_ibfk_1`;
ALTER TABLE todos DROP FOREIGN KEY `todos_ibfk_2`;
ALTER TABLE reminder_template DROP FOREIGN KEY `reminder_template_ibfk_1`;
-- update foreign key types
ALTER TABLE channels MODIFY `guild_id` BIGINT UNSIGNED;
ALTER TABLE command_aliases MODIFY `guild_id` BIGINT UNSIGNED;
ALTER TABLE events MODIFY `guild_id` BIGINT UNSIGNED;
ALTER TABLE guild_users MODIFY `guild` BIGINT UNSIGNED;
ALTER TABLE macro MODIFY `guild_id` BIGINT UNSIGNED;
ALTER TABLE roles MODIFY `guild_id` BIGINT UNSIGNED;
ALTER TABLE todos MODIFY `guild_id` BIGINT UNSIGNED;
ALTER TABLE reminder_template MODIFY `guild_id` BIGINT UNSIGNED;
-- update foreign key values
UPDATE channels SET `guild_id` = (SELECT `guild` FROM guilds WHERE guilds.`id` = `guild_id`);
UPDATE command_aliases SET `guild_id` = (SELECT `guild` FROM guilds WHERE guilds.`id` = `guild_id`);
UPDATE events SET `guild_id` = (SELECT `guild` FROM guilds WHERE guilds.`id` = `guild_id`);
UPDATE guild_users SET `guild` = (SELECT `guild` FROM guilds WHERE guilds.`id` = guild_users.`guild`);
UPDATE macro SET `guild_id` = (SELECT `guild` FROM guilds WHERE guilds.`id` = `guild_id`);
UPDATE roles SET `guild_id` = (SELECT `guild` FROM guilds WHERE guilds.`id` = `guild_id`);
UPDATE todos SET `guild_id` = (SELECT `guild` FROM guilds WHERE guilds.`id` = `guild_id`);
UPDATE reminder_template SET `guild_id` = (SELECT `guild` FROM guilds WHERE guilds.`id` = `guild_id`);
-- update guilds table
ALTER TABLE guilds MODIFY `id` BIGINT UNSIGNED NOT NULL;
UPDATE guilds SET `id` = `guild`;
ALTER TABLE guilds DROP COLUMN `guild`;
ALTER TABLE guilds ADD COLUMN `default_channel` BIGINT UNSIGNED;
ALTER TABLE guilds ADD CONSTRAINT `default_channel_fk`
FOREIGN KEY (`default_channel`)
REFERENCES channels(`channel`)
ON DELETE SET NULL
ON UPDATE CASCADE;
-- re-add constraints
ALTER TABLE channels ADD CONSTRAINT
FOREIGN KEY (`guild_id`)
REFERENCES guilds(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE command_aliases ADD CONSTRAINT
FOREIGN KEY (`guild_id`)
REFERENCES guilds(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE events ADD CONSTRAINT
FOREIGN KEY (`guild_id`)
REFERENCES guilds(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE guild_users ADD CONSTRAINT
FOREIGN KEY (`guild`)
REFERENCES guilds(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE macro ADD CONSTRAINT
FOREIGN KEY (`guild_id`)
REFERENCES guilds(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE roles ADD CONSTRAINT
FOREIGN KEY (`guild_id`)
REFERENCES guilds(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE todos ADD CONSTRAINT
FOREIGN KEY (`guild_id`)
REFERENCES guilds(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
COMMIT;
SET foreign_key_checks = 1;

View File

@ -7,12 +7,10 @@ edition = "2021"
tokio = { version = "1", features = ["process", "full"] } tokio = { version = "1", features = ["process", "full"] }
regex = "1.4" regex = "1.4"
log = "0.4" log = "0.4"
env_logger = "0.8"
chrono = "0.4" chrono = "0.4"
chrono-tz = { version = "0.5", features = ["serde"] } chrono-tz = { version = "0.5", features = ["serde"] }
lazy_static = "1.4" lazy_static = "1.4"
num-integer = "0.1" num-integer = "0.1"
serde = "1.0" serde = "1.0"
serde_json = "1.0" sqlx = { version = "0.6", features = ["runtime-tokio-rustls", "macros", "mysql", "bigdecimal", "chrono", "json"]}
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "macros", "mysql", "bigdecimal", "chrono", "json"]}
serenity = { version = "0.11.1", default-features = false, features = ["builder", "cache", "client", "gateway", "http", "model", "utils", "rustls_backend"] } serenity = { version = "0.11.1", default-features = false, features = ["builder", "cache", "client", "gateway", "http", "model", "utils", "rustls_backend"] }

View File

@ -226,7 +226,6 @@ impl Into<CreateEmbed> for Embed {
} }
} }
#[derive(Debug)]
pub struct Reminder { pub struct Reminder {
id: u32, id: u32,
@ -293,8 +292,20 @@ INNER JOIN
ON ON
reminders.channel_id = channels.id reminders.channel_id = channels.id
WHERE WHERE
reminders.`utc_time` < NOW() reminders.`id` IN (
LIMIT 25 SELECT
MIN(id)
FROM
reminders
WHERE
reminders.`utc_time` <= NOW()
AND (
reminders.`interval_seconds` IS NOT NULL
OR reminders.`interval_months` IS NOT NULL
OR reminders.enabled
)
GROUP BY channel_id
)
"#, "#,
) )
.fetch_all(pool) .fetch_all(pool)
@ -566,7 +577,7 @@ UPDATE `channels` SET paused = 0, paused_until = NULL WHERE `channel` = ?
}; };
if let Err(e) = result { if let Err(e) = result {
error!("Error sending {:?}: {:?}", self, e); error!("Error sending reminder {}: {:?}", self.id, e);
if let Error::Http(error) = e { if let Error::Http(error) = e {
if error.status_code() == Some(StatusCode::NOT_FOUND) { if error.status_code() == Some(StatusCode::NOT_FOUND) {

View File

@ -0,0 +1,131 @@
use std::time::{SystemTime, UNIX_EPOCH};
use chrono_tz::TZ_VARIANTS;
use poise::AutocompleteChoice;
use crate::{models::CtxData, time_parser::natural_parser, Context};
pub async fn timezone_autocomplete(ctx: Context<'_>, partial: &str) -> Vec<String> {
if partial.is_empty() {
ctx.data().popular_timezones.iter().map(|t| t.to_string()).collect::<Vec<String>>()
} else {
TZ_VARIANTS
.iter()
.filter(|tz| tz.to_string().contains(&partial))
.take(25)
.map(|t| t.to_string())
.collect::<Vec<String>>()
}
}
pub async fn macro_name_autocomplete(ctx: Context<'_>, partial: &str) -> Vec<String> {
sqlx::query!(
"
SELECT name
FROM macro
WHERE
guild_id = ?
AND name LIKE CONCAT(?, '%')",
ctx.guild_id().unwrap().0,
partial,
)
.fetch_all(&ctx.data().database)
.await
.unwrap_or_default()
.iter()
.map(|s| s.name.clone())
.collect()
}
pub async fn multiline_autocomplete(
_ctx: Context<'_>,
partial: &str,
) -> Vec<AutocompleteChoice<String>> {
if partial.is_empty() {
vec![AutocompleteChoice { name: "Multiline content...".to_string(), value: "".to_string() }]
} else {
vec![
AutocompleteChoice { name: partial.to_string(), value: partial.to_string() },
AutocompleteChoice { name: "Multiline content...".to_string(), value: "".to_string() },
]
}
}
pub async fn time_hint_autocomplete(
ctx: Context<'_>,
partial: &str,
) -> Vec<AutocompleteChoice<String>> {
if partial.is_empty() {
vec![AutocompleteChoice {
name: "Start typing a time...".to_string(),
value: "now".to_string(),
}]
} else {
match natural_parser(partial, &ctx.timezone().await.to_string()).await {
Some(timestamp) => match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(now) => {
let diff = timestamp - now.as_secs() as i64;
if diff < 0 {
vec![AutocompleteChoice {
name: "Time is in the past".to_string(),
value: "now".to_string(),
}]
} else {
if diff > 86400 {
vec![
AutocompleteChoice {
name: partial.to_string(),
value: partial.to_string(),
},
AutocompleteChoice {
name: format!(
"In approximately {} days, {} hours",
diff / 86400,
(diff % 86400) / 3600
),
value: partial.to_string(),
},
]
} else if diff > 3600 {
vec![
AutocompleteChoice {
name: partial.to_string(),
value: partial.to_string(),
},
AutocompleteChoice {
name: format!("In approximately {} hours", diff / 3600),
value: partial.to_string(),
},
]
} else {
vec![
AutocompleteChoice {
name: partial.to_string(),
value: partial.to_string(),
},
AutocompleteChoice {
name: format!("In approximately {} minutes", diff / 60),
value: partial.to_string(),
},
]
}
}
}
Err(_) => {
vec![AutocompleteChoice {
name: partial.to_string(),
value: partial.to_string(),
}]
}
},
None => {
vec![AutocompleteChoice {
name: "Time not recognised".to_string(),
value: "now".to_string(),
}]
}
}
}
}

View File

@ -0,0 +1,46 @@
use super::super::autocomplete::macro_name_autocomplete;
use crate::{Context, Error};
/// Delete a recorded macro
#[poise::command(
slash_command,
rename = "delete",
guild_only = true,
default_member_permissions = "MANAGE_GUILD",
identifying_name = "delete_macro"
)]
pub async fn delete_macro(
ctx: Context<'_>,
#[description = "Name of macro to delete"]
#[autocomplete = "macro_name_autocomplete"]
name: String,
) -> Result<(), Error> {
match sqlx::query!(
"
SELECT id FROM macro WHERE guild_id = ? AND name = ?",
ctx.guild_id().unwrap().0,
name
)
.fetch_one(&ctx.data().database)
.await
{
Ok(row) => {
sqlx::query!("DELETE FROM macro WHERE id = ?", row.id)
.execute(&ctx.data().database)
.await
.unwrap();
ctx.say(format!("Macro \"{}\" deleted", name)).await?;
}
Err(sqlx::Error::RowNotFound) => {
ctx.say(format!("Macro \"{}\" not found", name)).await?;
}
Err(e) => {
panic!("{}", e);
}
}
Ok(())
}

View File

@ -0,0 +1,89 @@
use poise::CreateReply;
use crate::{
component_models::pager::{MacroPager, Pager},
consts::THEME_COLOR,
models::{command_macro::CommandMacro, CtxData},
Context, Error,
};
/// List recorded macros
#[poise::command(
slash_command,
rename = "list",
guild_only = true,
default_member_permissions = "MANAGE_GUILD",
identifying_name = "list_macro"
)]
pub async fn list_macro(ctx: Context<'_>) -> Result<(), Error> {
let macros = ctx.command_macros().await?;
let resp = show_macro_page(&macros, 0);
ctx.send(|m| {
*m = resp;
m
})
.await?;
Ok(())
}
pub fn max_macro_page<U, E>(macros: &[CommandMacro<U, E>]) -> usize {
((macros.len() as f64) / 25.0).ceil() as usize
}
pub fn show_macro_page<U, E>(macros: &[CommandMacro<U, E>], page: usize) -> CreateReply {
let pager = MacroPager::new(page);
if macros.is_empty() {
let mut reply = CreateReply::default();
reply.embed(|e| {
e.title("Macros")
.description("No Macros Set Up. Use `/macro record` to get started.")
.color(*THEME_COLOR)
});
return reply;
}
let pages = max_macro_page(macros);
let mut page = page;
if page >= pages {
page = pages - 1;
}
let lower = (page * 25).min(macros.len());
let upper = ((page + 1) * 25).min(macros.len());
let fields = macros[lower..upper].iter().map(|m| {
if let Some(description) = &m.description {
(
m.name.clone(),
format!("*{}*\n- Has {} commands", description, m.commands.len()),
true,
)
} else {
(m.name.clone(), format!("- Has {} commands", m.commands.len()), true)
}
});
let mut reply = CreateReply::default();
reply
.embed(|e| {
e.title("Macros")
.fields(fields)
.footer(|f| f.text(format!("Page {} of {}", page + 1, pages)))
.color(*THEME_COLOR)
})
.components(|comp| {
pager.create_button_row(pages, comp);
comp
});
reply
}

View File

@ -0,0 +1,229 @@
use lazy_regex::regex;
use poise::serenity_prelude::command::CommandOptionType;
use regex::Captures;
use serde_json::{json, Value};
use crate::{models::command_macro::RawCommandMacro, Context, Error, GuildId};
struct Alias {
name: String,
command: String,
}
/// Migrate old $alias reminder commands to macros. Only macro names that are not taken will be used.
#[poise::command(
slash_command,
rename = "migrate",
guild_only = true,
default_member_permissions = "MANAGE_GUILD",
identifying_name = "migrate_macro"
)]
pub async fn migrate_macro(ctx: Context<'_>) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap();
let mut transaction = ctx.data().database.begin().await?;
let aliases = sqlx::query_as!(
Alias,
"SELECT name, command FROM command_aliases WHERE guild_id = ?",
guild_id.0
)
.fetch_all(&mut transaction)
.await?;
let mut added_aliases = 0;
for alias in aliases {
match parse_text_command(guild_id, alias.name, &alias.command) {
Some(cmd_macro) => {
sqlx::query!(
"INSERT INTO macro (guild_id, name, description, commands) VALUES (?, ?, ?, ?)",
cmd_macro.guild_id.0,
cmd_macro.name,
cmd_macro.description,
cmd_macro.commands
)
.execute(&mut transaction)
.await?;
added_aliases += 1;
}
None => {}
}
}
transaction.commit().await?;
ctx.send(|b| b.content(format!("Added {} macros.", added_aliases))).await?;
Ok(())
}
fn parse_text_command(
guild_id: GuildId,
alias_name: String,
command: &str,
) -> Option<RawCommandMacro> {
match command.split_once(" ") {
Some((command_word, args)) => {
let command_word = command_word.to_lowercase();
if command_word == "r"
|| command_word == "i"
|| command_word == "remind"
|| command_word == "interval"
{
let matcher = regex!(
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>.*)"#s
);
match matcher.captures(&args) {
Some(captures) => {
let mut args: Vec<Value> = vec![];
if let Some(group) = captures.name("time") {
let content = group.as_str();
args.push(json!({
"name": "time",
"value": content,
"type": CommandOptionType::String,
}));
}
if let Some(group) = captures.name("content") {
let content = group.as_str();
args.push(json!({
"name": "content",
"value": content,
"type": CommandOptionType::String,
}));
}
if let Some(group) = captures.name("interval") {
let content = group.as_str();
args.push(json!({
"name": "interval",
"value": content,
"type": CommandOptionType::String,
}));
}
if let Some(group) = captures.name("expires") {
let content = group.as_str();
args.push(json!({
"name": "expires",
"value": content,
"type": CommandOptionType::String,
}));
}
if let Some(group) = captures.name("mentions") {
let content = group.as_str();
args.push(json!({
"name": "channels",
"value": content,
"type": CommandOptionType::String,
}));
}
Some(RawCommandMacro {
guild_id,
name: alias_name,
description: None,
commands: json!([
{
"command_name": "remind",
"options": args,
}
]),
})
}
None => None,
}
} else if command_word == "n" || command_word == "natural" {
let matcher_primary = regex!(
r#"(?P<time>.*?)(?:\s+)(?:send|say)(?:\s+)(?P<content>.*?)(?:(?:\s+)to(?:\s+)(?P<mentions>((?:<@\d+>)|(?:<@!\d+>)|(?:<#\d+>)|(?:\s+))+))?$"#s
);
let matcher_secondary = regex!(
r#"(?P<msg>.*)(?:\s+)every(?:\s+)(?P<interval>.*?)(?:(?:\s+)(?:until|for)(?:\s+)(?P<expires>.*?))?$"#s
);
match matcher_primary.captures(&args) {
Some(captures) => {
let captures_secondary = matcher_secondary.captures(&args);
let mut args: Vec<Value> = vec![];
if let Some(group) = captures.name("time") {
let content = group.as_str();
args.push(json!({
"name": "time",
"value": content,
"type": CommandOptionType::String,
}));
}
if let Some(group) = captures.name("content") {
let content = group.as_str();
args.push(json!({
"name": "content",
"value": content,
"type": CommandOptionType::String,
}));
}
if let Some(group) =
captures_secondary.as_ref().and_then(|c: &Captures| c.name("interval"))
{
let content = group.as_str();
args.push(json!({
"name": "interval",
"value": content,
"type": CommandOptionType::String,
}));
}
if let Some(group) =
captures_secondary.and_then(|c: Captures| c.name("expires"))
{
let content = group.as_str();
args.push(json!({
"name": "expires",
"value": content,
"type": CommandOptionType::String,
}));
}
if let Some(group) = captures.name("mentions") {
let content = group.as_str();
args.push(json!({
"name": "channels",
"value": content,
"type": CommandOptionType::String,
}));
}
Some(RawCommandMacro {
guild_id,
name: alias_name,
description: None,
commands: json!([
{
"command_name": "remind",
"options": args,
}
]),
})
}
None => None,
}
} else {
None
}
}
None => None,
}
}

View File

@ -0,0 +1,19 @@
use crate::{Context, Error};
pub mod delete;
pub mod list;
pub mod migrate;
pub mod record;
pub mod run;
/// Record and replay command sequences
#[poise::command(
slash_command,
rename = "macro",
guild_only = true,
default_member_permissions = "MANAGE_GUILD",
identifying_name = "macro_base"
)]
pub async fn macro_base(_ctx: Context<'_>) -> Result<(), Error> {
Ok(())
}

View File

@ -0,0 +1,151 @@
use std::collections::hash_map::Entry;
use crate::{consts::THEME_COLOR, models::command_macro::CommandMacro, Context, Error};
/// Start recording up to 5 commands to replay
#[poise::command(
slash_command,
rename = "record",
guild_only = true,
default_member_permissions = "MANAGE_GUILD",
identifying_name = "record_macro"
)]
pub async fn record_macro(
ctx: Context<'_>,
#[description = "Name for the new macro"] name: String,
#[description = "Description for the new macro"] description: Option<String>,
) -> Result<(), Error> {
if name.len() > 100 {
ctx.say("Name must be less than 100 characters").await?;
return Ok(());
}
if description.as_ref().map_or(0, |d| d.len()) > 100 {
ctx.say("Description must be less than 100 characters").await?;
return Ok(());
}
let guild_id = ctx.guild_id().unwrap();
let row = sqlx::query!(
"
SELECT 1 as _e FROM macro WHERE guild_id = ? AND name = ?",
guild_id.0,
name
)
.fetch_one(&ctx.data().database)
.await;
if row.is_ok() {
ctx.send(|m| {
m.ephemeral(true).embed(|e| {
e.title("Unique Name Required")
.description(
"A macro already exists under this name.
Please select a unique name for your macro.",
)
.color(*THEME_COLOR)
})
})
.await?;
} else {
let okay = {
let mut lock = ctx.data().recording_macros.write().await;
if let Entry::Vacant(e) = lock.entry((guild_id, ctx.author().id)) {
e.insert(CommandMacro { guild_id, name, description, commands: vec![] });
true
} else {
false
}
};
if okay {
ctx.send(|m| {
m.ephemeral(true).embed(|e| {
e.title("Macro Recording Started")
.description(
"Run up to 5 commands, or type `/macro finish` to stop at any point.
Any commands ran as part of recording will be inconsequential",
)
.color(*THEME_COLOR)
})
})
.await?;
} else {
ctx.send(|m| {
m.ephemeral(true).embed(|e| {
e.title("Macro Already Recording")
.description(
"You are already recording a macro in this server.
Please use `/macro finish` to end this recording before starting another.",
)
.color(*THEME_COLOR)
})
})
.await?;
}
}
Ok(())
}
/// Finish current macro recording
#[poise::command(
slash_command,
rename = "finish",
guild_only = true,
default_member_permissions = "MANAGE_GUILD",
identifying_name = "finish_macro"
)]
pub async fn finish_macro(ctx: Context<'_>) -> Result<(), Error> {
let key = (ctx.guild_id().unwrap(), ctx.author().id);
{
let lock = ctx.data().recording_macros.read().await;
let contained = lock.get(&key);
if contained.map_or(true, |cmacro| cmacro.commands.is_empty()) {
ctx.send(|m| {
m.embed(|e| {
e.title("No Macro Recorded")
.description("Use `/macro record` to start recording a macro")
.color(*THEME_COLOR)
})
})
.await?;
} else {
let command_macro = contained.unwrap();
let json = serde_json::to_string(&command_macro.commands).unwrap();
sqlx::query!(
"INSERT INTO macro (guild_id, name, description, commands) VALUES (?, ?, ?, ?)",
command_macro.guild_id.0,
command_macro.name,
command_macro.description,
json
)
.execute(&ctx.data().database)
.await
.unwrap();
ctx.send(|m| {
m.embed(|e| {
e.title("Macro Recorded")
.description("Use `/macro run` to execute the macro")
.color(*THEME_COLOR)
})
})
.await?;
}
}
{
let mut lock = ctx.data().recording_macros.write().await;
lock.remove(&key);
}
Ok(())
}

View File

@ -0,0 +1,46 @@
use super::super::autocomplete::macro_name_autocomplete;
use crate::{models::command_macro::guild_command_macro, Context, Data, Error};
/// Run a recorded macro
#[poise::command(
slash_command,
rename = "run",
guild_only = true,
default_member_permissions = "MANAGE_GUILD",
identifying_name = "run_macro"
)]
pub async fn run_macro(
ctx: poise::ApplicationContext<'_, Data, Error>,
#[description = "Name of macro to run"]
#[autocomplete = "macro_name_autocomplete"]
name: String,
) -> Result<(), Error> {
match guild_command_macro(&Context::Application(ctx), &name).await {
Some(command_macro) => {
ctx.defer_response(false).await?;
for command in command_macro.commands {
if let Some(action) = command.action {
match (action)(poise::ApplicationContext { args: &command.options, ..ctx })
.await
{
Ok(()) => {}
Err(e) => {
println!("{:?}", e);
}
}
} else {
Context::Application(ctx)
.say(format!("Command \"{}\" not found", command.command_name))
.await?;
}
}
}
None => {
Context::Application(ctx).say(format!("Macro \"{}\" not found", name)).await?;
}
}
Ok(())
}

View File

@ -49,6 +49,7 @@ __Todo Commands__
__Setup Commands__ __Setup Commands__
`/timezone` - Set your timezone (necessary for `/remind` to work properly) `/timezone` - Set your timezone (necessary for `/remind` to work properly)
`/dm allow/block` - Change your DM settings for reminders.
__Advanced Commands__ __Advanced Commands__
`/macro` - Record and replay command sequences `/macro` - Record and replay command sequences

View File

@ -1,3 +1,5 @@
mod autocomplete;
pub mod command_macro;
pub mod info_cmds; pub mod info_cmds;
pub mod moderation_cmds; pub mod moderation_cmds;
pub mod reminder_cmds; pub mod reminder_cmds;

View File

@ -1,32 +1,11 @@
use std::collections::hash_map::Entry;
use chrono::offset::Utc; use chrono::offset::Utc;
use chrono_tz::{Tz, TZ_VARIANTS}; use chrono_tz::{Tz, TZ_VARIANTS};
use levenshtein::levenshtein; use levenshtein::levenshtein;
use poise::CreateReply; use log::warn;
use poise::serenity_prelude::{ChannelId, Mentionable};
use crate::{ use super::autocomplete::timezone_autocomplete;
component_models::pager::{MacroPager, Pager}, use crate::{consts::THEME_COLOR, models::CtxData, Context, Error};
consts::{EMBED_DESCRIPTION_MAX_LENGTH, THEME_COLOR},
models::{
command_macro::{guild_command_macro, CommandMacro},
CtxData,
},
Context, Data, Error,
};
async fn timezone_autocomplete(ctx: Context<'_>, partial: String) -> Vec<String> {
if partial.is_empty() {
ctx.data().popular_timezones.iter().map(|t| t.to_string()).collect::<Vec<String>>()
} else {
TZ_VARIANTS
.iter()
.filter(|tz| tz.to_string().contains(&partial))
.take(25)
.map(|t| t.to_string())
.collect::<Vec<String>>()
}
}
/// Select your timezone /// Select your timezone
#[poise::command(slash_command, identifying_name = "timezone")] #[poise::command(slash_command, identifying_name = "timezone")]
@ -124,376 +103,122 @@ You may want to use one of the popular timezones below, otherwise click [here](h
Ok(()) Ok(())
} }
async fn macro_name_autocomplete(ctx: Context<'_>, partial: String) -> Vec<String> { /// Configure whether other users can set reminders to your direct messages
sqlx::query!( #[poise::command(slash_command, rename = "dm", identifying_name = "allowed_dm")]
" pub async fn allowed_dm(_ctx: Context<'_>) -> Result<(), Error> {
SELECT name
FROM macro
WHERE
guild_id = (SELECT id FROM guilds WHERE guild = ?)
AND name LIKE CONCAT(?, '%')",
ctx.guild_id().unwrap().0,
partial,
)
.fetch_all(&ctx.data().database)
.await
.unwrap_or_default()
.iter()
.map(|s| s.name.clone())
.collect()
}
/// Record and replay command sequences
#[poise::command(
slash_command,
rename = "macro",
guild_only = true,
default_member_permissions = "MANAGE_GUILD",
identifying_name = "macro_base"
)]
pub async fn macro_base(_ctx: Context<'_>) -> Result<(), Error> {
Ok(()) Ok(())
} }
/// Start recording up to 5 commands to replay /// Allow other users to set reminders in your direct messages
#[poise::command(slash_command, rename = "allow", identifying_name = "allowed_dm")]
pub async fn set_allowed_dm(ctx: Context<'_>) -> Result<(), Error> {
let mut user_data = ctx.author_data().await?;
user_data.allowed_dm = true;
user_data.commit_changes(&ctx.data().database).await;
ctx.send(|r| {
r.ephemeral(true).embed(|e| {
e.title("DMs permitted")
.description("You will receive a message if a user sets a DM reminder for you.")
.color(*THEME_COLOR)
})
})
.await?;
Ok(())
}
/// Block other users from setting reminders in your direct messages
#[poise::command(slash_command, rename = "block", identifying_name = "allowed_dm")]
pub async fn unset_allowed_dm(ctx: Context<'_>) -> Result<(), Error> {
let mut user_data = ctx.author_data().await?;
user_data.allowed_dm = false;
user_data.commit_changes(&ctx.data().database).await;
ctx.send(|r| {
r.ephemeral(true).embed(|e| {
e.title("DMs blocked")
.description(
"You can still set DM reminders for yourself or for users with DMs enabled.",
)
.color(*THEME_COLOR)
})
})
.await?;
Ok(())
}
/// Set defaults for commands
#[poise::command( #[poise::command(
slash_command, slash_command,
rename = "record", identifying_name = "default",
guild_only = true, default_member_permissions = "MANAGE_GUILD"
default_member_permissions = "MANAGE_GUILD",
identifying_name = "record_macro"
)] )]
pub async fn record_macro( pub async fn default(_ctx: Context<'_>) -> Result<(), Error> {
Ok(())
}
/// Set a default channel for reminders to be sent to
#[poise::command(
slash_command,
guild_only = true,
identifying_name = "default_channel",
default_member_permissions = "MANAGE_GUILD"
)]
pub async fn default_channel(
ctx: Context<'_>, ctx: Context<'_>,
#[description = "Name for the new macro"] name: String, #[description = "Channel to send reminders to by default"] channel: Option<ChannelId>,
#[description = "Description for the new macro"] description: Option<String>,
) -> Result<(), Error> { ) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap(); if let Some(mut guild_data) = ctx.guild_data().await {
guild_data.default_channel = channel.map(|c| c.0);
let row = sqlx::query!( guild_data.commit_changes(&ctx.data().database).await?;
"
SELECT 1 as _e FROM macro WHERE guild_id = (SELECT id FROM guilds WHERE guild = ?) AND name = ?",
guild_id.0,
name
)
.fetch_one(&ctx.data().database)
.await;
if row.is_ok() { if let Some(channel) = channel {
ctx.send(|m| { ctx.send(|r| {
m.ephemeral(true).embed(|e| { r.ephemeral(true).content(format!("Default channel set to {}", channel.mention()))
e.title("Unique Name Required")
.description(
"A macro already exists under this name.
Please select a unique name for your macro.",
)
.color(*THEME_COLOR)
})
}) })
.await?; .await?;
} else { } else {
let okay = { ctx.send(|r| r.ephemeral(true).content("Default channel unset.")).await?;
let mut lock = ctx.data().recording_macros.write().await;
if let Entry::Vacant(e) = lock.entry((guild_id, ctx.author().id)) {
e.insert(CommandMacro { guild_id, name, description, commands: vec![] });
true
} else {
false
}
};
if okay {
ctx.send(|m| {
m.ephemeral(true).embed(|e| {
e.title("Macro Recording Started")
.description(
"Run up to 5 commands, or type `/macro finish` to stop at any point.
Any commands ran as part of recording will be inconsequential",
)
.color(*THEME_COLOR)
})
})
.await?;
} else {
ctx.send(|m| {
m.ephemeral(true).embed(|e| {
e.title("Macro Already Recording")
.description(
"You are already recording a macro in this server.
Please use `/macro finish` to end this recording before starting another.",
)
.color(*THEME_COLOR)
})
})
.await?;
} }
} }
Ok(()) Ok(())
} }
/// Finish current macro recording /// View the webhook being used to send reminders to this channel
#[poise::command( #[poise::command(
slash_command, slash_command,
rename = "finish", identifying_name = "webhook_url",
guild_only = true, required_permissions = "ADMINISTRATOR",
default_member_permissions = "MANAGE_GUILD", default_member_permissions = "ADMINISTRATOR"
identifying_name = "finish_macro"
)] )]
pub async fn finish_macro(ctx: Context<'_>) -> Result<(), Error> { pub async fn webhook(ctx: Context<'_>) -> Result<(), Error> {
let key = (ctx.guild_id().unwrap(), ctx.author().id); match ctx.channel_data().await {
Ok(data) => {
{ if let (Some(id), Some(token)) = (data.webhook_id, data.webhook_token) {
let lock = ctx.data().recording_macros.read().await; ctx.send(|b| {
let contained = lock.get(&key); b.ephemeral(true).content(format!(
"**Warning!**
if contained.map_or(true, |cmacro| cmacro.commands.is_empty()) { This link can be used by users to anonymously send messages, with or without permissions.
ctx.send(|m| { Do not share it!
m.embed(|e| { || https://discord.com/api/webhooks/{}/{} ||",
e.title("No Macro Recorded") id, token,
.description("Use `/macro record` to start recording a macro") ))
.color(*THEME_COLOR)
})
}) })
.await?; .await?;
} else { } else {
let command_macro = contained.unwrap(); ctx.say("No webhook configured on this channel.").await?;
let json = serde_json::to_string(&command_macro.commands).unwrap();
sqlx::query!(
"INSERT INTO macro (guild_id, name, description, commands) VALUES ((SELECT id FROM guilds WHERE guild = ?), ?, ?, ?)",
command_macro.guild_id.0,
command_macro.name,
command_macro.description,
json
)
.execute(&ctx.data().database)
.await
.unwrap();
ctx.send(|m| {
m.embed(|e| {
e.title("Macro Recorded")
.description("Use `/macro run` to execute the macro")
.color(*THEME_COLOR)
})
})
.await?;
} }
} }
{
let mut lock = ctx.data().recording_macros.write().await;
lock.remove(&key);
}
Ok(())
}
/// List recorded macros
#[poise::command(
slash_command,
rename = "list",
guild_only = true,
default_member_permissions = "MANAGE_GUILD",
identifying_name = "list_macro"
)]
pub async fn list_macro(ctx: Context<'_>) -> Result<(), Error> {
let macros = ctx.command_macros().await?;
let resp = show_macro_page(&macros, 0);
ctx.send(|m| {
*m = resp;
m
})
.await?;
Ok(())
}
/// Run a recorded macro
#[poise::command(
slash_command,
rename = "run",
guild_only = true,
default_member_permissions = "MANAGE_GUILD",
identifying_name = "run_macro"
)]
pub async fn run_macro(
ctx: poise::ApplicationContext<'_, Data, Error>,
#[description = "Name of macro to run"]
#[autocomplete = "macro_name_autocomplete"]
name: String,
) -> Result<(), Error> {
match guild_command_macro(&Context::Application(ctx), &name).await {
Some(command_macro) => {
ctx.defer_response(false).await?;
for command in command_macro.commands {
if let Some(action) = command.action {
match (action)(poise::ApplicationContext { args: &command.options, ..ctx })
.await
{
Ok(()) => {}
Err(e) => { Err(e) => {
println!("{:?}", e); warn!("Error fetching channel data: {:?}", e);
}
}
} else {
Context::Application(ctx)
.say(format!("Command \"{}\" not found", command.command_name))
.await?;
}
}
}
None => { ctx.say("No webhook configured on this channel.").await?;
Context::Application(ctx).say(format!("Macro \"{}\" not found", name)).await?;
} }
} }
Ok(()) Ok(())
} }
/// Delete a recorded macro
#[poise::command(
slash_command,
rename = "delete",
guild_only = true,
default_member_permissions = "MANAGE_GUILD",
identifying_name = "delete_macro"
)]
pub async fn delete_macro(
ctx: Context<'_>,
#[description = "Name of macro to delete"]
#[autocomplete = "macro_name_autocomplete"]
name: String,
) -> Result<(), Error> {
match sqlx::query!(
"
SELECT id FROM macro WHERE guild_id = (SELECT id FROM guilds WHERE guild = ?) AND name = ?",
ctx.guild_id().unwrap().0,
name
)
.fetch_one(&ctx.data().database)
.await
{
Ok(row) => {
sqlx::query!("DELETE FROM macro WHERE id = ?", row.id)
.execute(&ctx.data().database)
.await
.unwrap();
ctx.say(format!("Macro \"{}\" deleted", name)).await?;
}
Err(sqlx::Error::RowNotFound) => {
ctx.say(format!("Macro \"{}\" not found", name)).await?;
}
Err(e) => {
panic!("{}", e);
}
}
Ok(())
}
pub fn max_macro_page<U, E>(macros: &[CommandMacro<U, E>]) -> usize {
let mut skipped_char_count = 0;
macros
.iter()
.map(|m| {
if let Some(description) = &m.description {
format!("**{}**\n- *{}*\n- Has {} commands", m.name, description, m.commands.len())
} else {
format!("**{}**\n- Has {} commands", m.name, m.commands.len())
}
})
.fold(1, |mut pages, p| {
skipped_char_count += p.len();
if skipped_char_count > EMBED_DESCRIPTION_MAX_LENGTH {
skipped_char_count = p.len();
pages += 1;
}
pages
})
}
pub fn show_macro_page<U, E>(macros: &[CommandMacro<U, E>], page: usize) -> CreateReply {
let pager = MacroPager::new(page);
if macros.is_empty() {
let mut reply = CreateReply::default();
reply.embed(|e| {
e.title("Macros")
.description("No Macros Set Up. Use `/macro record` to get started.")
.color(*THEME_COLOR)
});
return reply;
}
let pages = max_macro_page(macros);
let mut page = page;
if page >= pages {
page = pages - 1;
}
let mut char_count = 0;
let mut skipped_char_count = 0;
let mut skipped_pages = 0;
let display_vec: Vec<String> = macros
.iter()
.map(|m| {
if let Some(description) = &m.description {
format!("**{}**\n- *{}*\n- Has {} commands", m.name, description, m.commands.len())
} else {
format!("**{}**\n- Has {} commands", m.name, m.commands.len())
}
})
.skip_while(|p| {
skipped_char_count += p.len();
if skipped_char_count > EMBED_DESCRIPTION_MAX_LENGTH {
skipped_char_count = p.len();
skipped_pages += 1;
}
skipped_pages < page
})
.take_while(|p| {
char_count += p.len();
char_count < EMBED_DESCRIPTION_MAX_LENGTH
})
.collect::<Vec<String>>();
let display = display_vec.join("\n");
let mut reply = CreateReply::default();
reply
.embed(|e| {
e.title("Macros")
.description(display)
.footer(|f| f.text(format!("Page {} of {}", page + 1, pages)))
.color(*THEME_COLOR)
})
.components(|comp| {
pager.create_button_row(pages, comp);
comp
});
reply
}

View File

@ -8,12 +8,16 @@ use chrono::NaiveDateTime;
use chrono_tz::Tz; use chrono_tz::Tz;
use num_integer::Integer; use num_integer::Integer;
use poise::{ use poise::{
serenity::{builder::CreateEmbed, model::channel::Channel}, serenity_prelude::{
serenity_prelude::{ButtonStyle, ReactionType}, builder::CreateEmbed, component::ButtonStyle, model::channel::Channel, ReactionType,
CreateReply, },
CreateReply, Modal,
}; };
use crate::{ use crate::{
commands::autocomplete::{
multiline_autocomplete, time_hint_autocomplete, timezone_autocomplete,
},
component_models::{ component_models::{
pager::{DelPager, LookPager, Pager}, pager::{DelPager, LookPager, Pager},
ComponentDataModel, DelSelector, UndoReminder, ComponentDataModel, DelSelector, UndoReminder,
@ -36,7 +40,7 @@ use crate::{
}, },
time_parser::natural_parser, time_parser::natural_parser,
utils::{check_guild_subscription, check_subscription}, utils::{check_guild_subscription, check_subscription},
Context, Error, ApplicationContext, Context, Error,
}; };
/// Pause all reminders on the current channel until a certain time or indefinitely /// Pause all reminders on the current channel until a certain time or indefinitely
@ -548,23 +552,81 @@ pub async fn delete_timer(
Ok(()) Ok(())
} }
/// Create a new reminder #[derive(poise::Modal)]
#[name = "Reminder"]
struct ContentModal {
#[name = "Content"]
#[placeholder = "Message..."]
#[paragraph]
#[max_length = 2000]
content: String,
}
/// Create a reminder. Press "+4 more" for other options.
#[poise::command( #[poise::command(
slash_command, slash_command,
identifying_name = "remind", identifying_name = "remind",
default_member_permissions = "MANAGE_GUILD" default_member_permissions = "MANAGE_GUILD"
)] )]
pub async fn remind( pub async fn remind(
ctx: Context<'_>, ctx: ApplicationContext<'_>,
#[description = "A description of the time to set the reminder for"] time: String, #[description = "A description of the time to set the reminder for"]
#[description = "The message content to send"] content: String, #[autocomplete = "time_hint_autocomplete"]
time: String,
#[description = "The message content to send"]
#[autocomplete = "multiline_autocomplete"]
content: String,
#[description = "Channel or user mentions to set the reminder for"] channels: Option<String>, #[description = "Channel or user mentions to set the reminder for"] channels: Option<String>,
#[description = "(Patreon only) Time to wait before repeating the reminder. Leave blank for one-shot reminder"] #[description = "(Patreon only) Time to wait before repeating the reminder. Leave blank for one-shot reminder"]
interval: Option<String>, interval: Option<String>,
#[description = "(Patreon only) For repeating reminders, the time at which the reminder will stop sending"] #[description = "(Patreon only) For repeating reminders, the time at which the reminder will stop repeating"]
expires: Option<String>, expires: Option<String>,
#[description = "Set the TTS flag on the reminder message, similar to the /tts command"] #[description = "Set the TTS flag on the reminder message, similar to the /tts command"]
tts: Option<bool>, tts: Option<bool>,
#[description = "Set a timezone override for this reminder only"]
#[autocomplete = "timezone_autocomplete"]
timezone: Option<String>,
) -> Result<(), Error> {
let tz = timezone.map(|t| t.parse::<Tz>().ok()).flatten();
if content.is_empty() {
let data = ContentModal::execute(ctx).await?;
create_reminder(
Context::Application(ctx),
time,
data.content,
channels,
interval,
expires,
tts,
tz,
)
.await
} else {
create_reminder(
Context::Application(ctx),
time,
content,
channels,
interval,
expires,
tts,
tz,
)
.await
}
}
async fn create_reminder(
ctx: Context<'_>,
time: String,
content: String,
channels: Option<String>,
interval: Option<String>,
expires: Option<String>,
tts: Option<bool>,
timezone: Option<Tz>,
) -> Result<(), Error> { ) -> Result<(), Error> {
if interval.is_none() && expires.is_some() { if interval.is_none() && expires.is_some() {
ctx.say("`expires` can only be used with `interval`").await?; ctx.say("`expires` can only be used with `interval`").await?;
@ -575,7 +637,7 @@ pub async fn remind(
ctx.defer().await?; ctx.defer().await?;
let user_data = ctx.author_data().await.unwrap(); let user_data = ctx.author_data().await.unwrap();
let timezone = ctx.timezone().await; let timezone = timezone.unwrap_or(ctx.timezone().await);
let time = natural_parser(&time, &timezone.to_string()).await; let time = natural_parser(&time, &timezone.to_string()).await;
@ -591,7 +653,9 @@ pub async fn remind(
let list = channels.map(|arg| parse_mention_list(&arg)).unwrap_or_default(); let list = channels.map(|arg| parse_mention_list(&arg)).unwrap_or_default();
if list.is_empty() { if list.is_empty() {
if ctx.guild_id().is_some() { if let Some(channel_id) = ctx.default_channel().await {
vec![ReminderScope::Channel(channel_id.0)]
} else if ctx.guild_id().is_some() {
vec![ReminderScope::Channel(ctx.channel_id().0)] vec![ReminderScope::Channel(ctx.channel_id().0)]
} else { } else {
vec![ReminderScope::User(ctx.author().id.0)] vec![ReminderScope::User(ctx.author().id.0)]
@ -694,6 +758,7 @@ pub async fn remind(
} }
} }
} }
None => { None => {
ctx.say("Time could not be processed").await?; ctx.say("Time could not be processed").await?;
} }

View File

@ -6,6 +6,7 @@ use crate::{
ComponentDataModel, TodoSelector, ComponentDataModel, TodoSelector,
}, },
consts::{EMBED_DESCRIPTION_MAX_LENGTH, SELECT_MAX_ENTRIES, THEME_COLOR}, consts::{EMBED_DESCRIPTION_MAX_LENGTH, SELECT_MAX_ENTRIES, THEME_COLOR},
models::CtxData,
Context, Error, Context, Error,
}; };
@ -46,7 +47,7 @@ pub async fn todo_guild_add(
) -> Result<(), Error> { ) -> Result<(), Error> {
sqlx::query!( sqlx::query!(
"INSERT INTO todos (guild_id, value) "INSERT INTO todos (guild_id, value)
VALUES ((SELECT id FROM guilds WHERE guild = ?), ?)", VALUES (?, ?)",
ctx.guild_id().unwrap().0, ctx.guild_id().unwrap().0,
task task
) )
@ -69,9 +70,7 @@ VALUES ((SELECT id FROM guilds WHERE guild = ?), ?)",
)] )]
pub async fn todo_guild_view(ctx: Context<'_>) -> Result<(), Error> { pub async fn todo_guild_view(ctx: Context<'_>) -> Result<(), Error> {
let values = sqlx::query!( let values = sqlx::query!(
"SELECT todos.id, value FROM todos "SELECT todos.id, value FROM todos WHERE guild_id = ?",
INNER JOIN guilds ON todos.guild_id = guilds.id
WHERE guilds.guild = ?",
ctx.guild_id().unwrap().0, ctx.guild_id().unwrap().0,
) )
.fetch_all(&ctx.data().database) .fetch_all(&ctx.data().database)
@ -116,9 +115,12 @@ pub async fn todo_channel_add(
ctx: Context<'_>, ctx: Context<'_>,
#[description = "The task to add to the todo list"] task: String, #[description = "The task to add to the todo list"] task: String,
) -> Result<(), Error> { ) -> Result<(), Error> {
// ensure channel is cached
let _ = ctx.channel_data().await;
sqlx::query!( sqlx::query!(
"INSERT INTO todos (guild_id, channel_id, value) "INSERT INTO todos (guild_id, channel_id, value)
VALUES ((SELECT id FROM guilds WHERE guild = ?), (SELECT id FROM channels WHERE channel = ?), ?)", VALUES (?, (SELECT id FROM channels WHERE channel = ?), ?)",
ctx.guild_id().unwrap().0, ctx.guild_id().unwrap().0,
ctx.channel_id().0, ctx.channel_id().0,
task task

View File

@ -5,25 +5,25 @@ use std::io::Cursor;
use chrono_tz::Tz; use chrono_tz::Tz;
use log::warn; use log::warn;
use poise::{ use poise::{
serenity::{
builder::CreateEmbed,
client::Context,
model::{
channel::Channel,
interactions::{
message_component::MessageComponentInteraction, InteractionResponseType,
},
prelude::InteractionApplicationCommandCallbackDataFlags,
},
},
serenity_prelude as serenity, serenity_prelude as serenity,
serenity_prelude::{
builder::CreateEmbed,
model::{
application::interaction::{
message_component::MessageComponentInteraction, InteractionResponseType,
MessageFlags,
},
channel::Channel,
},
Context,
},
}; };
use rmp_serde::Serializer; use rmp_serde::Serializer;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{ use crate::{
commands::{ commands::{
moderation_cmds::{max_macro_page, show_macro_page}, command_macro::list::{max_macro_page, show_macro_page},
reminder_cmds::{max_delete_page, show_delete_page}, reminder_cmds::{max_delete_page, show_delete_page},
todo_cmds::{max_todo_page, show_todo_page}, todo_cmds::{max_todo_page, show_todo_page},
}, },
@ -222,9 +222,7 @@ WHERE channels.channel = ?",
.collect::<Vec<(usize, String)>>() .collect::<Vec<(usize, String)>>()
} else { } else {
sqlx::query!( sqlx::query!(
"SELECT todos.id, value FROM todos "SELECT todos.id, value FROM todos WHERE guild_id = ?",
INNER JOIN guilds ON todos.guild_id = guilds.id
WHERE guilds.guild = ?",
pager.guild_id, pager.guild_id,
) )
.fetch_all(&data.database) .fetch_all(&data.database)
@ -260,7 +258,7 @@ WHERE guilds.guild = ?",
r.kind(InteractionResponseType::ChannelMessageWithSource) r.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|d| { .interaction_response_data(|d| {
d.flags( d.flags(
InteractionApplicationCommandCallbackDataFlags::EPHEMERAL, MessageFlags::EPHEMERAL,
) )
.content("Only the user who performed the command can use these components") .content("Only the user who performed the command can use these components")
}) })
@ -314,7 +312,7 @@ WHERE guilds.guild = ?",
r.kind(InteractionResponseType::ChannelMessageWithSource) r.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|d| { .interaction_response_data(|d| {
d.flags( d.flags(
InteractionApplicationCommandCallbackDataFlags::EPHEMERAL, MessageFlags::EPHEMERAL,
) )
.content("Only the user who performed the command can use these components") .content("Only the user who performed the command can use these components")
}) })

View File

@ -1,7 +1,7 @@
// todo split pager out into a single struct // todo split pager out into a single struct
use chrono_tz::Tz; use chrono_tz::Tz;
use poise::serenity::{ use poise::serenity_prelude::{
builder::CreateComponents, model::interactions::message_component::ButtonStyle, builder::CreateComponents, model::application::component::ButtonStyle,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_repr::*; use serde_repr::*;

View File

@ -2,7 +2,7 @@ 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 EMBED_DESCRIPTION_MAX_LENGTH: usize = 4000; pub const EMBED_DESCRIPTION_MAX_LENGTH: usize = 4096;
pub const SELECT_MAX_ENTRIES: usize = 25; pub const SELECT_MAX_ENTRIES: usize = 25;
pub const CHARACTERS: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; pub const CHARACTERS: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
@ -12,7 +12,7 @@ pub const MACRO_MAX_COMMANDS: usize = 5;
use std::{collections::HashSet, env, iter::FromIterator}; use std::{collections::HashSet, env, iter::FromIterator};
use poise::serenity::model::prelude::AttachmentType; use poise::serenity_prelude::model::prelude::AttachmentType;
use regex::Regex; use regex::Regex;
lazy_static! { lazy_static! {

View File

@ -1,12 +1,14 @@
use std::{collections::HashMap, env, sync::atomic::Ordering}; use std::{collections::HashMap, env};
use log::{error, info, warn}; use log::error;
use poise::{ use poise::{
serenity::{model::interactions::Interaction, utils::shard_id},
serenity_prelude as serenity, serenity_prelude as serenity,
serenity_prelude::{model::application::interaction::Interaction, utils::shard_id},
}; };
use crate::{component_models::ComponentDataModel, Data, Error}; use crate::{
component_models::ComponentDataModel, models::guild_data::GuildData, Data, Error, THEME_COLOR,
};
pub async fn listener( pub async fn listener(
ctx: &serenity::Context, ctx: &serenity::Context,
@ -17,45 +19,6 @@ pub async fn listener(
poise::Event::Ready { .. } => { poise::Event::Ready { .. } => {
ctx.set_activity(serenity::Activity::watching("for /remind")).await; ctx.set_activity(serenity::Activity::watching("for /remind")).await;
} }
poise::Event::CacheReady { .. } => {
info!("Cache Ready! Preparing extra processes");
if !data.is_loop_running.load(Ordering::Relaxed) {
let kill_tx = data.broadcast.clone();
let kill_recv = data.broadcast.subscribe();
let ctx1 = ctx.clone();
let ctx2 = ctx.clone();
let pool1 = data.database.clone();
let pool2 = data.database.clone();
let run_settings = env::var("DONTRUN").unwrap_or_else(|_| "".to_string());
if !run_settings.contains("postman") {
tokio::spawn(async move {
match postman::initialize(kill_recv, ctx1, &pool1).await {
Ok(_) => {}
Err(e) => {
error!("postman exiting: {}", e);
}
};
});
} else {
warn!("Not running postman");
}
if !run_settings.contains("web") {
tokio::spawn(async move {
reminder_web::initialize(kill_tx, ctx2, pool2).await.unwrap();
});
} else {
warn!("Not running web");
}
data.is_loop_running.swap(true, Ordering::Relaxed);
}
}
poise::Event::ChannelDelete { channel } => { poise::Event::ChannelDelete { channel } => {
sqlx::query!("DELETE FROM channels WHERE channel = ?", channel.id.as_u64()) sqlx::query!("DELETE FROM channels WHERE channel = ?", channel.id.as_u64())
.execute(&data.database) .execute(&data.database)
@ -66,11 +29,74 @@ pub async fn listener(
if *is_new { if *is_new {
let guild_id = guild.id.as_u64().to_owned(); let guild_id = guild.id.as_u64().to_owned();
sqlx::query!("INSERT INTO guilds (guild) VALUES (?)", guild_id) sqlx::query!("INSERT IGNORE INTO guilds (id) VALUES (?)", guild_id)
.execute(&data.database) .execute(&data.database)
.await .await?;
.unwrap();
if let Err(e) = post_guild_count(ctx, &data.http, guild_id).await {
error!("DiscordBotList: {:?}", e);
}
let default_channel = guild.default_channel_guaranteed();
if let Some(default_channel) = default_channel {
default_channel
.send_message(&ctx, |m| {
m.embed(|e| {
e.title("Thank you for adding Reminder Bot!").description(
"To get started:
• Set your timezone with `/timezone`
• Set up permissions in Server Settings 🠚 Integrations 🠚 Reminder Bot (desktop only)
• Create your first reminder with `/remind`
__Support__
If you need any support, please come and ask us! Join our [Discord](https://discord.jellywx.com).
__Updates__
To stay up to date on the latest features and fixes, join our [Discord](https://discord.jellywx.com).
",
).color(*THEME_COLOR)
})
})
.await?;
}
}
}
poise::Event::GuildDelete { incomplete, .. } => {
let _ = sqlx::query!("DELETE FROM guilds WHERE id = ?", incomplete.id.0)
.execute(&data.database)
.await;
}
poise::Event::InteractionCreate { interaction } => {
match interaction {
Interaction::ApplicationCommand(app_command) => {
if let Some(guild_id) = app_command.guild_id {
// check database guild exists
GuildData::from_guild(guild_id, &data.database).await?;
}
}
Interaction::MessageComponent(component) => {
let component_model =
ComponentDataModel::from_custom_id(&component.data.custom_id);
component_model.act(ctx, data, component).await;
}
_ => {}
}
}
_ => {}
}
Ok(())
}
async fn post_guild_count(
ctx: &serenity::Context,
http: &reqwest::Client,
guild_id: u64,
) -> Result<(), reqwest::Error> {
if let Ok(token) = env::var("DISCORDBOTS_TOKEN") { if let Ok(token) = env::var("DISCORDBOTS_TOKEN") {
let shard_count = ctx.cache.shard_count(); let shard_count = ctx.cache.shard_count();
let current_shard_id = shard_id(guild_id, shard_count); let current_shard_id = shard_id(guild_id, shard_count);
@ -79,9 +105,7 @@ pub async fn listener(
.cache .cache
.guilds() .guilds()
.iter() .iter()
.filter(|g| { .filter(|g| shard_id(g.as_u64().to_owned(), shard_count) == current_shard_id)
shard_id(g.as_u64().to_owned(), shard_count) == current_shard_id
})
.count() as u64; .count() as u64;
let mut hm = HashMap::new(); let mut hm = HashMap::new();
@ -89,40 +113,16 @@ pub async fn listener(
hm.insert("shard_id", current_shard_id); hm.insert("shard_id", current_shard_id);
hm.insert("shard_count", shard_count); hm.insert("shard_count", shard_count);
let response = data http.post(
.http format!("https://top.gg/api/bots/{}/stats", ctx.cache.current_user_id().as_u64())
.post(
format!(
"https://top.gg/api/bots/{}/stats",
ctx.cache.current_user_id().as_u64()
)
.as_str(), .as_str(),
) )
.header("Authorization", token) .header("Authorization", token)
.json(&hm) .json(&hm)
.send() .send()
.await; .await
.map(|_| ())
if let Err(res) = response { } else {
println!("DiscordBots Response: {:?}", res);
}
}
}
}
poise::Event::GuildDelete { incomplete, .. } => {
let _ = sqlx::query!("DELETE FROM guilds WHERE guild = ?", incomplete.id.0)
.execute(&data.database)
.await;
}
poise::Event::InteractionCreate { interaction } => {
if let Interaction::MessageComponent(component) = interaction {
let component_model = ComponentDataModel::from_custom_id(&component.data.custom_id);
component_model.act(ctx, data, component).await;
}
}
_ => {}
}
Ok(()) Ok(())
} }
}

View File

@ -1,9 +1,14 @@
use poise::serenity::model::channel::Channel; use poise::{
serenity_prelude::model::channel::Channel, ApplicationCommandOrAutocompleteInteraction,
};
use crate::{consts::MACRO_MAX_COMMANDS, models::command_macro::RecordedCommand, Context, Error}; use crate::{consts::MACRO_MAX_COMMANDS, models::command_macro::RecordedCommand, Context, Error};
async fn macro_check(ctx: Context<'_>) -> bool { async fn macro_check(ctx: Context<'_>) -> bool {
if let Context::Application(app_ctx) = ctx { if let Context::Application(app_ctx) = ctx {
if let ApplicationCommandOrAutocompleteInteraction::ApplicationCommand(_) =
app_ctx.interaction
{
if let Some(guild_id) = ctx.guild_id() { if let Some(guild_id) = ctx.guild_id() {
if ctx.command().identifying_name != "finish_macro" { if ctx.command().identifying_name != "finish_macro" {
let mut lock = ctx.data().recording_macros.write().await; let mut lock = ctx.data().recording_macros.write().await;
@ -35,6 +40,7 @@ async fn macro_check(ctx: Context<'_>) -> bool {
} }
} }
} }
}
true true
} }

View File

@ -18,12 +18,12 @@ use std::{
env, env,
error::Error as StdError, error::Error as StdError,
fmt::{Debug, Display, Formatter}, fmt::{Debug, Display, Formatter},
sync::atomic::AtomicBool,
}; };
use chrono_tz::Tz; use chrono_tz::Tz;
use dotenv::dotenv; use dotenv::dotenv;
use poise::serenity::model::{ use log::{error, warn};
use poise::serenity_prelude::model::{
gateway::GatewayIntents, gateway::GatewayIntents,
id::{GuildId, UserId}, id::{GuildId, UserId},
}; };
@ -31,7 +31,7 @@ use sqlx::{MySql, Pool};
use tokio::sync::{broadcast, broadcast::Sender, RwLock}; use tokio::sync::{broadcast, broadcast::Sender, RwLock};
use crate::{ use crate::{
commands::{info_cmds, moderation_cmds, reminder_cmds, todo_cmds}, commands::{command_macro, info_cmds, moderation_cmds, reminder_cmds, todo_cmds},
consts::THEME_COLOR, consts::THEME_COLOR,
event_handlers::listener, event_handlers::listener,
hooks::all_checks, hooks::all_checks,
@ -43,14 +43,14 @@ type Database = MySql;
type Error = Box<dyn std::error::Error + Send + Sync>; type Error = Box<dyn std::error::Error + Send + Sync>;
type Context<'a> = poise::Context<'a, Data, Error>; type Context<'a> = poise::Context<'a, Data, Error>;
type ApplicationContext<'a> = poise::ApplicationContext<'a, Data, Error>;
pub struct Data { pub struct Data {
database: Pool<Database>, database: Pool<Database>,
http: reqwest::Client, http: reqwest::Client,
recording_macros: RwLock<HashMap<(GuildId, UserId), CommandMacro<Data, Error>>>, recording_macros: RwLock<HashMap<(GuildId, UserId), CommandMacro<Data, Error>>>,
popular_timezones: Vec<Tz>, popular_timezones: Vec<Tz>,
is_loop_running: AtomicBool, _broadcast: Sender<()>,
broadcast: Sender<()>,
} }
impl Debug for Data { impl Debug for Data {
@ -103,13 +103,26 @@ async fn _main(tx: Sender<()>) -> Result<(), Box<dyn StdError + Send + Sync>> {
moderation_cmds::timezone(), moderation_cmds::timezone(),
poise::Command { poise::Command {
subcommands: vec![ subcommands: vec![
moderation_cmds::delete_macro(), moderation_cmds::set_allowed_dm(),
moderation_cmds::finish_macro(), moderation_cmds::unset_allowed_dm(),
moderation_cmds::list_macro(),
moderation_cmds::record_macro(),
moderation_cmds::run_macro(),
], ],
..moderation_cmds::macro_base() ..moderation_cmds::allowed_dm()
},
moderation_cmds::webhook(),
poise::Command {
subcommands: vec![
command_macro::delete::delete_macro(),
command_macro::record::finish_macro(),
command_macro::list::list_macro(),
command_macro::record::record_macro(),
command_macro::run::run_macro(),
command_macro::migrate::migrate_macro(),
],
..command_macro::macro_base()
},
poise::Command {
subcommands: vec![moderation_cmds::default_channel()],
..moderation_cmds::default()
}, },
reminder_cmds::pause(), reminder_cmds::pause(),
reminder_cmds::offset(), reminder_cmds::offset(),
@ -159,7 +172,12 @@ async fn _main(tx: Sender<()>) -> Result<(), Box<dyn StdError + Send + Sync>> {
Pool::connect(&env::var("DATABASE_URL").expect("No database URL provided")).await.unwrap(); Pool::connect(&env::var("DATABASE_URL").expect("No database URL provided")).await.unwrap();
let popular_timezones = sqlx::query!( let popular_timezones = sqlx::query!(
"SELECT timezone FROM users GROUP BY timezone ORDER BY COUNT(timezone) DESC LIMIT 21" "SELECT IFNULL(timezone, 'UTC') AS timezone
FROM users
WHERE timezone IS NOT NULL
GROUP BY timezone
ORDER BY COUNT(timezone) DESC
LIMIT 21"
) )
.fetch_all(&database) .fetch_all(&database)
.await .await
@ -168,27 +186,50 @@ async fn _main(tx: Sender<()>) -> Result<(), Box<dyn StdError + Send + Sync>> {
.map(|t| t.timezone.parse::<Tz>().unwrap()) .map(|t| t.timezone.parse::<Tz>().unwrap())
.collect::<Vec<Tz>>(); .collect::<Vec<Tz>>();
poise::Framework::build() poise::Framework::builder()
.token(discord_token) .token(discord_token)
.user_data_setup(move |ctx, _bot, framework| { .user_data_setup(move |ctx, _bot, framework| {
Box::pin(async move { Box::pin(async move {
register_application_commands( register_application_commands(ctx, framework, None).await.unwrap();
ctx,
framework, let kill_tx = tx.clone();
env::var("DEBUG_GUILD") let kill_recv = tx.subscribe();
.map(|inner| GuildId(inner.parse().expect("DEBUG_GUILD not valid")))
.ok(), let ctx1 = ctx.clone();
) let ctx2 = ctx.clone();
.await
.unwrap(); let pool1 = database.clone();
let pool2 = database.clone();
let run_settings = env::var("DONTRUN").unwrap_or_else(|_| "".to_string());
if !run_settings.contains("postman") {
tokio::spawn(async move {
match postman::initialize(kill_recv, ctx1, &pool1).await {
Ok(_) => {}
Err(e) => {
error!("postman exiting: {}", e);
}
};
});
} else {
warn!("Not running postman");
}
if !run_settings.contains("web") {
tokio::spawn(async move {
reminder_web::initialize(kill_tx, ctx2, pool2).await.unwrap();
});
} else {
warn!("Not running web");
}
Ok(Data { Ok(Data {
http: reqwest::Client::new(), http: reqwest::Client::new(),
database, database,
popular_timezones, popular_timezones,
recording_macros: Default::default(), recording_macros: Default::default(),
is_loop_running: AtomicBool::new(false), _broadcast: tx,
broadcast: tx,
}) })
}) })
}) })

View File

@ -1,5 +1,5 @@
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use poise::serenity::model::channel::Channel; use poise::serenity_prelude::model::channel::Channel;
use sqlx::MySqlPool; use sqlx::MySqlPool;
pub struct ChannelData { pub struct ChannelData {
@ -38,7 +38,7 @@ SELECT id, name, nudge, blacklisted, webhook_id, webhook_token, paused, paused_u
sqlx::query!( sqlx::query!(
" "
INSERT IGNORE INTO channels (channel, name, guild_id) VALUES (?, ?, (SELECT id FROM guilds WHERE guild = ?)) INSERT IGNORE INTO channels (channel, name, guild_id) VALUES (?, ?, ?)
", ",
channel_id, channel_id,
channel_name, channel_name,

View File

@ -1,7 +1,8 @@
use poise::serenity::model::{ use poise::serenity_prelude::model::{
id::GuildId, interactions::application_command::ApplicationCommandInteractionDataOption, application::interaction::application_command::CommandDataOption, id::GuildId,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{Context, Data, Error}; use crate::{Context, Data, Error};
@ -19,7 +20,7 @@ pub struct RecordedCommand<U, E> {
#[serde(default = "default_none::<U, E>")] #[serde(default = "default_none::<U, E>")]
pub action: Option<Func<U, E>>, pub action: Option<Func<U, E>>,
pub command_name: String, pub command_name: String,
pub options: Vec<ApplicationCommandInteractionDataOption>, pub options: Vec<CommandDataOption>,
} }
pub struct CommandMacro<U, E> { pub struct CommandMacro<U, E> {
@ -29,13 +30,20 @@ pub struct CommandMacro<U, E> {
pub commands: Vec<RecordedCommand<U, E>>, pub commands: Vec<RecordedCommand<U, E>>,
} }
pub struct RawCommandMacro {
pub guild_id: GuildId,
pub name: String,
pub description: Option<String>,
pub commands: Value,
}
pub async fn guild_command_macro( pub async fn guild_command_macro(
ctx: &Context<'_>, ctx: &Context<'_>,
name: &str, name: &str,
) -> Option<CommandMacro<Data, Error>> { ) -> Option<CommandMacro<Data, Error>> {
let row = sqlx::query!( let row = sqlx::query!(
" "
SELECT * FROM macro WHERE guild_id = (SELECT id FROM guilds WHERE guild = ?) AND name = ? SELECT * FROM macro WHERE guild_id = ? AND name = ?
", ",
ctx.guild_id().unwrap().0, ctx.guild_id().unwrap().0,
name name

52
src/models/guild_data.rs Normal file
View File

@ -0,0 +1,52 @@
use sqlx::MySqlPool;
use crate::GuildId;
pub struct GuildData {
pub id: u64,
pub default_channel: Option<u64>,
}
impl GuildData {
pub async fn from_guild(guild: GuildId, pool: &MySqlPool) -> Result<Self, sqlx::Error> {
let guild_id = guild.0;
if let Ok(row) = sqlx::query_as_unchecked!(
Self,
"
SELECT id, default_channel FROM guilds WHERE id = ?
",
guild_id
)
.fetch_one(pool)
.await
{
Ok(row)
} else {
sqlx::query!(
"
INSERT IGNORE INTO guilds (id) VALUES (?)
",
guild_id
)
.execute(&pool.clone())
.await?;
Ok(Self { id: guild_id, default_channel: None })
}
}
pub async fn commit_changes(&self, pool: &MySqlPool) -> Result<(), sqlx::Error> {
sqlx::query!(
"
UPDATE guilds SET default_channel = ? WHERE id = ?
",
self.default_channel,
self.id
)
.execute(pool)
.await?;
Ok(())
}
}

View File

@ -1,28 +1,28 @@
pub mod channel_data; pub mod channel_data;
pub mod command_macro; pub mod command_macro;
pub mod guild_data;
pub mod reminder; pub mod reminder;
pub mod timer; pub mod timer;
pub mod user_data; pub mod user_data;
use chrono_tz::Tz; use chrono_tz::Tz;
use poise::serenity::{async_trait, model::id::UserId}; use log::warn;
use poise::serenity_prelude::{async_trait, model::id::UserId, ChannelId};
use crate::{ use crate::{
models::{channel_data::ChannelData, user_data::UserData}, models::{channel_data::ChannelData, guild_data::GuildData, user_data::UserData},
CommandMacro, Context, Data, Error, GuildId, CommandMacro, Context, Data, Error, GuildId,
}; };
#[async_trait] #[async_trait]
pub trait CtxData { pub trait CtxData {
async fn user_data<U: Into<UserId> + Send>(&self, user_id: U) -> Result<UserData, Error>; async fn user_data<U: Into<UserId> + Send>(&self, user_id: U) -> Result<UserData, Error>;
async fn author_data(&self) -> Result<UserData, Error>; async fn author_data(&self) -> Result<UserData, Error>;
async fn timezone(&self) -> Tz; async fn timezone(&self) -> Tz;
async fn channel_data(&self) -> Result<ChannelData, Error>; async fn channel_data(&self) -> Result<ChannelData, Error>;
async fn guild_data(&self) -> Option<GuildData>;
async fn command_macros(&self) -> Result<Vec<CommandMacro<Data, Error>>, Error>; async fn command_macros(&self) -> Result<Vec<CommandMacro<Data, Error>>, Error>;
async fn default_channel(&self) -> Option<ChannelId>;
} }
#[async_trait] #[async_trait]
@ -51,24 +51,55 @@ impl CtxData for Context<'_> {
async fn command_macros(&self) -> Result<Vec<CommandMacro<Data, Error>>, Error> { async fn command_macros(&self) -> Result<Vec<CommandMacro<Data, Error>>, Error> {
self.data().command_macros(self.guild_id().unwrap()).await self.data().command_macros(self.guild_id().unwrap()).await
} }
async fn default_channel(&self) -> Option<ChannelId> {
match self.guild_id() {
Some(guild_id) => {
let guild_data = GuildData::from_guild(guild_id, &self.data().database).await;
match guild_data {
Ok(data) => data.default_channel.map(|c| ChannelId(c)),
Err(e) => {
warn!("SQL error: {:?}", e);
None
}
}
}
None => None,
}
}
async fn guild_data(&self) -> Option<GuildData> {
match self.guild_id() {
Some(guild_id) => GuildData::from_guild(guild_id, &self.data().database).await.ok(),
None => None,
}
}
} }
impl Data { impl Data {
pub(crate) async fn command_macros( pub async fn command_macros(
&self, &self,
guild_id: GuildId, guild_id: GuildId,
) -> Result<Vec<CommandMacro<Data, Error>>, Error> { ) -> Result<Vec<CommandMacro<Data, Error>>, Error> {
let rows = sqlx::query!( let rows = sqlx::query!(
"SELECT name, description, commands FROM macro WHERE guild_id = (SELECT id FROM guilds WHERE guild = ?)", "SELECT name, description, commands FROM macro WHERE guild_id = ?",
guild_id.0 guild_id.0
) )
.fetch_all(&self.database) .fetch_all(&self.database)
.await?.iter().map(|row| CommandMacro { .await?
.iter()
.map(|row| CommandMacro {
guild_id, guild_id,
name: row.name.clone(), name: row.name.clone(),
description: row.description.clone(), description: row.description.clone(),
commands: serde_json::from_str(&row.commands).unwrap(), commands: serde_json::from_str(&row.commands).unwrap(),
}).collect(); })
.collect();
Ok(rows) Ok(rows)
} }

View File

@ -2,7 +2,7 @@ use std::{collections::HashSet, fmt::Display};
use chrono::{Duration, NaiveDateTime, Utc}; use chrono::{Duration, NaiveDateTime, Utc};
use chrono_tz::Tz; use chrono_tz::Tz;
use poise::serenity::{ use poise::serenity_prelude::{
http::CacheHttp, http::CacheHttp,
model::{ model::{
channel::GuildChannel, channel::GuildChannel,
@ -233,6 +233,10 @@ impl<'a> MultiReminderBuilder<'a> {
if let Some(guild_id) = self.guild_id { if let Some(guild_id) = self.guild_id {
if guild_id.member(&self.ctx.discord(), user).await.is_err() { if guild_id.member(&self.ctx.discord(), user).await.is_err() {
Err(ReminderError::InvalidTag) Err(ReminderError::InvalidTag)
} else if self.set_by.map_or(true, |i| i != user_data.id)
&& !user_data.allowed_dm
{
Err(ReminderError::UserBlockedDm)
} else { } else {
Ok(user_data.dm_channel) Ok(user_data.dm_channel)
} }

View File

@ -7,6 +7,7 @@ pub enum ReminderError {
PastTime, PastTime,
ShortInterval, ShortInterval,
InvalidTag, InvalidTag,
UserBlockedDm,
DiscordError(String), DiscordError(String),
} }
@ -30,6 +31,9 @@ impl ToString for ReminderError {
ReminderError::InvalidTag => { ReminderError::InvalidTag => {
"Couldn't find a location by your tag. Your tag must be either a channel or a user (not a role)".to_string() "Couldn't find a location by your tag. Your tag must be either a channel or a user (not a role)".to_string()
} }
ReminderError::UserBlockedDm => {
"User has DM reminders disabled".to_string()
}
ReminderError::DiscordError(s) => format!("A Discord error occurred: **{}**", s), ReminderError::DiscordError(s) => format!("A Discord error occurred: **{}**", s),
} }
} }

View File

@ -1,4 +1,4 @@
use poise::serenity::model::id::ChannelId; use poise::serenity_prelude::model::id::ChannelId;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_repr::*; use serde_repr::*;

View File

@ -8,9 +8,9 @@ use std::hash::{Hash, Hasher};
use chrono::{NaiveDateTime, TimeZone}; use chrono::{NaiveDateTime, TimeZone};
use chrono_tz::Tz; use chrono_tz::Tz;
use poise::{ use poise::serenity_prelude::{
serenity::model::id::{ChannelId, GuildId, UserId}, model::id::{ChannelId, GuildId, UserId},
serenity_prelude::Cache, Cache,
}; };
use sqlx::Executor; use sqlx::Executor;
@ -245,7 +245,7 @@ LEFT JOIN
ON ON
reminders.set_by = users.id reminders.set_by = users.id
WHERE WHERE
channels.guild_id = (SELECT id FROM guilds WHERE guild = ?) channels.guild_id = ?
", ",
guild_id.as_u64() guild_id.as_u64()
) )

View File

@ -1,6 +1,6 @@
use chrono_tz::Tz; use chrono_tz::Tz;
use log::error; use log::error;
use poise::serenity::{http::CacheHttp, model::id::UserId}; use poise::serenity_prelude::{http::CacheHttp, model::id::UserId};
use sqlx::MySqlPool; use sqlx::MySqlPool;
use crate::consts::LOCAL_TIMEZONE; use crate::consts::LOCAL_TIMEZONE;
@ -10,6 +10,7 @@ pub struct UserData {
pub user: u64, pub user: u64,
pub dm_channel: u32, pub dm_channel: u32,
pub timezone: String, pub timezone: String,
pub allowed_dm: bool,
} }
impl UserData { impl UserData {
@ -21,7 +22,7 @@ impl UserData {
match sqlx::query!( match sqlx::query!(
" "
SELECT timezone FROM users WHERE user = ? SELECT IFNULL(timezone, 'UTC') AS timezone FROM users WHERE user = ?
", ",
user_id user_id
) )
@ -46,7 +47,7 @@ SELECT timezone FROM users WHERE user = ?
match sqlx::query_as_unchecked!( match sqlx::query_as_unchecked!(
Self, Self,
" "
SELECT id, user, dm_channel, IF(timezone IS NULL, ?, timezone) AS timezone FROM users WHERE user = ? SELECT id, user, dm_channel, IF(timezone IS NULL, ?, timezone) AS timezone, allowed_dm FROM users WHERE user = ?
", ",
*LOCAL_TIMEZONE, *LOCAL_TIMEZONE,
user_id.0 user_id.0
@ -83,7 +84,7 @@ INSERT INTO users (name, user, dm_channel, timezone) VALUES ('', ?, (SELECT id F
Ok(sqlx::query_as_unchecked!( Ok(sqlx::query_as_unchecked!(
Self, Self,
" "
SELECT id, user, dm_channel, timezone FROM users WHERE user = ? SELECT id, user, dm_channel, timezone, allowed_dm FROM users WHERE user = ?
", ",
user_id.0 user_id.0
) )
@ -102,9 +103,10 @@ SELECT id, user, dm_channel, timezone FROM users WHERE user = ?
pub async fn commit_changes(&self, pool: &MySqlPool) { pub async fn commit_changes(&self, pool: &MySqlPool) {
sqlx::query!( sqlx::query!(
" "
UPDATE users SET timezone = ? WHERE id = ? UPDATE users SET timezone = ?, allowed_dm = ? WHERE id = ?
", ",
self.timezone, self.timezone,
self.allowed_dm,
self.id self.id
) )
.execute(pool) .execute(pool)

View File

@ -1,10 +1,11 @@
use poise::{ use poise::{
serenity::{ serenity_prelude as serenity,
serenity_prelude::{
builder::CreateApplicationCommands, builder::CreateApplicationCommands,
http::CacheHttp, http::CacheHttp,
interaction::MessageFlags,
model::id::{GuildId, UserId}, model::id::{GuildId, UserId},
}, },
serenity_prelude as serenity,
}; };
use crate::{ use crate::{
@ -13,10 +14,10 @@ use crate::{
}; };
pub async fn register_application_commands( pub async fn register_application_commands(
ctx: &poise::serenity::client::Context, ctx: &serenity::Context,
framework: &poise::Framework<Data, Error>, framework: &poise::Framework<Data, Error>,
guild_id: Option<GuildId>, guild_id: Option<GuildId>,
) -> Result<(), poise::serenity::Error> { ) -> Result<(), serenity::Error> {
let mut commands_builder = CreateApplicationCommands::default(); let mut commands_builder = CreateApplicationCommands::default();
let commands = &framework.options().commands; let commands = &framework.options().commands;
for command in commands { for command in commands {
@ -27,7 +28,7 @@ pub async fn register_application_commands(
commands_builder.add_application_command(context_menu_command); commands_builder.add_application_command(context_menu_command);
} }
} }
let commands_builder = poise::serenity::json::Value::Array(commands_builder.0); let commands_builder = poise::serenity_prelude::json::Value::Array(commands_builder.0);
if let Some(guild_id) = guild_id { if let Some(guild_id) = guild_id {
ctx.http.create_guild_application_commands(guild_id.0, &commands_builder).await?; ctx.http.create_guild_application_commands(guild_id.0, &commands_builder).await?;
@ -102,6 +103,6 @@ pub fn send_as_initial_response(
}); });
} }
if ephemeral { if ephemeral {
f.flags(serenity::InteractionApplicationCommandCallbackDataFlags::EPHEMERAL); f.flags(MessageFlags::EPHEMERAL);
} }
} }

View File

@ -12,10 +12,10 @@ oauth2 = "4"
log = "0.4" log = "0.4"
reqwest = "0.11" reqwest = "0.11"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" sqlx = { version = "0.6", features = ["runtime-tokio-rustls", "macros", "mysql", "chrono", "json"] }
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "macros", "mysql", "chrono", "json"] }
chrono = "0.4" chrono = "0.4"
chrono-tz = "0.5" chrono-tz = "0.5"
lazy_static = "1.4.0" lazy_static = "1.4.0"
rand = "0.7" rand = "0.7"
base64 = "0.13" base64 = "0.13"
csv = "1.1"

View File

@ -26,12 +26,8 @@ use serenity::model::prelude::AttachmentType;
lazy_static! { lazy_static! {
pub static ref DEFAULT_AVATAR: AttachmentType<'static> = ( pub static ref DEFAULT_AVATAR: AttachmentType<'static> = (
include_bytes!(concat!( include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../assets/webhook.jpg")) as &[u8],
env!("CARGO_MANIFEST_DIR"), "webhook.jpg",
"/../assets/",
env!("WEBHOOK_AVATAR", "WEBHOOK_AVATAR not provided for compilation")
)) as &[u8],
env!("WEBHOOK_AVATAR"),
) )
.into(); .into();
pub static ref SUBSCRIPTION_ROLES: HashSet<u64> = HashSet::from_iter( pub static ref SUBSCRIPTION_ROLES: HashSet<u64> = HashSet::from_iter(

View File

@ -146,10 +146,15 @@ pub async fn initialize(
routes::dashboard::guild::get_reminder_templates, routes::dashboard::guild::get_reminder_templates,
routes::dashboard::guild::create_reminder_template, routes::dashboard::guild::create_reminder_template,
routes::dashboard::guild::delete_reminder_template, routes::dashboard::guild::delete_reminder_template,
routes::dashboard::guild::create_reminder, routes::dashboard::guild::create_guild_reminder,
routes::dashboard::guild::get_reminders, routes::dashboard::guild::get_reminders,
routes::dashboard::guild::edit_reminder, routes::dashboard::guild::edit_reminder,
routes::dashboard::guild::delete_reminder, routes::dashboard::guild::delete_reminder,
routes::dashboard::export::export_reminders,
routes::dashboard::export::export_reminder_templates,
routes::dashboard::export::export_todos,
routes::dashboard::export::import_reminders,
routes::dashboard::export::import_todos,
], ],
) )
.launch() .launch()

View File

@ -1,7 +1,7 @@
macro_rules! check_length { macro_rules! check_length {
($max:ident, $field:expr) => { ($max:ident, $field:expr) => {
if $field.len() > $max { if $field.len() > $max {
return json!({ "error": format!("{} exceeded", stringify!($max)) }); return Err(json!({ "error": format!("{} exceeded", stringify!($max)) }));
} }
}; };
($max:ident, $field:expr, $($fields:expr),+) => { ($max:ident, $field:expr, $($fields:expr),+) => {
@ -25,7 +25,7 @@ macro_rules! check_length_opt {
macro_rules! check_url { macro_rules! check_url {
($field:expr) => { ($field:expr) => {
if !($field.starts_with("http://") || $field.starts_with("https://")) { if !($field.starts_with("http://") || $field.starts_with("https://")) {
return json!({ "error": "URL invalid" }); return Err(json!({ "error": "URL invalid" }));
} }
}; };
($field:expr, $($fields:expr),+) => { ($field:expr, $($fields:expr),+) => {
@ -60,7 +60,7 @@ macro_rules! check_authorization {
match member { match member {
Err(_) => { Err(_) => {
return json!({"error": "User not in guild"}) return Err(json!({"error": "User not in guild"}));
} }
Ok(_) => {} Ok(_) => {}
@ -68,13 +68,13 @@ macro_rules! check_authorization {
} }
None => { None => {
return json!({"error": "Bot not in guild"}) return Err(json!({"error": "Bot not in guild"}));
} }
} }
} }
None => { None => {
return json!({"error": "User not authorized"}); return Err(json!({"error": "User not authorized"}));
} }
} }
} }
@ -117,3 +117,9 @@ macro_rules! update_field {
update_field!($pool, $error, $reminder.[$($fields),+]); update_field!($pool, $error, $reminder.[$($fields),+]);
}; };
} }
macro_rules! json_err {
($message:expr) => {
Err(json!({ "error": $message }))
};
}

View File

@ -0,0 +1,430 @@
use csv::{QuoteStyle, WriterBuilder};
use rocket::{
http::CookieJar,
serde::json::{json, serde_json, Json},
State,
};
use serenity::{
client::Context,
model::id::{ChannelId, GuildId},
};
use sqlx::{MySql, Pool};
use crate::routes::dashboard::{
create_reminder, generate_uid, ImportBody, JsonResult, Reminder, ReminderCsv,
ReminderTemplateCsv, TodoCsv,
};
#[get("/api/guild/<id>/export/reminders")]
pub async fn export_reminders(
id: u64,
cookies: &CookieJar<'_>,
ctx: &State<Context>,
pool: &State<Pool<MySql>>,
) -> JsonResult {
check_authorization!(cookies, ctx.inner(), id);
let mut csv_writer = WriterBuilder::new().quote_style(QuoteStyle::Always).from_writer(vec![]);
let channels_res = GuildId(id).channels(&ctx.inner()).await;
match channels_res {
Ok(channels) => {
let channels = channels
.keys()
.into_iter()
.map(|k| k.as_u64().to_string())
.collect::<Vec<String>>()
.join(",");
let result = sqlx::query_as_unchecked!(
ReminderCsv,
"SELECT
reminders.attachment,
reminders.attachment_name,
reminders.avatar,
CONCAT('#', channels.channel) AS channel,
reminders.content,
reminders.embed_author,
reminders.embed_author_url,
reminders.embed_color,
reminders.embed_description,
reminders.embed_footer,
reminders.embed_footer_url,
reminders.embed_image_url,
reminders.embed_thumbnail_url,
reminders.embed_title,
reminders.embed_fields,
reminders.enabled,
reminders.expires,
reminders.interval_seconds,
reminders.interval_months,
reminders.name,
reminders.restartable,
reminders.tts,
reminders.username,
reminders.utc_time
FROM reminders
LEFT JOIN channels ON channels.id = reminders.channel_id
WHERE FIND_IN_SET(channels.channel, ?)",
channels
)
.fetch_all(pool.inner())
.await;
match result {
Ok(reminders) => {
reminders.iter().for_each(|reminder| {
csv_writer.serialize(reminder).unwrap();
});
match csv_writer.into_inner() {
Ok(inner) => match String::from_utf8(inner) {
Ok(encoded) => Ok(json!({ "body": encoded })),
Err(e) => {
warn!("Failed to write UTF-8: {:?}", e);
Err(json!({"error": "Failed to write UTF-8"}))
}
},
Err(e) => {
warn!("Failed to extract CSV: {:?}", e);
Err(json!({"error": "Failed to extract CSV"}))
}
}
}
Err(e) => {
warn!("Failed to complete SQL query: {:?}", e);
Err(json!({"error": "Failed to query reminders"}))
}
}
}
Err(e) => {
warn!("Could not fetch channels from {}: {:?}", id, e);
Err(json!({"error": "Failed to get guild channels"}))
}
}
}
#[put("/api/guild/<id>/export/reminders", data = "<body>")]
pub async fn import_reminders(
id: u64,
cookies: &CookieJar<'_>,
body: Json<ImportBody>,
ctx: &State<Context>,
pool: &State<Pool<MySql>>,
) -> JsonResult {
check_authorization!(cookies, ctx.inner(), id);
let user_id =
cookies.get_private("userid").map(|c| c.value().parse::<u64>().ok()).flatten().unwrap();
match base64::decode(&body.body) {
Ok(body) => {
let mut reader = csv::Reader::from_reader(body.as_slice());
for result in reader.deserialize::<ReminderCsv>() {
match result {
Ok(record) => {
let channel_id = record.channel.split_at(1).1;
match channel_id.parse::<u64>() {
Ok(channel_id) => {
let reminder = Reminder {
attachment: record.attachment,
attachment_name: record.attachment_name,
avatar: record.avatar,
channel: channel_id,
content: record.content,
embed_author: record.embed_author,
embed_author_url: record.embed_author_url,
embed_color: record.embed_color,
embed_description: record.embed_description,
embed_footer: record.embed_footer,
embed_footer_url: record.embed_footer_url,
embed_image_url: record.embed_image_url,
embed_thumbnail_url: record.embed_thumbnail_url,
embed_title: record.embed_title,
embed_fields: record
.embed_fields
.map(|s| serde_json::from_str(&s).ok())
.flatten(),
enabled: record.enabled,
expires: record.expires,
interval_seconds: record.interval_seconds,
interval_months: record.interval_months,
name: record.name,
restartable: record.restartable,
tts: record.tts,
uid: generate_uid(),
username: record.username,
utc_time: record.utc_time,
};
create_reminder(
ctx.inner(),
pool.inner(),
GuildId(id),
UserId(user_id),
reminder,
)
.await?;
}
Err(_) => {
return json_err!(format!(
"Failed to parse channel {}",
channel_id
));
}
}
}
Err(e) => {
warn!("Couldn't deserialize CSV row: {:?}", e);
return json_err!("Deserialize error. Aborted");
}
}
}
Ok(json!({}))
}
Err(_) => {
json_err!("Malformed base64")
}
}
}
#[get("/api/guild/<id>/export/todos")]
pub async fn export_todos(
id: u64,
cookies: &CookieJar<'_>,
ctx: &State<Context>,
pool: &State<Pool<MySql>>,
) -> JsonResult {
check_authorization!(cookies, ctx.inner(), id);
let mut csv_writer = WriterBuilder::new().quote_style(QuoteStyle::Always).from_writer(vec![]);
match sqlx::query_as_unchecked!(
TodoCsv,
"SELECT value, CONCAT('#', channels.channel) AS channel_id FROM todos
LEFT JOIN channels ON todos.channel_id = channels.id
INNER JOIN guilds ON todos.guild_id = guilds.id
WHERE guilds.guild = ?",
id
)
.fetch_all(pool.inner())
.await
{
Ok(todos) => {
todos.iter().for_each(|todo| {
csv_writer.serialize(todo).unwrap();
});
match csv_writer.into_inner() {
Ok(inner) => match String::from_utf8(inner) {
Ok(encoded) => Ok(json!({ "body": encoded })),
Err(e) => {
warn!("Failed to write UTF-8: {:?}", e);
json_err!("Failed to write UTF-8")
}
},
Err(e) => {
warn!("Failed to extract CSV: {:?}", e);
json_err!("Failed to extract CSV")
}
}
}
Err(e) => {
warn!("Could not fetch templates from {}: {:?}", id, e);
json_err!("Failed to query templates")
}
}
}
#[put("/api/guild/<id>/export/todos", data = "<body>")]
pub async fn import_todos(
id: u64,
cookies: &CookieJar<'_>,
body: Json<ImportBody>,
ctx: &State<Context>,
pool: &State<Pool<MySql>>,
) -> JsonResult {
check_authorization!(cookies, ctx.inner(), id);
let channels_res = GuildId(id).channels(&ctx.inner()).await;
match channels_res {
Ok(channels) => match base64::decode(&body.body) {
Ok(body) => {
let mut reader = csv::Reader::from_reader(body.as_slice());
let query_placeholder = "(?, (SELECT id FROM channels WHERE channel = ?), (SELECT id FROM guilds WHERE guild = ?))";
let mut query_params = vec![];
for result in reader.deserialize::<TodoCsv>() {
match result {
Ok(record) => match record.channel_id {
Some(channel_id) => {
let channel_id = channel_id.split_at(1).1;
match channel_id.parse::<u64>() {
Ok(channel_id) => {
if channels.contains_key(&ChannelId(channel_id)) {
query_params.push((record.value, Some(channel_id), id));
} else {
return json_err!(format!(
"Invalid channel ID {}",
channel_id
));
}
}
Err(_) => {
return json_err!(format!(
"Invalid channel ID {}",
channel_id
));
}
}
}
None => {
query_params.push((record.value, None, id));
}
},
Err(e) => {
warn!("Couldn't deserialize CSV row: {:?}", e);
return json_err!("Deserialize error. Aborted");
}
}
}
let _ = sqlx::query!(
"DELETE FROM todos WHERE guild_id = (SELECT id FROM guilds WHERE guild = ?)",
id
)
.execute(pool.inner())
.await;
let query_str = format!(
"INSERT INTO todos (value, channel_id, guild_id) VALUES {}",
vec![query_placeholder].repeat(query_params.len()).join(",")
);
let mut query = sqlx::query(&query_str);
for param in query_params {
query = query.bind(param.0).bind(param.1).bind(param.2);
}
let res = query.execute(pool.inner()).await;
match res {
Ok(_) => Ok(json!({})),
Err(e) => {
warn!("Couldn't execute todo query: {:?}", e);
json_err!("An unexpected error occured.")
}
}
}
Err(_) => {
json_err!("Malformed base64")
}
},
Err(e) => {
warn!("Couldn't fetch channels for guild {}: {:?}", id, e);
json_err!("Couldn't fetch channels.")
}
}
}
#[get("/api/guild/<id>/export/reminder_templates")]
pub async fn export_reminder_templates(
id: u64,
cookies: &CookieJar<'_>,
ctx: &State<Context>,
pool: &State<Pool<MySql>>,
) -> JsonResult {
check_authorization!(cookies, ctx.inner(), id);
let mut csv_writer = WriterBuilder::new().quote_style(QuoteStyle::Always).from_writer(vec![]);
match sqlx::query_as_unchecked!(
ReminderTemplateCsv,
"SELECT
name,
attachment,
attachment_name,
avatar,
content,
embed_author,
embed_author_url,
embed_color,
embed_description,
embed_footer,
embed_footer_url,
embed_image_url,
embed_thumbnail_url,
embed_title,
embed_fields,
tts,
username
FROM reminder_template WHERE guild_id = (SELECT id FROM guilds WHERE guild = ?)",
id
)
.fetch_all(pool.inner())
.await
{
Ok(templates) => {
templates.iter().for_each(|template| {
csv_writer.serialize(template).unwrap();
});
match csv_writer.into_inner() {
Ok(inner) => match String::from_utf8(inner) {
Ok(encoded) => Ok(json!({ "body": encoded })),
Err(e) => {
warn!("Failed to write UTF-8: {:?}", e);
json_err!("Failed to write UTF-8")
}
},
Err(e) => {
warn!("Failed to extract CSV: {:?}", e);
json_err!("Failed to extract CSV")
}
}
}
Err(e) => {
warn!("Could not fetch templates from {}: {:?}", id, e);
json_err!("Failed to query templates")
}
}
}

View File

@ -1,10 +1,8 @@
use std::env; use std::env;
use base64;
use chrono::Utc;
use rocket::{ use rocket::{
http::CookieJar, http::CookieJar,
serde::json::{json, Json, Value as JsonValue}, serde::json::{json, Json},
State, State,
}; };
use serde::Serialize; use serde::Serialize;
@ -18,16 +16,14 @@ use serenity::{
use sqlx::{MySql, Pool}; use sqlx::{MySql, Pool};
use crate::{ use crate::{
check_guild_subscription, check_subscription,
consts::{ consts::{
DAY, MAX_CONTENT_LENGTH, MAX_EMBED_AUTHOR_LENGTH, MAX_EMBED_DESCRIPTION_LENGTH, MAX_CONTENT_LENGTH, MAX_EMBED_AUTHOR_LENGTH, MAX_EMBED_DESCRIPTION_LENGTH,
MAX_EMBED_FIELDS, MAX_EMBED_FIELD_TITLE_LENGTH, MAX_EMBED_FIELD_VALUE_LENGTH, MAX_EMBED_FIELDS, MAX_EMBED_FIELD_TITLE_LENGTH, MAX_EMBED_FIELD_VALUE_LENGTH,
MAX_EMBED_FOOTER_LENGTH, MAX_EMBED_TITLE_LENGTH, MAX_URL_LENGTH, MAX_USERNAME_LENGTH, MAX_EMBED_FOOTER_LENGTH, MAX_EMBED_TITLE_LENGTH, MAX_URL_LENGTH, MAX_USERNAME_LENGTH,
MIN_INTERVAL,
}, },
routes::dashboard::{ routes::dashboard::{
create_database_channel, generate_uid, name_default, template_name_default, DeleteReminder, create_database_channel, create_reminder, template_name_default, DeleteReminder,
DeleteReminderTemplate, PatchReminder, Reminder, ReminderTemplate, DeleteReminderTemplate, JsonResult, PatchReminder, Reminder, ReminderTemplate,
}, },
}; };
@ -44,7 +40,7 @@ pub async fn get_guild_patreon(
id: u64, id: u64,
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
ctx: &State<Context>, ctx: &State<Context>,
) -> JsonValue { ) -> JsonResult {
check_authorization!(cookies, ctx.inner(), id); check_authorization!(cookies, ctx.inner(), id);
match GuildId(id).to_guild_cached(ctx.inner()) { match GuildId(id).to_guild_cached(ctx.inner()) {
@ -59,12 +55,10 @@ pub async fn get_guild_patreon(
.contains(&RoleId(env::var("PATREON_ROLE_ID").unwrap().parse().unwrap())) .contains(&RoleId(env::var("PATREON_ROLE_ID").unwrap().parse().unwrap()))
}); });
json!({ "patreon": patreon }) Ok(json!({ "patreon": patreon }))
} }
None => { None => json_err!("Bot not in guild"),
json!({"error": "Bot not in guild"})
}
} }
} }
@ -73,7 +67,7 @@ pub async fn get_guild_channels(
id: u64, id: u64,
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
ctx: &State<Context>, ctx: &State<Context>,
) -> JsonValue { ) -> JsonResult {
check_authorization!(cookies, ctx.inner(), id); check_authorization!(cookies, ctx.inner(), id);
match GuildId(id).to_guild_cached(ctx.inner()) { match GuildId(id).to_guild_cached(ctx.inner()) {
@ -97,12 +91,10 @@ pub async fn get_guild_channels(
}) })
.collect::<Vec<ChannelInfo>>(); .collect::<Vec<ChannelInfo>>();
json!(channel_info) Ok(json!(channel_info))
} }
None => { None => json_err!("Bot not in guild"),
json!({"error": "Bot not in guild"})
}
} }
} }
@ -113,7 +105,7 @@ struct RoleInfo {
} }
#[get("/api/guild/<id>/roles")] #[get("/api/guild/<id>/roles")]
pub async fn get_guild_roles(id: u64, cookies: &CookieJar<'_>, ctx: &State<Context>) -> JsonValue { pub async fn get_guild_roles(id: u64, cookies: &CookieJar<'_>, ctx: &State<Context>) -> JsonResult {
check_authorization!(cookies, ctx.inner(), id); check_authorization!(cookies, ctx.inner(), id);
let roles_res = ctx.cache.guild_roles(id); let roles_res = ctx.cache.guild_roles(id);
@ -125,12 +117,12 @@ pub async fn get_guild_roles(id: u64, cookies: &CookieJar<'_>, ctx: &State<Conte
.map(|(_, r)| RoleInfo { id: r.id.to_string(), name: r.name.to_string() }) .map(|(_, r)| RoleInfo { id: r.id.to_string(), name: r.name.to_string() })
.collect::<Vec<RoleInfo>>(); .collect::<Vec<RoleInfo>>();
json!(roles) Ok(json!(roles))
} }
None => { None => {
warn!("Could not fetch roles from {}", id); warn!("Could not fetch roles from {}", id);
json!({"error": "Could not get roles"}) json_err!("Could not get roles")
} }
} }
} }
@ -141,7 +133,7 @@ pub async fn get_reminder_templates(
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
ctx: &State<Context>, ctx: &State<Context>,
pool: &State<Pool<MySql>>, pool: &State<Pool<MySql>>,
) -> JsonValue { ) -> JsonResult {
check_authorization!(cookies, ctx.inner(), id); check_authorization!(cookies, ctx.inner(), id);
match sqlx::query_as_unchecked!( match sqlx::query_as_unchecked!(
@ -152,13 +144,11 @@ pub async fn get_reminder_templates(
.fetch_all(pool.inner()) .fetch_all(pool.inner())
.await .await
{ {
Ok(templates) => { Ok(templates) => Ok(json!(templates)),
json!(templates)
}
Err(e) => { Err(e) => {
warn!("Could not fetch templates from {}: {:?}", id, e); warn!("Could not fetch templates from {}: {:?}", id, e);
json!({"error": "Could not get templates"}) json_err!("Could not get templates")
} }
} }
} }
@ -170,7 +160,7 @@ pub async fn create_reminder_template(
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
ctx: &State<Context>, ctx: &State<Context>,
pool: &State<Pool<MySql>>, pool: &State<Pool<MySql>>,
) -> JsonValue { ) -> JsonResult {
check_authorization!(cookies, ctx.inner(), id); check_authorization!(cookies, ctx.inner(), id);
// validate lengths // validate lengths
@ -254,12 +244,12 @@ pub async fn create_reminder_template(
.await .await
{ {
Ok(_) => { Ok(_) => {
json!({}) Ok(json!({}))
} }
Err(e) => { Err(e) => {
warn!("Could not fetch templates from {}: {:?}", id, e); warn!("Could not fetch templates from {}: {:?}", id, e);
json!({"error": "Could not get templates"}) json_err!("Could not get templates")
} }
} }
} }
@ -271,7 +261,7 @@ pub async fn delete_reminder_template(
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
ctx: &State<Context>, ctx: &State<Context>,
pool: &State<Pool<MySql>>, pool: &State<Pool<MySql>>,
) -> JsonValue { ) -> JsonResult {
check_authorization!(cookies, ctx.inner(), id); check_authorization!(cookies, ctx.inner(), id);
match sqlx::query!( match sqlx::query!(
@ -282,230 +272,41 @@ pub async fn delete_reminder_template(
.await .await
{ {
Ok(_) => { Ok(_) => {
json!({}) Ok(json!({}))
} }
Err(e) => { Err(e) => {
warn!("Could not delete template from {}: {:?}", id, e); warn!("Could not delete template from {}: {:?}", id, e);
json!({"error": "Could not delete template"}) json_err!("Could not delete template")
} }
} }
} }
#[post("/api/guild/<id>/reminders", data = "<reminder>")] #[post("/api/guild/<id>/reminders", data = "<reminder>")]
pub async fn create_reminder( pub async fn create_guild_reminder(
id: u64, id: u64,
reminder: Json<Reminder>, reminder: Json<Reminder>,
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
serenity_context: &State<Context>, serenity_context: &State<Context>,
pool: &State<Pool<MySql>>, pool: &State<Pool<MySql>>,
) -> JsonValue { ) -> JsonResult {
check_authorization!(cookies, serenity_context.inner(), id); check_authorization!(cookies, serenity_context.inner(), id);
let user_id = let user_id =
cookies.get_private("userid").map(|c| c.value().parse::<u64>().ok()).flatten().unwrap(); cookies.get_private("userid").map(|c| c.value().parse::<u64>().ok()).flatten().unwrap();
// validate channel create_reminder(
let channel = ChannelId(reminder.channel).to_channel_cached(&serenity_context.inner());
let channel_exists = channel.is_some();
let channel_matches_guild =
channel.map_or(false, |c| c.guild().map_or(false, |c| c.guild_id.0 == id));
if !channel_matches_guild || !channel_exists {
warn!(
"Error in `create_reminder`: channel {} not found for guild {} (channel exists: {})",
reminder.channel, id, channel_exists
);
return json!({"error": "Channel not found"});
}
let channel = create_database_channel(
serenity_context.inner(), serenity_context.inner(),
ChannelId(reminder.channel),
pool.inner(), pool.inner(),
GuildId(id),
UserId(user_id),
reminder.into_inner(),
) )
.await;
if let Err(e) = channel {
warn!("`create_database_channel` returned an error code: {:?}", e);
return json!({"error": "Failed to configure channel for reminders. Please check the bot permissions"});
}
let channel = channel.unwrap();
// validate lengths
check_length!(MAX_CONTENT_LENGTH, reminder.content);
check_length!(MAX_EMBED_DESCRIPTION_LENGTH, reminder.embed_description);
check_length!(MAX_EMBED_TITLE_LENGTH, reminder.embed_title);
check_length!(MAX_EMBED_AUTHOR_LENGTH, reminder.embed_author);
check_length!(MAX_EMBED_FOOTER_LENGTH, reminder.embed_footer);
check_length_opt!(MAX_EMBED_FIELDS, reminder.embed_fields);
if let Some(fields) = &reminder.embed_fields {
for field in &fields.0 {
check_length!(MAX_EMBED_FIELD_VALUE_LENGTH, field.value);
check_length!(MAX_EMBED_FIELD_TITLE_LENGTH, field.title);
}
}
check_length_opt!(MAX_USERNAME_LENGTH, reminder.username);
check_length_opt!(
MAX_URL_LENGTH,
reminder.embed_footer_url,
reminder.embed_thumbnail_url,
reminder.embed_author_url,
reminder.embed_image_url,
reminder.avatar
);
// validate urls
check_url_opt!(
reminder.embed_footer_url,
reminder.embed_thumbnail_url,
reminder.embed_author_url,
reminder.embed_image_url,
reminder.avatar
);
// validate time and interval
if reminder.utc_time < Utc::now().naive_utc() {
return json!({"error": "Time must be in the future"});
}
if reminder.interval_seconds.is_some() || reminder.interval_months.is_some() {
if reminder.interval_months.unwrap_or(0) * 30 * DAY as u32
+ reminder.interval_seconds.unwrap_or(0)
< *MIN_INTERVAL
{
return json!({"error": "Interval too short"});
}
}
// check patreon if necessary
if reminder.interval_seconds.is_some() || reminder.interval_months.is_some() {
if !check_guild_subscription(serenity_context.inner(), GuildId(id)).await
&& !check_subscription(serenity_context.inner(), user_id).await
{
return json!({"error": "Patreon is required to set intervals"});
}
}
// base64 decode error dropped here
let attachment_data = reminder.attachment.as_ref().map(|s| base64::decode(s).ok()).flatten();
let name = if reminder.name.is_empty() { name_default() } else { reminder.name.clone() };
let new_uid = generate_uid();
// write to db
match sqlx::query!(
"INSERT INTO reminders (
uid,
attachment,
attachment_name,
channel_id,
avatar,
content,
embed_author,
embed_author_url,
embed_color,
embed_description,
embed_footer,
embed_footer_url,
embed_image_url,
embed_thumbnail_url,
embed_title,
embed_fields,
enabled,
expires,
interval_seconds,
interval_months,
name,
restartable,
tts,
username,
`utc_time`
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
new_uid,
attachment_data,
reminder.attachment_name,
channel,
reminder.avatar,
reminder.content,
reminder.embed_author,
reminder.embed_author_url,
reminder.embed_color,
reminder.embed_description,
reminder.embed_footer,
reminder.embed_footer_url,
reminder.embed_image_url,
reminder.embed_thumbnail_url,
reminder.embed_title,
reminder.embed_fields,
reminder.enabled,
reminder.expires,
reminder.interval_seconds,
reminder.interval_months,
name,
reminder.restartable,
reminder.tts,
reminder.username,
reminder.utc_time,
)
.execute(pool.inner())
.await .await
{
Ok(_) => sqlx::query_as_unchecked!(
Reminder,
"SELECT
reminders.attachment,
reminders.attachment_name,
reminders.avatar,
channels.channel,
reminders.content,
reminders.embed_author,
reminders.embed_author_url,
reminders.embed_color,
reminders.embed_description,
reminders.embed_footer,
reminders.embed_footer_url,
reminders.embed_image_url,
reminders.embed_thumbnail_url,
reminders.embed_title,
reminders.embed_fields,
reminders.enabled,
reminders.expires,
reminders.interval_seconds,
reminders.interval_months,
reminders.name,
reminders.restartable,
reminders.tts,
reminders.uid,
reminders.username,
reminders.utc_time
FROM reminders
LEFT JOIN channels ON channels.id = reminders.channel_id
WHERE uid = ?",
new_uid
)
.fetch_one(pool.inner())
.await
.map(|r| json!(r))
.unwrap_or_else(|e| {
warn!("Failed to complete SQL query: {:?}", e);
json!({"error": "Could not load reminder"})
}),
Err(e) => {
warn!("Error in `create_reminder`: Could not execute query: {:?}", e);
json!({"error": "Unknown error"})
}
}
} }
#[get("/api/guild/<id>/reminders")] #[get("/api/guild/<id>/reminders")]
pub async fn get_reminders(id: u64, ctx: &State<Context>, pool: &State<Pool<MySql>>) -> JsonValue { pub async fn get_reminders(id: u64, ctx: &State<Context>, pool: &State<Pool<MySql>>) -> JsonResult {
let channels_res = GuildId(id).channels(&ctx.inner()).await; let channels_res = GuildId(id).channels(&ctx.inner()).await;
match channels_res { match channels_res {
@ -552,17 +353,17 @@ pub async fn get_reminders(id: u64, ctx: &State<Context>, pool: &State<Pool<MySq
) )
.fetch_all(pool.inner()) .fetch_all(pool.inner())
.await .await
.map(|r| json!(r)) .map(|r| Ok(json!(r)))
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
warn!("Failed to complete SQL query: {:?}", e); warn!("Failed to complete SQL query: {:?}", e);
json!({"error": "Could not load reminders"}) json_err!("Could not load reminders")
}) })
} }
Err(e) => { Err(e) => {
warn!("Could not fetch channels from {}: {:?}", id, e); warn!("Could not fetch channels from {}: {:?}", id, e);
json!([]) Ok(json!([]))
} }
} }
} }
@ -573,7 +374,7 @@ pub async fn edit_reminder(
reminder: Json<PatchReminder>, reminder: Json<PatchReminder>,
serenity_context: &State<Context>, serenity_context: &State<Context>,
pool: &State<Pool<MySql>>, pool: &State<Pool<MySql>>,
) -> JsonValue { ) -> JsonResult {
let mut error = vec![]; let mut error = vec![];
update_field!(pool.inner(), error, reminder.[ update_field!(pool.inner(), error, reminder.[
@ -614,7 +415,7 @@ pub async fn edit_reminder(
reminder.channel, id reminder.channel, id
); );
return json!({"error": "Channel not found"}); return Err(json!({"error": "Channel not found"}));
} }
let channel = create_database_channel( let channel = create_database_channel(
@ -627,7 +428,9 @@ pub async fn edit_reminder(
if let Err(e) = channel { if let Err(e) = channel {
warn!("`create_database_channel` returned an error code: {:?}", e); warn!("`create_database_channel` returned an error code: {:?}", e);
return json!({"error": "Failed to configure channel for reminders. Please check the bot permissions"}); return Err(
json!({"error": "Failed to configure channel for reminders. Please check the bot permissions"}),
);
} }
let channel = channel.unwrap(); let channel = channel.unwrap();
@ -655,7 +458,7 @@ pub async fn edit_reminder(
reminder.channel, id reminder.channel, id
); );
return json!({"error": "Channel not found"}); return Err(json!({"error": "Channel not found"}));
} }
} }
} }
@ -695,12 +498,12 @@ pub async fn edit_reminder(
.fetch_one(pool.inner()) .fetch_one(pool.inner())
.await .await
{ {
Ok(reminder) => json!({"reminder": reminder, "errors": error}), Ok(reminder) => Ok(json!({"reminder": reminder, "errors": error})),
Err(e) => { Err(e) => {
warn!("Error exiting `edit_reminder': {:?}", e); warn!("Error exiting `edit_reminder': {:?}", e);
json!({"reminder": Option::<Reminder>::None, "errors": vec!["Unknown error"]}) Err(json!({"reminder": Option::<Reminder>::None, "errors": vec!["Unknown error"]}))
} }
} }
} }
@ -709,19 +512,17 @@ pub async fn edit_reminder(
pub async fn delete_reminder( pub async fn delete_reminder(
reminder: Json<DeleteReminder>, reminder: Json<DeleteReminder>,
pool: &State<Pool<MySql>>, pool: &State<Pool<MySql>>,
) -> JsonValue { ) -> JsonResult {
match sqlx::query!("DELETE FROM reminders WHERE uid = ?", reminder.uid) match sqlx::query!("DELETE FROM reminders WHERE uid = ?", reminder.uid)
.execute(pool.inner()) .execute(pool.inner())
.await .await
{ {
Ok(_) => { Ok(_) => Ok(json!({})),
json!({})
}
Err(e) => { Err(e) => {
warn!("Error in `delete_reminder`: {:?}", e); warn!("Error in `delete_reminder`: {:?}", e);
json!({"error": "Could not delete reminder"}) Err(json!({"error": "Could not delete reminder"}))
} }
} }
} }

View File

@ -1,21 +1,37 @@
use std::collections::HashMap; use std::collections::HashMap;
use chrono::naive::NaiveDateTime; use chrono::{naive::NaiveDateTime, Utc};
use rand::{rngs::OsRng, seq::IteratorRandom}; use rand::{rngs::OsRng, seq::IteratorRandom};
use rocket::{http::CookieJar, response::Redirect}; use rocket::{
http::CookieJar,
response::Redirect,
serde::json::{json, Value as JsonValue},
};
use rocket_dyn_templates::Template; use rocket_dyn_templates::Template;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serenity::{http::Http, model::id::ChannelId}; use serenity::{
use sqlx::{types::Json, Executor}; client::Context,
http::Http,
model::id::{ChannelId, GuildId, UserId},
};
use sqlx::{types::Json, Executor, MySql, Pool};
use crate::{ use crate::{
consts::{CHARACTERS, DEFAULT_AVATAR}, check_guild_subscription, check_subscription,
consts::{
CHARACTERS, DAY, DEFAULT_AVATAR, MAX_CONTENT_LENGTH, MAX_EMBED_AUTHOR_LENGTH,
MAX_EMBED_DESCRIPTION_LENGTH, MAX_EMBED_FIELDS, MAX_EMBED_FIELD_TITLE_LENGTH,
MAX_EMBED_FIELD_VALUE_LENGTH, MAX_EMBED_FOOTER_LENGTH, MAX_EMBED_TITLE_LENGTH,
MAX_URL_LENGTH, MAX_USERNAME_LENGTH, MIN_INTERVAL,
},
Database, Error, Database, Error,
}; };
pub mod export;
pub mod guild; pub mod guild;
pub mod user; pub mod user;
pub type JsonResult = Result<JsonValue, JsonValue>;
type Unset<T> = Option<T>; type Unset<T> = Option<T>;
fn name_default() -> String { fn name_default() -> String {
@ -60,6 +76,28 @@ pub struct ReminderTemplate {
username: Option<String>, username: Option<String>,
} }
#[derive(Serialize, Deserialize)]
pub struct ReminderTemplateCsv {
#[serde(default = "template_name_default")]
name: String,
attachment: Option<Vec<u8>>,
attachment_name: Option<String>,
avatar: Option<String>,
content: String,
embed_author: String,
embed_author_url: Option<String>,
embed_color: u32,
embed_description: String,
embed_footer: String,
embed_footer_url: Option<String>,
embed_image_url: Option<String>,
embed_thumbnail_url: Option<String>,
embed_title: String,
embed_fields: Option<String>,
tts: bool,
username: Option<String>,
}
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct DeleteReminderTemplate { pub struct DeleteReminderTemplate {
id: u32, id: u32,
@ -105,6 +143,36 @@ pub struct Reminder {
utc_time: NaiveDateTime, utc_time: NaiveDateTime,
} }
#[derive(Serialize, Deserialize)]
pub struct ReminderCsv {
#[serde(with = "base64s")]
attachment: Option<Vec<u8>>,
attachment_name: Option<String>,
avatar: Option<String>,
channel: String,
content: String,
embed_author: String,
embed_author_url: Option<String>,
embed_color: u32,
embed_description: String,
embed_footer: String,
embed_footer_url: Option<String>,
embed_image_url: Option<String>,
embed_thumbnail_url: Option<String>,
embed_title: String,
embed_fields: Option<String>,
enabled: bool,
expires: Option<NaiveDateTime>,
interval_seconds: Option<u32>,
interval_months: Option<u32>,
#[serde(default = "name_default")]
name: String,
restartable: bool,
tts: bool,
username: Option<String>,
utc_time: NaiveDateTime,
}
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct PatchReminder { pub struct PatchReminder {
uid: String, uid: String,
@ -220,13 +288,225 @@ pub struct DeleteReminder {
uid: String, uid: String,
} }
#[derive(Deserialize)]
pub struct ImportBody {
body: String,
}
#[derive(Serialize, Deserialize)]
pub struct TodoCsv {
value: String,
channel_id: Option<String>,
}
pub async fn create_reminder(
ctx: &Context,
pool: &Pool<MySql>,
guild_id: GuildId,
user_id: UserId,
reminder: Reminder,
) -> JsonResult {
// validate channel
let channel = ChannelId(reminder.channel).to_channel_cached(&ctx);
let channel_exists = channel.is_some();
let channel_matches_guild =
channel.map_or(false, |c| c.guild().map_or(false, |c| c.guild_id == guild_id));
if !channel_matches_guild || !channel_exists {
warn!(
"Error in `create_reminder`: channel {} not found for guild {} (channel exists: {})",
reminder.channel, guild_id, channel_exists
);
return Err(json!({"error": "Channel not found"}));
}
let channel = create_database_channel(&ctx, ChannelId(reminder.channel), pool).await;
if let Err(e) = channel {
warn!("`create_database_channel` returned an error code: {:?}", e);
return Err(
json!({"error": "Failed to configure channel for reminders. Please check the bot permissions"}),
);
}
let channel = channel.unwrap();
// validate lengths
check_length!(MAX_CONTENT_LENGTH, reminder.content);
check_length!(MAX_EMBED_DESCRIPTION_LENGTH, reminder.embed_description);
check_length!(MAX_EMBED_TITLE_LENGTH, reminder.embed_title);
check_length!(MAX_EMBED_AUTHOR_LENGTH, reminder.embed_author);
check_length!(MAX_EMBED_FOOTER_LENGTH, reminder.embed_footer);
check_length_opt!(MAX_EMBED_FIELDS, reminder.embed_fields);
if let Some(fields) = &reminder.embed_fields {
for field in &fields.0 {
check_length!(MAX_EMBED_FIELD_VALUE_LENGTH, field.value);
check_length!(MAX_EMBED_FIELD_TITLE_LENGTH, field.title);
}
}
check_length_opt!(MAX_USERNAME_LENGTH, reminder.username);
check_length_opt!(
MAX_URL_LENGTH,
reminder.embed_footer_url,
reminder.embed_thumbnail_url,
reminder.embed_author_url,
reminder.embed_image_url,
reminder.avatar
);
// validate urls
check_url_opt!(
reminder.embed_footer_url,
reminder.embed_thumbnail_url,
reminder.embed_author_url,
reminder.embed_image_url,
reminder.avatar
);
// validate time and interval
if reminder.utc_time < Utc::now().naive_utc() {
return Err(json!({"error": "Time must be in the future"}));
}
if reminder.interval_seconds.is_some() || reminder.interval_months.is_some() {
if reminder.interval_months.unwrap_or(0) * 30 * DAY as u32
+ reminder.interval_seconds.unwrap_or(0)
< *MIN_INTERVAL
{
return Err(json!({"error": "Interval too short"}));
}
}
// check patreon if necessary
if reminder.interval_seconds.is_some() || reminder.interval_months.is_some() {
if !check_guild_subscription(&ctx, guild_id).await
&& !check_subscription(&ctx, user_id).await
{
return Err(json!({"error": "Patreon is required to set intervals"}));
}
}
// base64 decode error dropped here
let attachment_data = reminder.attachment.as_ref().map(|s| base64::decode(s).ok()).flatten();
let name = if reminder.name.is_empty() { name_default() } else { reminder.name.clone() };
let new_uid = generate_uid();
// write to db
match sqlx::query!(
"INSERT INTO reminders (
uid,
attachment,
attachment_name,
channel_id,
avatar,
content,
embed_author,
embed_author_url,
embed_color,
embed_description,
embed_footer,
embed_footer_url,
embed_image_url,
embed_thumbnail_url,
embed_title,
embed_fields,
enabled,
expires,
interval_seconds,
interval_months,
name,
restartable,
tts,
username,
`utc_time`
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
new_uid,
attachment_data,
reminder.attachment_name,
channel,
reminder.avatar,
reminder.content,
reminder.embed_author,
reminder.embed_author_url,
reminder.embed_color,
reminder.embed_description,
reminder.embed_footer,
reminder.embed_footer_url,
reminder.embed_image_url,
reminder.embed_thumbnail_url,
reminder.embed_title,
reminder.embed_fields,
reminder.enabled,
reminder.expires,
reminder.interval_seconds,
reminder.interval_months,
name,
reminder.restartable,
reminder.tts,
reminder.username,
reminder.utc_time,
)
.execute(pool)
.await
{
Ok(_) => sqlx::query_as_unchecked!(
Reminder,
"SELECT
reminders.attachment,
reminders.attachment_name,
reminders.avatar,
channels.channel,
reminders.content,
reminders.embed_author,
reminders.embed_author_url,
reminders.embed_color,
reminders.embed_description,
reminders.embed_footer,
reminders.embed_footer_url,
reminders.embed_image_url,
reminders.embed_thumbnail_url,
reminders.embed_title,
reminders.embed_fields,
reminders.enabled,
reminders.expires,
reminders.interval_seconds,
reminders.interval_months,
reminders.name,
reminders.restartable,
reminders.tts,
reminders.uid,
reminders.username,
reminders.utc_time
FROM reminders
LEFT JOIN channels ON channels.id = reminders.channel_id
WHERE uid = ?",
new_uid
)
.fetch_one(pool)
.await
.map(|r| Ok(json!(r)))
.unwrap_or_else(|e| {
warn!("Failed to complete SQL query: {:?}", e);
Err(json!({"error": "Could not load reminder"}))
}),
Err(e) => {
warn!("Error in `create_reminder`: Could not execute query: {:?}", e);
Err(json!({"error": "Unknown error"}))
}
}
}
async fn create_database_channel( async fn create_database_channel(
ctx: impl AsRef<Http>, ctx: impl AsRef<Http>,
channel: ChannelId, channel: ChannelId,
pool: impl Executor<'_, Database = Database> + Copy, pool: impl Executor<'_, Database = Database> + Copy,
) -> Result<u32, crate::Error> { ) -> Result<u32, crate::Error> {
println!("{:?}", channel);
let row = let row =
sqlx::query!("SELECT webhook_token, webhook_id FROM channels WHERE channel = ?", channel.0) sqlx::query!("SELECT webhook_token, webhook_id FROM channels WHERE channel = ?", channel.0)
.fetch_one(pool) .fetch_one(pool)

View File

@ -61,7 +61,10 @@ pub async fn get_user_info(
.member(&ctx.inner(), user_id) .member(&ctx.inner(), user_id)
.await; .await;
let timezone = sqlx::query!("SELECT timezone FROM users WHERE user = ?", user_id) let timezone = sqlx::query!(
"SELECT IFNULL(timezone, 'UTC') AS timezone FROM users WHERE user = ?",
user_id
)
.fetch_one(pool.inner()) .fetch_one(pool.inner())
.await .await
.map_or(None, |q| Some(q.timezone)); .map_or(None, |q| Some(q.timezone));

View File

@ -25,7 +25,6 @@ pub async fn discord_login(
// Set the desired scopes. // Set the desired scopes.
.add_scope(Scope::new("identify".to_string())) .add_scope(Scope::new("identify".to_string()))
.add_scope(Scope::new("guilds".to_string())) .add_scope(Scope::new("guilds".to_string()))
.add_scope(Scope::new("email".to_string()))
// Set the PKCE code challenge. // Set the PKCE code challenge.
.set_pkce_challenge(pkce_challenge) .set_pkce_challenge(pkce_challenge)
.url(); .url();

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View File

@ -12,6 +12,10 @@ const $createTemplateBtn = $createReminder.querySelector("button#createTemplate"
const $loadTemplateBtn = document.querySelector("button#load-template"); const $loadTemplateBtn = document.querySelector("button#load-template");
const $deleteTemplateBtn = document.querySelector("button#delete-template"); const $deleteTemplateBtn = document.querySelector("button#delete-template");
const $templateSelect = document.querySelector("select#templateSelect"); const $templateSelect = document.querySelector("select#templateSelect");
const $exportBtn = document.querySelector("button#export-data");
const $importBtn = document.querySelector("button#import-data");
const $downloader = document.querySelector("a#downloader");
const $uploader = document.querySelector("input#uploader");
let channels = []; let channels = [];
let guildNames = {}; let guildNames = {};
@ -670,6 +674,39 @@ function has_source(string) {
} }
} }
$uploader.addEventListener("change", (ev) => {
const urlTail = document.querySelector('input[name="exportSelect"]:checked').value;
new Promise((resolve) => {
let fileReader = new FileReader();
fileReader.onload = (e) => resolve(fileReader.result);
fileReader.readAsDataURL($uploader.files[0]);
}).then((dataUrl) => {
fetch(`/dashboard/api/guild/${guildId()}/export/${urlTail}`, {
method: "PUT",
body: JSON.stringify({ body: dataUrl.split(",")[1] }),
}).then(() => {
delete $uploader.files[0];
});
});
});
$importBtn.addEventListener("click", () => {
$uploader.click();
});
$exportBtn.addEventListener("click", () => {
const urlTail = document.querySelector('input[name="exportSelect"]:checked').value;
fetch(`/dashboard/api/guild/${guildId()}/export/${urlTail}`)
.then((response) => response.json())
.then((data) => {
$downloader.href =
"data:text/plain;charset=utf-8," + encodeURIComponent(data.body);
$downloader.click();
});
});
$createReminderBtn.addEventListener("click", async () => { $createReminderBtn.addEventListener("click", async () => {
$createReminderBtn.querySelector("span.icon > i").classList = [ $createReminderBtn.querySelector("span.icon > i").classList = [
"fas fa-spinner fa-spin", "fas fa-spinner fa-spin",
@ -834,7 +871,7 @@ document.addEventListener("remindersLoaded", () => {
}); });
}); });
const fileInput = document.querySelectorAll("input[type=file]"); const fileInput = document.querySelectorAll("input.file-input[type=file]");
fileInput.forEach((element) => { fileInput.forEach((element) => {
element.addEventListener("change", () => { element.addEventListener("change", () => {

View File

@ -177,38 +177,41 @@
<section class="modal-card-body"> <section class="modal-card-body">
<div class="control"> <div class="control">
<div class="field"> <div class="field">
<input type="checkbox" class="default-width"> <label>
<label>Reminders</label> <input type="radio" class="default-width" name="exportSelect" value="reminders" checked>
Reminders
</label>
</div> </div>
</div> </div>
<div class="control"> <div class="control">
<div class="field"> <div class="field">
<input type="checkbox" class="default-width"> <label>
<label>Todo Lists</label> <input type="radio" class="default-width" name="exportSelect" value="todos">
Todo Lists
</label>
</div> </div>
</div> </div>
<div class="control"> <div class="control">
<div class="field"> <div class="field">
<input type="checkbox" class="default-width"> <label>
<label>Timers</label> <input type="radio" class="default-width" name="exportSelect" value="reminder_templates">
</div> Reminder templates
</div> </label>
<div class="control">
<div class="field">
<input type="checkbox" class="default-width">
<label>Reminder templates</label>
</div>
</div>
<div class="control">
<div class="field">
<input type="checkbox" class="default-width">
<label>Macros</label>
</div> </div>
</div> </div>
<br>
<div class="has-text-centered"> <div class="has-text-centered">
<div style="color: red; font-weight: bold;">
By selecting "Import", you understand that this will overwrite existing data.
</div>
<div style="color: red">
Please first read the <a href="/help/iemanager">support page</a>
</div>
<button class="button is-success is-outlined" id="import-data">Import Data</button> <button class="button is-success is-outlined" id="import-data">Import Data</button>
<button class="button is-success" id="export-data">Export Data</button> <button class="button is-success" id="export-data">Export Data</button>
</div> </div>
<a id="downloader" download="export.csv" class="is-hidden"></a>
<input id="uploader" type="file" hidden></input>
</section> </section>
</div> </div>
<button class="modal-close is-large close-modal" aria-label="close"></button> <button class="modal-close is-large close-modal" aria-label="close"></button>

View File

@ -5,5 +5,5 @@
{% set show_contact = True %} {% set show_contact = True %}
{% set page_title = "An Error Has Occurred" %} {% set page_title = "An Error Has Occurred" %}
{% set page_subtitle = "A server error has occurred. Please contact me and I will try and resolve this" %} {% set page_subtitle = "A server error has occurred. Please retry, or ask in our Discord." %}
{% endblock %} {% endblock %}

View File

@ -49,7 +49,7 @@
<div class="container"> <div class="container">
<h2 class="title">Who your data is shared with</h2> <h2 class="title">Who your data is shared with</h2>
<p class="is-size-5 pl-6"> <p class="is-size-5 pl-6">
Your data may also be guarded by the privacy policies of <strong>MEGA</strong>, our backup provider, and Your data is also guarded by the privacy policies of <strong>MEGA</strong>, our backup provider, and
<strong>Hetzner</strong>, our hosting provider. <strong>Hetzner</strong>, our hosting provider.
</p> </p>
</div> </div>
@ -68,7 +68,7 @@
<br> <br>
<br> <br>
Reminders deleted with <strong>/del</strong> or via the dashboard are removed from the live database Reminders deleted with <strong>/del</strong> or via the dashboard are removed from the live database
instantly, but may persist in backups. instantly, but may persist in backups for up to a year.
</p> </p>
</div> </div>
</section> </section>

View File

@ -14,13 +14,75 @@
<div class="container"> <div class="container">
<p class="title">Export your data</p> <p class="title">Export your data</p>
<p class="content"> <p class="content">
You can create reminders with the <code>/remind</code> command. You can export data associated with your server from the dashboard. The data will export as a CSV
<br> file. The CSV file can then be edited and imported to bulk edit server data.
Fill out the "time" and "content" fields. If you wish, press on "Optional" to view other options
for the reminder.
</p> </p>
</div> </div>
</div> </div>
</section> </section>
<section class="hero is-small">
<div class="hero-body">
<div class="container">
<p class="title">Import data</p>
<p class="content">
You can import previous exports or modified exports. When importing a file, <strong>existing data
will be overwritten</strong>.
</p>
</div>
</div>
</section>
<section class="hero is-small">
<div class="hero-body">
<div class="container content">
<p class="title">Edit your data</p>
<p>
The CSV can be edited either as a text file or in a spreadsheet editor such as LibreOffice Calc. To
set up LibreOffice Calc for editing, do the following:
</p>
<ol>
<li>
Export data from dashboard.
<figure>
<img src="/static/img/support/iemanager/select_export.png" alt="Selecting export button">
</figure>
</li>
<li>
Open the file in LibreOffice. <strong>During the import dialogue, select "Format quoted field as text".</strong>
<figure>
<img src="/static/img/support/iemanager/format_text.png" alt="Selecting format button">
</figure>
</li>
<li>
Make edits to the spreadsheet. You can add, edit, and remove rows for reminders. Don't remove the title row.
<figure>
<img src="/static/img/support/iemanager/edit_spreadsheet.png" alt="Editing spreadsheet">
</figure>
</li>
<li>
Save the edited CSV file and import it on the dashboard.
<figure>
<img src="/static/img/support/iemanager/import.png" alt="Import new reminders">
</figure>
</li>
</ol>
Other spreadsheet tools can also be used to edit exports, as long as they are properly configured:
<ul>
<li>
<strong>Google Sheets</strong>: Create a new blank spreadsheet. Select <strong>File >> Import >> Upload >> export.csv</strong>.
Use the following import settings:
<figure>
<img src="/static/img/support/iemanager/sheets_settings.png" alt="Google sheets import settings">
</figure>
</li>
<li>
<strong>Excel (including Excel Online)</strong>: Avoid using Excel. Excel will not correctly import channels, or give
clear options to correct imports.
</li>
</ul>
</div>
</div>
</section>
{% endblock %} {% endblock %}

View File

@ -20,11 +20,12 @@
<br> <br>
Violating the Terms of Service may result in receiving a permanent ban from the Discord server, Violating the Terms of Service may result in receiving a permanent ban from the Discord server,
permanent restriction on your usage of Reminder Bot, or removal of some or all of your content on permanent restriction on your usage of Reminder Bot, or removal of some or all of your content on
Reminder Bot or the Discord server. Reminder Bot or the Discord server. None of these will necessarily be preceded or succeeded by a warning
or notice.
<br> <br>
<br> <br>
The Terms of Service may be updated at any time. Notice will be provided via the Discord server. You The Terms of Service may be updated. Notice will be provided via the Discord server. You
should consider the Terms of Service to be a guideline for appropriate behaviour. should consider the Terms of Service to be a strong for appropriate behaviour.
</p> </p>
</div> </div>
</section> </section>
@ -37,6 +38,12 @@
<li>Do not use the bot to harass other Discord users</li> <li>Do not use the bot to harass other Discord users</li>
<li>Do not use the bot to transmit malware or other illegal content</li> <li>Do not use the bot to transmit malware or other illegal content</li>
<li>Do not use the bot to send more than 15 messages during a 60 second period</li> <li>Do not use the bot to send more than 15 messages during a 60 second period</li>
<li>
Do not attempt to circumvent restrictions imposed by the bot or website, including trying to access
data of other users, circumvent Patreon restrictions, or uploading files and creating reminders that
are too large for the bot to send or process. Some or all of these actions may be illegal in your
country
</li>
</ul> </ul>
</div> </div>
</section> </section>