ran rustfmt over project. cleared up a couple of clippy things

This commit is contained in:
2020-10-12 21:01:27 +01:00
parent 88596fb399
commit c9fd2fea81
10 changed files with 1374 additions and 939 deletions

View File

@ -1,30 +1,15 @@
use regex_command_attr::command;
use serenity::{
client::Context,
model::{
channel::{
Message,
},
},
framework::standard::CommandResult,
};
use serenity::{client::Context, framework::standard::CommandResult, model::channel::Message};
use chrono::offset::Utc;
use crate::{
models::{
UserData,
GuildData,
},
THEME_COLOR,
SQLPool,
models::{GuildData, UserData},
SQLPool, THEME_COLOR,
};
use std::time::{
SystemTime,
UNIX_EPOCH
};
use std::time::{SystemTime, UNIX_EPOCH};
#[command]
#[can_blacklist(false)]
@ -36,7 +21,10 @@ async fn ping(ctx: &Context, msg: &Message, _args: String) -> CommandResult {
let delta = since_epoch.as_millis() as i64 - msg.timestamp.timestamp_millis();
let _ = msg.channel_id.say(&ctx, format!("Time taken to receive message: {}ms", delta)).await;
let _ = msg
.channel_id
.say(&ctx, format!("Time taken to receive message: {}ms", delta))
.await;
Ok(())
}
@ -44,92 +32,131 @@ async fn ping(ctx: &Context, msg: &Message, _args: String) -> CommandResult {
#[command]
#[can_blacklist(false)]
async fn help(ctx: &Context, msg: &Message, _args: String) -> CommandResult {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
let desc = user_data.response(&pool, "help").await;
msg.channel_id.send_message(ctx, |m| m
.embed(move |e| e
.title("Help")
.description(desc)
.color(THEME_COLOR)
)
).await?;
msg.channel_id
.send_message(ctx, |m| {
m.embed(move |e| e.title("Help").description(desc).color(THEME_COLOR))
})
.await?;
Ok(())
}
#[command]
async fn info(ctx: &Context, msg: &Message, _args: String) -> CommandResult {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
let guild_data = GuildData::from_guild(msg.guild(&ctx).await.unwrap(), &pool).await.unwrap();
let guild_data = GuildData::from_guild(msg.guild(&ctx).await.unwrap(), &pool)
.await
.unwrap();
let desc = user_data.response(&pool, "info").await
let desc = user_data
.response(&pool, "info")
.await
.replacen("{user}", &ctx.cache.current_user().await.name, 1)
.replacen("{prefix}", &guild_data.prefix, 1);
msg.channel_id.send_message(ctx, |m| m
.embed(move |e| e
.title("Info")
.description(desc)
.color(THEME_COLOR)
)
).await?;
msg.channel_id
.send_message(ctx, |m| {
m.embed(move |e| e.title("Info").description(desc).color(THEME_COLOR))
})
.await?;
Ok(())
}
#[command]
async fn donate(ctx: &Context, msg: &Message, _args: String) -> CommandResult {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
let desc = user_data.response(&pool, "donate").await;
msg.channel_id.send_message(ctx, |m| m
.embed(move |e| e
.title("Donate")
.description(desc)
.color(THEME_COLOR)
)
).await?;
msg.channel_id
.send_message(ctx, |m| {
m.embed(move |e| e.title("Donate").description(desc).color(THEME_COLOR))
})
.await?;
Ok(())
}
#[command]
async fn dashboard(ctx: &Context, msg: &Message, _args: String) -> CommandResult {
msg.channel_id.send_message(ctx, |m| m
.embed(move |e| e
.title("Dashboard")
.description("https://reminder-bot.com/dashboard")
.color(THEME_COLOR)
)
).await?;
msg.channel_id
.send_message(ctx, |m| {
m.embed(move |e| {
e.title("Dashboard")
.description("https://reminder-bot.com/dashboard")
.color(THEME_COLOR)
})
})
.await?;
Ok(())
}
#[command]
async fn clock(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
let now = Utc::now().with_timezone(&user_data.timezone());
if args == "12" {
let _ = msg.channel_id.say(&ctx, user_data.response(&pool, "clock/time").await.replacen("{}", &now.format("%I:%M:%S %p").to_string(), 1)).await;
}
else {
let _ = msg.channel_id.say(&ctx, user_data.response(&pool, "clock/time").await.replacen("{}", &now.format("%H:%M:%S").to_string(), 1)).await;
let _ = msg
.channel_id
.say(
&ctx,
user_data.response(&pool, "clock/time").await.replacen(
"{}",
&now.format("%I:%M:%S %p").to_string(),
1,
),
)
.await;
} else {
let _ = msg
.channel_id
.say(
&ctx,
user_data.response(&pool, "clock/time").await.replacen(
"{}",
&now.format("%H:%M:%S").to_string(),
1,
),
)
.await;
}
Ok(())

View File

@ -1,4 +1,4 @@
pub mod info_cmds;
pub mod moderation_cmds;
pub mod reminder_cmds;
pub mod todo_cmds;
pub mod moderation_cmds;

View File

@ -2,16 +2,8 @@ use regex_command_attr::command;
use serenity::{
client::Context,
model::{
id::RoleId,
channel::{
Message,
},
},
framework::{
Framework,
standard::CommandResult,
},
framework::{standard::CommandResult, Framework},
model::{channel::Message, id::RoleId},
};
use chrono_tz::Tz;
@ -21,41 +13,40 @@ use chrono::offset::Utc;
use inflector::Inflector;
use crate::{
models::{
ChannelData,
UserData,
GuildData,
},
SQLPool,
FrameworkCtx,
consts::{REGEX_ALIAS, REGEX_CHANNEL, REGEX_COMMANDS, REGEX_ROLE},
framework::SendIterator,
consts::{
REGEX_ALIAS,
REGEX_CHANNEL,
REGEX_COMMANDS,
REGEX_ROLE,
},
models::{ChannelData, GuildData, UserData},
FrameworkCtx, SQLPool,
};
use std::iter;
#[command]
#[supports_dm(false)]
#[permission_level(Restricted)]
#[can_blacklist(false)]
async fn blacklist(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let capture_opt = REGEX_CHANNEL.captures(&args).map(|cap| cap.get(1)).flatten();
let capture_opt = REGEX_CHANNEL
.captures(&args)
.map(|cap| cap.get(1))
.flatten();
let mut channel = match capture_opt {
Some(capture) =>
ChannelData::from_id(capture.as_str().parse::<u64>().unwrap(), &pool).await.unwrap(),
Some(capture) => ChannelData::from_id(capture.as_str().parse::<u64>().unwrap(), &pool)
.await
.unwrap(),
None =>
ChannelData::from_channel(msg.channel(&ctx).await.unwrap(), &pool).await.unwrap(),
None => ChannelData::from_channel(msg.channel(&ctx).await.unwrap(), &pool)
.await
.unwrap(),
};
channel.blacklisted = !channel.blacklisted;
@ -63,8 +54,7 @@ async fn blacklist(ctx: &Context, msg: &Message, args: String) -> CommandResult
if channel.blacklisted {
let _ = msg.channel_id.say(&ctx, "Blacklisted").await;
}
else {
} else {
let _ = msg.channel_id.say(&ctx, "Unblacklisted").await;
}
@ -73,8 +63,13 @@ async fn blacklist(ctx: &Context, msg: &Message, args: String) -> CommandResult
#[command]
async fn timezone(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let mut user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
@ -86,7 +81,9 @@ async fn timezone(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let now = Utc::now().with_timezone(&user_data.timezone());
let content = user_data.response(&pool, "timezone/set_p").await
let content = user_data
.response(&pool, "timezone/set_p")
.await
.replacen("{timezone}", &user_data.timezone, 1)
.replacen("{time}", &now.format("%H:%M").to_string(), 1);
@ -94,13 +91,23 @@ async fn timezone(ctx: &Context, msg: &Message, args: String) -> CommandResult {
}
Err(_) => {
let _ = msg.channel_id.say(&ctx, user_data.response(&pool, "timezone/no_timezone").await).await;
let _ = msg
.channel_id
.say(
&ctx,
user_data.response(&pool, "timezone/no_timezone").await,
)
.await;
}
}
}
else {
let content = user_data.response(&pool, "timezone/no_argument").await
.replace("{prefix}", &GuildData::prefix_from_id(msg.guild_id, &pool).await)
} else {
let content = user_data
.response(&pool, "timezone/no_argument")
.await
.replace(
"{prefix}",
&GuildData::prefix_from_id(msg.guild_id, &pool).await,
)
.replacen("{timezone}", &user_data.timezone, 1);
let _ = msg.channel_id.say(&ctx, content).await;
@ -111,25 +118,36 @@ async fn timezone(ctx: &Context, msg: &Message, args: String) -> CommandResult {
#[command]
async fn language(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let mut user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
match sqlx::query!(
"
SELECT code FROM languages WHERE code = ? OR name = ?
", args, args)
.fetch_one(&pool)
.await {
",
args,
args
)
.fetch_one(&pool)
.await
{
Ok(row) => {
user_data.language = row.code;
user_data.commit_changes(&pool).await;
let _ = msg.channel_id.say(&ctx, user_data.response(&pool, "lang/set_p").await).await;
},
let _ = msg
.channel_id
.say(&ctx, user_data.response(&pool, "lang/set_p").await)
.await;
}
Err(_) => {
let language_codes = sqlx::query!("SELECT name, code FROM languages")
@ -137,15 +155,24 @@ SELECT code FROM languages WHERE code = ? OR name = ?
.await
.unwrap()
.iter()
.map(|language| format!("{} ({})", language.name.to_title_case(), language.code.to_uppercase()))
.map(|language| {
format!(
"{} ({})",
language.name.to_title_case(),
language.code.to_uppercase()
)
})
.collect::<Vec<String>>()
.join("\n");
let content = user_data.response(&pool, "lang/invalid").await
.replacen("{}", &language_codes, 1);
let content =
user_data
.response(&pool, "lang/invalid")
.await
.replacen("{}", &language_codes, 1);
let _ = msg.channel_id.say(&ctx, content).await;
},
}
}
Ok(())
@ -155,24 +182,38 @@ SELECT code FROM languages WHERE code = ? OR name = ?
#[supports_dm(false)]
#[permission_level(Restricted)]
async fn prefix(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let mut guild_data = GuildData::from_guild(msg.guild(&ctx).await.unwrap(), &pool).await.unwrap();
let mut guild_data = GuildData::from_guild(msg.guild(&ctx).await.unwrap(), &pool)
.await
.unwrap();
let user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
if args.len() > 5 {
let _ = msg.channel_id.say(&ctx, user_data.response(&pool, "prefix/too_long").await).await;
}
else if args.is_empty() {
let _ = msg.channel_id.say(&ctx, user_data.response(&pool, "prefix/no_argument").await).await;
}
else {
let _ = msg
.channel_id
.say(&ctx, user_data.response(&pool, "prefix/too_long").await)
.await;
} else if args.is_empty() {
let _ = msg
.channel_id
.say(&ctx, user_data.response(&pool, "prefix/no_argument").await)
.await;
} else {
guild_data.prefix = args;
guild_data.commit_changes(&pool).await;
let content = user_data.response(&pool, "prefix/success").await
.replacen("{prefix}", &guild_data.prefix, 1);
let content = user_data.response(&pool, "prefix/success").await.replacen(
"{prefix}",
&guild_data.prefix,
1,
);
let _ = msg.channel_id.say(&ctx, content).await;
}
@ -184,17 +225,31 @@ async fn prefix(ctx: &Context, msg: &Message, args: String) -> CommandResult {
#[supports_dm(false)]
#[permission_level(Restricted)]
async fn restrict(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
let guild_data = GuildData::from_guild(msg.guild(&ctx).await.unwrap(), &pool).await.unwrap();
let guild_data = GuildData::from_guild(msg.guild(&ctx).await.unwrap(), &pool)
.await
.unwrap();
let role_tag_match = REGEX_ROLE.find(&args);
if let Some(role_tag) = role_tag_match {
let commands = REGEX_COMMANDS.find_iter(&args.to_lowercase()).map(|c| c.as_str().to_string()).collect::<Vec<String>>();
let role_id = RoleId(role_tag.as_str()[3..role_tag.as_str().len()-1].parse::<u64>().unwrap());
let commands = REGEX_COMMANDS
.find_iter(&args.to_lowercase())
.map(|c| c.as_str().to_string())
.collect::<Vec<String>>();
let role_id = RoleId(
role_tag.as_str()[3..role_tag.as_str().len() - 1]
.parse::<u64>()
.unwrap(),
);
let role_opt = role_id.to_role_cached(&ctx).await;
@ -202,20 +257,28 @@ async fn restrict(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let _ = sqlx::query!(
"
DELETE FROM command_restrictions WHERE role_id = (SELECT id FROM roles WHERE role = ?)
", role.id.as_u64())
.execute(&pool)
.await;
",
role.id.as_u64()
)
.execute(&pool)
.await;
if commands.is_empty() {
let _ = msg.channel_id.say(&ctx, user_data.response(&pool, "restrict/disabled").await).await;
}
else {
let _ = msg
.channel_id
.say(&ctx, user_data.response(&pool, "restrict/disabled").await)
.await;
} else {
let _ = sqlx::query!(
"
INSERT IGNORE INTO roles (role, name, guild_id) VALUES (?, ?, ?)
", role.id.as_u64(), role.name, guild_data.id)
.execute(&pool)
.await;
",
role.id.as_u64(),
role.name,
guild_data.id
)
.execute(&pool)
.await;
for command in commands {
let res = sqlx::query!(
@ -228,18 +291,22 @@ INSERT INTO command_restrictions (role_id, command) VALUES ((SELECT id FROM role
if res.is_err() {
println!("{:?}", res);
let content = user_data.response(&pool, "restrict/failure").await
let content = user_data
.response(&pool, "restrict/failure")
.await
.replacen("{command}", &command, 1);
let _ = msg.channel_id.say(&ctx, content).await;
}
}
let _ = msg.channel_id.say(&ctx, user_data.response(&pool, "restrict/enabled").await).await;
let _ = msg
.channel_id
.say(&ctx, user_data.response(&pool, "restrict/enabled").await)
.await;
}
}
}
else if args.is_empty() {
} else if args.is_empty() {
let guild_id = msg.guild_id.unwrap().as_u64().to_owned();
let rows = sqlx::query!(
@ -254,18 +321,29 @@ ON
roles.id = command_restrictions.role_id
WHERE
roles.guild_id = (SELECT id FROM guilds WHERE guild = ?)
", guild_id)
.fetch_all(&pool)
.await
.unwrap();
",
guild_id
)
.fetch_all(&pool)
.await
.unwrap();
let display_inner = rows.iter().map(|row| format!("<@&{}> can use {}", row.role, row.command)).collect::<Vec<String>>().join("\n");
let display = user_data.response(&pool, "restrict/allowed").await.replacen("{}", &display_inner, 1);
let display_inner = rows
.iter()
.map(|row| format!("<@&{}> can use {}", row.role, row.command))
.collect::<Vec<String>>()
.join("\n");
let display = user_data
.response(&pool, "restrict/allowed")
.await
.replacen("{}", &display_inner, 1);
let _ = msg.channel_id.say(&ctx, display).await;
}
else {
let _ = msg.channel_id.say(&ctx, user_data.response(&pool, "restrict/help").await).await;
} else {
let _ = msg
.channel_id
.say(&ctx, user_data.response(&pool, "restrict/help").await)
.await;
}
Ok(())
@ -275,8 +353,13 @@ WHERE
#[supports_dm(false)]
#[permission_level(Managed)]
async fn alias(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
@ -293,21 +376,21 @@ async fn alias(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let aliases = sqlx::query!(
"
SELECT name, command FROM command_aliases WHERE guild_id = (SELECT id FROM guilds WHERE guild = ?)
", guild_id)
.fetch_all(&pool)
.await
.unwrap();
",
guild_id
)
.fetch_all(&pool)
.await
.unwrap();
let content = iter::once("Aliases:".to_string())
.chain(
aliases
.iter()
.map(|row| format!("**{}**: `{}`", row.name, row.command)
)
);
let content = iter::once("Aliases:".to_string()).chain(
aliases
.iter()
.map(|row| format!("**{}**: `{}`", row.name, row.command)),
);
let _ = msg.channel_id.say_lines(&ctx, content).await;
},
}
"remove" => {
if let Some(command) = command_opt {
@ -322,19 +405,27 @@ SELECT COUNT(1) AS count FROM command_aliases WHERE name = ? AND guild_id = (SEL
sqlx::query!(
"
DELETE FROM command_aliases WHERE name = ? AND guild_id = (SELECT id FROM guilds WHERE guild = ?)
", command, guild_id)
.execute(&pool)
.await
.unwrap();
",
command,
guild_id
)
.execute(&pool)
.await
.unwrap();
let content = user_data.response(&pool, "alias/removed").await.replace("{count}", &deleted_count.count.to_string());
let content = user_data
.response(&pool, "alias/removed")
.await
.replace("{count}", &deleted_count.count.to_string());
let _ = msg.channel_id.say(&ctx, content).await;
} else {
let _ = msg
.channel_id
.say(&ctx, user_data.response(&pool, "alias/help").await)
.await;
}
else {
let _ = msg.channel_id.say(&ctx, user_data.response(&pool, "alias/help").await).await;
}
},
}
name => {
if let Some(command) = command_opt {
@ -355,11 +446,13 @@ UPDATE command_aliases SET command = ? WHERE guild_id = (SELECT id FROM guilds W
.unwrap();
}
let content = user_data.response(&pool, "alias/created").await.replace("{name}", name);
let content = user_data
.response(&pool, "alias/created")
.await
.replace("{name}", name);
let _ = msg.channel_id.say(&ctx, content).await;
}
else {
} else {
match sqlx::query!(
"
SELECT command FROM command_aliases WHERE guild_id = (SELECT id FROM guilds WHERE guild = ?) AND name = ?
@ -386,10 +479,12 @@ SELECT command FROM command_aliases WHERE guild_id = (SELECT id FROM guilds WHER
}
}
}
}
else {
} else {
let prefix = GuildData::prefix_from_id(msg.guild_id, &pool).await;
let content = user_data.response(&pool, "alias/help").await.replace("{prefix}", &prefix);
let content = user_data
.response(&pool, "alias/help")
.await
.replace("{prefix}", &prefix);
let _ = msg.channel_id.say(&ctx, content).await;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,26 +1,19 @@
use regex_command_attr::command;
use serenity::{
constants::MESSAGE_CODE_LIMIT,
client::Context,
model::{
id::{
UserId, GuildId, ChannelId,
},
channel::{
Message,
},
},
constants::MESSAGE_CODE_LIMIT,
framework::standard::CommandResult,
model::{
channel::Message,
id::{ChannelId, GuildId, UserId},
},
};
use std::fmt;
use crate::{
models::{
UserData,
GuildData,
},
models::{GuildData, UserData},
SQLPool,
};
use sqlx::MySqlPool;
@ -54,18 +47,15 @@ impl TodoTarget {
pub fn command(&self, subcommand_opt: Option<SubCommand>) -> String {
let context = if self.channel.is_some() {
"channel"
}
else if self.guild.is_some() {
} else if self.guild.is_some() {
"guild"
}
else {
} else {
"user"
};
if let Some(subcommand) = subcommand_opt {
format!("todo {} {}", context, subcommand.to_string())
}
else {
} else {
format!("todo {}", context)
}
}
@ -73,43 +63,56 @@ impl TodoTarget {
pub fn name(&self) -> String {
if self.channel.is_some() {
"Channel"
}
else if self.guild.is_some() {
} else if self.guild.is_some() {
"Guild"
}
else {
} else {
"User"
}.to_string()
}
.to_string()
}
pub async fn view(&self, pool: MySqlPool) -> Result<Vec<Todo>, Box<dyn std::error::Error + Send + Sync>> {
pub async fn view(
&self,
pool: MySqlPool,
) -> Result<Vec<Todo>, Box<dyn std::error::Error + Send + Sync>> {
Ok(if let Some(cid) = self.channel {
sqlx::query_as!(Todo,
sqlx::query_as!(
Todo,
"
SELECT * FROM todos WHERE channel_id = (SELECT id FROM channels WHERE channel = ?)
", cid.as_u64())
.fetch_all(&pool)
.await?
}
else if let Some(gid) = self.guild {
sqlx::query_as!(Todo,
",
cid.as_u64()
)
.fetch_all(&pool)
.await?
} else if let Some(gid) = self.guild {
sqlx::query_as!(
Todo,
"
SELECT * FROM todos WHERE guild_id = (SELECT id FROM guilds WHERE guild = ?) AND channel_id IS NULL
", gid.as_u64())
.fetch_all(&pool)
.await?
}
else {
sqlx::query_as!(Todo,
",
gid.as_u64()
)
.fetch_all(&pool)
.await?
} else {
sqlx::query_as!(
Todo,
"
SELECT * FROM todos WHERE user_id = (SELECT id FROM users WHERE user = ?) AND guild_id IS NULL
", self.user.as_u64())
.fetch_all(&pool)
.await?
",
self.user.as_u64()
)
.fetch_all(&pool)
.await?
})
}
pub async fn add(&self, value: String, pool: MySqlPool) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
pub async fn add(
&self,
value: String,
pool: MySqlPool,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
if let (Some(cid), Some(gid)) = (self.channel, self.guild) {
sqlx::query!(
"
@ -119,11 +122,15 @@ INSERT INTO todos (user_id, guild_id, channel_id, value) VALUES (
(SELECT id FROM channels WHERE channel = ?),
?
)
", self.user.as_u64(), gid.as_u64(), cid.as_u64(), value)
.execute(&pool)
.await?;
}
else if let Some(gid) = self.guild {
",
self.user.as_u64(),
gid.as_u64(),
cid.as_u64(),
value
)
.execute(&pool)
.await?;
} else if let Some(gid) = self.guild {
sqlx::query!(
"
INSERT INTO todos (user_id, guild_id, value) VALUES (
@ -131,74 +138,95 @@ INSERT INTO todos (user_id, guild_id, value) VALUES (
(SELECT id FROM guilds WHERE guild = ?),
?
)
", self.user.as_u64(), gid.as_u64(), value)
.execute(&pool)
.await?;
}
else {
",
self.user.as_u64(),
gid.as_u64(),
value
)
.execute(&pool)
.await?;
} else {
sqlx::query!(
"
INSERT INTO todos (user_id, value) VALUES (
(SELECT id FROM users WHERE user = ?),
?
)
", self.user.as_u64(), value)
.execute(&pool)
.await?;
",
self.user.as_u64(),
value
)
.execute(&pool)
.await?;
}
Ok(())
}
pub async fn remove(&self, num: usize, pool: &MySqlPool) -> Result<Todo, Box<dyn std::error::Error + Sync + Send>> {
pub async fn remove(
&self,
num: usize,
pool: &MySqlPool,
) -> Result<Todo, Box<dyn std::error::Error + Sync + Send>> {
let todos = self.view(pool.clone()).await?;
if let Some(removal_todo) = todos.get(num) {
let deleting = sqlx::query_as!(Todo,
let deleting = sqlx::query_as!(
Todo,
"
SELECT * FROM todos WHERE id = ?
", removal_todo.id)
.fetch_one(&pool.clone())
.await?;
",
removal_todo.id
)
.fetch_one(&pool.clone())
.await?;
sqlx::query!(
"
DELETE FROM todos WHERE id = ?
", removal_todo.id)
.execute(pool)
.await?;
",
removal_todo.id
)
.execute(pool)
.await?;
Ok(deleting)
}
else {
} else {
Err(Box::new(TodoNotFound))
}
}
pub async fn clear(&self, pool: &MySqlPool) -> Result<(), Box<dyn std::error::Error + Sync + Send>> {
pub async fn clear(
&self,
pool: &MySqlPool,
) -> Result<(), Box<dyn std::error::Error + Sync + Send>> {
if let Some(cid) = self.channel {
sqlx::query!(
"
DELETE FROM todos WHERE channel_id = (SELECT id FROM channels WHERE channel = ?)
", cid.as_u64())
.execute(pool)
.await?;
}
else if let Some(gid) = self.guild {
",
cid.as_u64()
)
.execute(pool)
.await?;
} else if let Some(gid) = self.guild {
sqlx::query!(
"
DELETE FROM todos WHERE guild_id = (SELECT id FROM guilds WHERE guild = ?) AND channel_id IS NULL
", gid.as_u64())
.execute(pool)
.await?;
}
else {
",
gid.as_u64()
)
.execute(pool)
.await?;
} else {
sqlx::query!(
"
DELETE FROM todos WHERE user_id = (SELECT id FROM users WHERE user = ?) AND guild_id IS NULL
", self.user.as_u64())
.execute(pool)
.await?;
",
self.user.as_u64()
)
.execute(pool)
.await?;
}
Ok(())
@ -219,47 +247,53 @@ impl ToString for SubCommand {
SubCommand::Add => "add",
SubCommand::Remove => "remove",
SubCommand::Clear => "clear",
}.to_string()
}
.to_string()
}
}
#[command]
#[permission_level(Managed)]
async fn todo_parse(ctx: &Context, msg: &Message, args: String) -> CommandResult {
let mut split = args.split(' ');
if let Some(target) = split.next() {
let target_opt = match target {
"user" =>
Some(TodoTarget {user: msg.author.id, guild: None, channel: None}),
"user" => Some(TodoTarget {
user: msg.author.id,
guild: None,
channel: None,
}),
"channel" =>
"channel" => {
if let Some(gid) = msg.guild_id {
Some(TodoTarget {user: msg.author.id, guild: Some(gid), channel: Some(msg.channel_id)})
}
else {
Some(TodoTarget {
user: msg.author.id,
guild: Some(gid),
channel: Some(msg.channel_id),
})
} else {
None
},
}
}
"server" | "guild" => {
if let Some(gid) = msg.guild_id {
Some(TodoTarget {user: msg.author.id, guild: Some(gid), channel: None})
}
else {
Some(TodoTarget {
user: msg.author.id,
guild: Some(gid),
channel: None,
})
} else {
None
}
},
}
_ => {
None
},
_ => None,
};
if let Some(target) = target_opt {
let subcommand_opt = match split.next() {
Some("add") => Some(SubCommand::Add),
Some("remove") => Some(SubCommand::Remove),
@ -272,19 +306,21 @@ async fn todo_parse(ctx: &Context, msg: &Message, args: String) -> CommandResult
};
if let Some(subcommand) = subcommand_opt {
todo(ctx, msg, target, subcommand, split.collect::<Vec<&str>>().join(" ")).await;
}
else {
todo(
ctx,
msg,
target,
subcommand,
split.collect::<Vec<&str>>().join(" "),
)
.await;
} else {
show_help(&ctx, msg, Some(target)).await;
}
}
else {
} else {
show_help(&ctx, msg, None).await;
}
}
else {
} else {
show_help(&ctx, msg, None).await;
}
@ -292,22 +328,45 @@ async fn todo_parse(ctx: &Context, msg: &Message, args: String) -> CommandResult
}
async fn show_help(ctx: &Context, msg: &Message, target: Option<TodoTarget>) {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
let prefix = GuildData::prefix_from_id(msg.guild_id, &pool).await;
let content = user_data.response(&pool, "todo/help").await
let content = user_data
.response(&pool, "todo/help")
.await
.replace("{prefix}", &prefix)
.replace("{command}", target.map_or_else(|| "todo user".to_string(), |t| t.command(None)).as_str());
.replace(
"{command}",
target
.map_or_else(|| "todo user".to_string(), |t| t.command(None))
.as_str(),
);
let _ = msg.channel_id.say(&ctx, content).await;
}
async fn todo(ctx: &Context, msg: &Message, target: TodoTarget, subcommand: SubCommand, extra: String) {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
async fn todo(
ctx: &Context,
msg: &Message,
target: TodoTarget,
subcommand: SubCommand,
extra: String,
) {
let pool = ctx
.data
.read()
.await
.get::<SQLPool>()
.cloned()
.expect("Could not get SQLPool from data");
let user_data = UserData::from_user(&msg.author, &ctx, &pool).await.unwrap();
let prefix = GuildData::prefix_from_id(msg.guild_id, &pool).await;
@ -325,8 +384,7 @@ async fn todo(ctx: &Context, msg: &Message, target: TodoTarget, subcommand: SubC
char_count = display.len();
todo_groups.push(display);
}
else {
} else {
char_count += display.len();
let last_group = todo_groups.pop().unwrap();
@ -336,44 +394,54 @@ async fn todo(ctx: &Context, msg: &Message, target: TodoTarget, subcommand: SubC
});
for group in todo_groups {
let _ = msg.channel_id.send_message(&ctx, |m| m
.embed(|e| e
.title(format!("{} Todo", target.name()))
.description(group)
)
).await;
let _ = msg
.channel_id
.send_message(&ctx, |m| {
m.embed(|e| {
e.title(format!("{} Todo", target.name()))
.description(group)
})
})
.await;
}
},
}
SubCommand::Add => {
let content = user_data.response(&pool, "todo/added").await
let content = user_data
.response(&pool, "todo/added")
.await
.replacen("{name}", &extra, 1);
target.add(extra, pool).await.unwrap();
let _ = msg.channel_id.say(&ctx, content).await;
},
}
SubCommand::Remove => {
let _ = if let Ok(num) = extra.parse::<usize>() {
if let Ok(todo) = target.remove(num - 1, &pool).await {
let content = user_data.response(&pool, "todo/removed").await
.replacen("{}", &todo.value, 1);
let content = user_data.response(&pool, "todo/removed").await.replacen(
"{}",
&todo.value,
1,
);
msg.channel_id.say(&ctx, content)
} else {
msg.channel_id
.say(&ctx, user_data.response(&pool, "todo/error_index").await)
}
else {
msg.channel_id.say(&ctx, user_data.response(&pool, "todo/error_index").await)
}
}
else {
let content = user_data.response(&pool, "todo/error_value").await
} else {
let content = user_data
.response(&pool, "todo/error_value")
.await
.replacen("{prefix}", &prefix, 1)
.replacen("{command}", &target.command(Some(subcommand)), 1);
msg.channel_id.say(&ctx, content)
}.await;
},
}
.await;
}
SubCommand::Clear => {
target.clear(&pool).await.unwrap();
@ -381,6 +449,6 @@ async fn todo(ctx: &Context, msg: &Message, target: TodoTarget, subcommand: SubC
let content = user_data.response(&pool, "todo/cleared").await;
let _ = msg.channel_id.say(&ctx, content).await;
},
}
}
}