Merge pull request 'beeeeg refactor :3' (#1) from videogame-hacker/rustcord:patch/cleanup-match-statements into master

Reviewed-on: #1
This commit is contained in:
Agatha Lovelace 2021-07-08 15:42:24 +00:00
commit 8b0313c942
5 changed files with 122 additions and 151 deletions

View File

@ -1,5 +1,5 @@
use serenity::{ use serenity::{
framework::standard::{macros::command, Args, CommandResult}, framework::standard::{macros::command, Args, CommandError, CommandResult},
model::channel::Message, model::channel::Message,
prelude::*, prelude::*,
}; };
@ -8,36 +8,32 @@ use serenity::{
#[command] #[command]
#[aliases("what's this")] #[aliases("what's this")]
async fn define(ctx: &Context, message: &Message, args: Args) -> CommandResult { async fn define(ctx: &Context, message: &Message, args: Args) -> CommandResult {
let text: String = args.rest().trim().to_string(); if args.is_empty() {
let defs = &urbandict::get_definitions(&text); return Err("No arguments!".into());
if !args.is_empty() {
match defs {
Err(_e) => {
return Err("Invalid query >w<".into());
}
Ok(v) => {
if !v.is_empty() {
let def = &v[0];
let _ = message
.channel_id
.send_message(&ctx.http, |m| {
m.embed(|e| {
e.title(format!("Query: {}, Author: {}", text, def.author))
.field(
"Definition: ",
def.definition.replace(|c| c == '[' || c == ']', ""),
false,
)
.color(0xffd1dc)
})
})
.await;
} else {
return Err("No results!".into());
}
}
}
} }
let text: String = args.rest().trim().to_string();
let defs =
urbandict::get_definitions(&text).map_err(|_| CommandError::from("Invalid query >w<"))?;
let def = defs
.first()
.ok_or_else(|| CommandError::from("No results!"))?;
let _ = message
.channel_id
.send_message(&ctx.http, |m| {
m.embed(|e| {
e.title(format!("Query: {}, Author: {}", text, def.author))
.field(
"Definition: ",
def.definition.replace(|c| c == '[' || c == ']', ""),
false,
)
.color(0xffd1dc)
})
})
.await;
Ok(()) Ok(())
} }

View File

@ -1,7 +1,7 @@
use percent_encoding::{percent_encode, NON_ALPHANUMERIC}; use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
use serde::Deserialize; use serde::Deserialize;
use serenity::{ use serenity::{
framework::standard::{macros::command, Args, CommandResult}, framework::standard::{macros::command, Args, CommandError, CommandResult},
model::channel::Message, model::channel::Message,
prelude::*, prelude::*,
}; };
@ -24,24 +24,19 @@ async fn lyrics(ctx: &Context, message: &Message, args: Args) -> CommandResult {
// TODO: use https://orion.apiseeds.com/api/music/lyric/:artist/:track instead // TODO: use https://orion.apiseeds.com/api/music/lyric/:artist/:track instead
let mut url = String::from("https://mourits.xyz:2096/?q="); let mut url = String::from("https://mourits.xyz:2096/?q=");
// check if input is not empty // check if input is not empty
let input = match args.rest().trim() { let input = args.rest().trim();
"" => { if input.is_empty() {
return Err("Called without input!".into()); return Err("Called without input!".into());
} }
v => v,
};
// encode into url // encode into url
url += &s!(percent_encode(input.as_bytes(), NON_ALPHANUMERIC)); url += &s!(percent_encode(input.as_bytes(), NON_ALPHANUMERIC));
let request = match reqwest::get(&url).await { let request = reqwest::get(&url).await?;
Ok(v) => v,
Err(e) => return Err(e.into()),
};
let resp: Response = match request.json().await { let resp: Response = request
Ok(v) => v, .json()
Err(_) => return Err("Could not find lyrics".into()), .await
}; .map_err(|_| CommandError::from("Could not find lyrics"))?;
let _ = message let _ = message
.channel_id .channel_id
.send_message(&ctx.http, |m| { .send_message(&ctx.http, |m| {

View File

@ -1,5 +1,5 @@
use serenity::{ use serenity::{
framework::standard::{macros::command, Args, CommandResult}, framework::standard::{macros::command, Args, CommandError, CommandResult},
model::{channel::Message, id::ChannelId}, model::{channel::Message, id::ChannelId},
prelude::*, prelude::*,
}; };
@ -19,12 +19,10 @@ async fn pinned(ctx: &Context, message: &Message, mut args: Args) -> CommandResu
Ok(v) => v, Ok(v) => v,
Err(_) => message.channel_id, Err(_) => message.channel_id,
}; };
let pinned = match target_channel.pins(&ctx.http).await { let pinned = target_channel
Ok(v) => v, .pins(&ctx.http)
Err(e) => { .await
return Err(format!("Could not get pinned messages! Error: {}", e).into()); .map_err(|e| CommandError::from(format!("Could not get pinned messages! Error: {}", e)))?;
}
};
if pinned.is_empty() { if pinned.is_empty() {
return Err("No pinned messages found!".into()); return Err("No pinned messages found!".into());
} }

View File

@ -1,6 +1,6 @@
use serenity::{ use serenity::{
builder::CreateMessage, builder::CreateMessage,
framework::standard::{macros::command, Args, CommandResult}, framework::standard::{macros::command, Args, CommandError, CommandResult},
http::AttachmentType, http::AttachmentType,
model::channel::Message, model::channel::Message,
prelude::*, prelude::*,
@ -10,11 +10,11 @@ use serenity::{
#[command] #[command]
async fn spoiler(ctx: &Context, message: &Message, args: Args) -> CommandResult { async fn spoiler(ctx: &Context, message: &Message, args: Args) -> CommandResult {
// check if the message has any attachments // check if the message has any attachments
let attachments = match message.attachments.is_empty() {
true => { let attachments = if message.attachments.is_empty() {
return Err("No images were attached!".into()); return Err("No images were attached!".into());
} } else {
false => &message.attachments, &message.attachments
}; };
// get the author's nick in the server, otherwise default to global username later // get the author's nick in the server, otherwise default to global username later
@ -42,10 +42,10 @@ async fn spoiler(ctx: &Context, message: &Message, args: Args) -> CommandResult
for a in attachments { for a in attachments {
// download each attachment // download each attachment
let content = match a.download().await { let content = a
Ok(content) => content, .download()
Err(_) => return Err("Error downloading attachment".into()), .await
}; .map_err(|_| CommandError::from("Error downloading attachment"))?;
let content: &[u8] = content.as_slice(); let content: &[u8] = content.as_slice();

View File

@ -14,7 +14,8 @@ use serenity::{
}, },
framework::standard::{ framework::standard::{
macros::{check, command, group, hook}, macros::{check, command, group, hook},
Args, CommandOptions, CommandResult, DispatchError, Reason, StandardFramework, Args, CommandError, CommandOptions, CommandResult, DispatchError, Reason,
StandardFramework,
}, },
model::{ model::{
channel::{Message, ReactionType}, channel::{Message, ReactionType},
@ -91,30 +92,27 @@ async fn dispatch_error(ctx: &Context, msg: &Message, error: DispatchError) {
#[hook] #[hook]
async fn after(ctx: &Context, msg: &Message, command_name: &str, command_result: CommandResult) { async fn after(ctx: &Context, msg: &Message, command_name: &str, command_result: CommandResult) {
// prints error in chat // prints error in chat
match command_result { if let Err(why) = command_result {
Ok(()) => (), let _ = msg
Err(why) => { .channel_id
let _ = msg .send_message(&ctx.http, |m| {
.channel_id m.embed(|e| {
.send_message(&ctx.http, |m| { e.title(format!("Error in **{}**", command_name))
m.embed(|e| { .description(&why.to_string())
e.title(format!("Error in **{}**", command_name)) /*.thumbnail("https://i.imgur.com/VzOEz2E.png") oh no */
.description(&why.to_string()) .colour(0xff6961)
/*.thumbnail("https://i.imgur.com/VzOEz2E.png") oh no */
.colour(0xff6961)
})
}) })
.await; })
// prints error in console .await;
eprintln!( // prints error in console
"{}", eprintln!(
format!( "{}",
"Error in {}: {}", format!(
command_name.purple(), "Error in {}: {}",
&why.to_string().red().bold() command_name.purple(),
) &why.to_string().red().bold()
); )
} );
} }
} }
@ -209,23 +207,21 @@ async fn ping(ctx: &Context, message: &Message) -> CommandResult {
// I have no idea if this works but its 5æm and I need to sleep help // I have no idea if this works but its 5æm and I need to sleep help
let data = ctx.data.read().await; let data = ctx.data.read().await;
let shard_manager = match data.get::<ShardManagerContainer>() { let shard_manager = data
Some(v) => v, .get::<ShardManagerContainer>()
None => return Err("There was a problem getting the shard manager!".into()), .ok_or_else(|| CommandError::from("There was a problem getting the shard manager!"))?;
};
let manager = shard_manager.lock().await; let manager = shard_manager.lock().await;
let runners = manager.runners.lock().await; let runners = manager.runners.lock().await;
let runner = match runners.get(&ShardId(ctx.shard_id)) { let runner = runners
Some(v) => v, .get(&ShardId(ctx.shard_id))
None => return Err("No shard found!".into()), .ok_or_else(|| CommandError::from("No shard found!"))?;
};
let ping = match runner.latency { let ping = runner
Some(v) => v.as_millis(), .latency
None => return Err("Could not get latency!".into()), .ok_or_else(|| CommandError::from("Could not get latency!"))?
}; .as_millis();
let _ = message let _ = message
.channel_id .channel_id
@ -347,32 +343,29 @@ async fn bottom_rng(ctx: &Context, message: &Message, mut args: Args) -> Command
// get N last messages, otherwise 10 // get N last messages, otherwise 10
let num = args.single::<u64>().unwrap_or(10); let num = args.single::<u64>().unwrap_or(10);
let messages = message let mut messages = message
.channel_id .channel_id
.messages(&ctx.http, |get| get.before(message.id).limit(num)) .messages(&ctx.http, |get| get.before(message.id).limit(num))
.await; .await
if let Err(e) = messages { .map_err(|e| CommandError::from(format!("Error: {}", e)))?;
return Err(format!("Error: {}", e).into());
} else { // remove all messages by other users
let mut messages = messages?; messages.retain(|v| v.author != message.mentions[0]);
// remove all messages by other users let mut input = String::new();
messages.retain(|v| v.author != message.mentions[0]); for msg in messages {
let mut input = String::new(); input += &format!("{} ", msg.content);
for msg in messages {
input += &format!("{} ", msg.content);
}
let result: u64 = StdRng::seed_from_u64(calculate_hash(&input)).gen_range(0..100);
let _ = message
.channel_id
.send_message(&ctx.http, |m| {
m.embed(|e| {
e.title("Bottom RNG")
.description(format!("Result: {}", result))
.color(0x800869)
})
})
.await;
} }
let result: u64 = StdRng::seed_from_u64(calculate_hash(&input)).gen_range(0..100);
let _ = message
.channel_id
.send_message(&ctx.http, |m| {
m.embed(|e| {
e.title("Bottom RNG")
.description(format!("Result: {}", result))
.color(0x800869)
})
})
.await;
Ok(()) Ok(())
} }
@ -392,7 +385,7 @@ async fn headpat(ctx: &Context, message: &Message, args: Args) -> CommandResult
_ => message.mentions[0].name.as_str(), _ => message.mentions[0].name.as_str(),
}; };
if let Err(e) = message message
.channel_id .channel_id
.send_message(&ctx.http, |m| { .send_message(&ctx.http, |m| {
m.embed(|e| { m.embed(|e| {
@ -403,10 +396,7 @@ async fn headpat(ctx: &Context, message: &Message, args: Args) -> CommandResult
.description("[Source](https://www.pinterest.com/pin/377809856242075277/)") .description("[Source](https://www.pinterest.com/pin/377809856242075277/)")
}) })
}) })
.await .await?;
{
let _ = message.channel_id.say(&ctx.http, format!("{:?}", e)).await;
};
Ok(()) Ok(())
} }
@ -533,20 +523,18 @@ async fn pfp(ctx: &Context, message: &Message) -> CommandResult {
async fn owo(ctx: &Context, message: &Message, args: Args) -> CommandResult { async fn owo(ctx: &Context, message: &Message, args: Args) -> CommandResult {
use owoify::OwOifiable; use owoify::OwOifiable;
let lastmsg = match message let messages = message
.channel_id .channel_id
.messages(&ctx.http, |get| get.before(message.id).limit(1)) .messages(&ctx.http, |get| get.before(message.id).limit(1))
.await .await
{ .map_err(|_| CommandError::from("Could not get last message!"))?;
Ok(v) => v,
Err(_) => return Err("Could not get last message!".into()),
};
let lastmsg = &lastmsg[0].content; let lastmsg = &messages[0].content;
let input: String = match args.is_empty() { let input: String = if args.is_empty() {
true => s!(lastmsg), s!(lastmsg)
false => args.rest().trim().to_string(), } else {
args.rest().trim().to_string()
}; };
let _ = message.channel_id.say(&ctx.http, input.owoify()).await; let _ = message.channel_id.say(&ctx.http, input.owoify()).await;
@ -558,23 +546,17 @@ async fn owo(ctx: &Context, message: &Message, args: Args) -> CommandResult {
#[only_in(guilds)] #[only_in(guilds)]
#[aliases("description", "topic")] #[aliases("description", "topic")]
async fn desc(ctx: &Context, message: &Message) -> CommandResult { async fn desc(ctx: &Context, message: &Message) -> CommandResult {
let channel = match message.channel(&ctx).await { let channel = message
Some(ch) => ch, .channel(&ctx)
None => { .await
return Err("Could not get channel!".into()); .ok_or_else(|| CommandError::from("Could not get channel!"))?;
} let channel = channel
}; .guild()
let channel = match channel.guild() { .ok_or_else(|| CommandError::from("Could not get guild channel!"))?;
Some(g) => g,
None => {
return Err("Could not get guild channel!".into());
}
};
let topic = if channel.topic.clone().unwrap() != "" { let topic = match channel.topic.as_deref() {
channel.topic.clone().unwrap() Some("") | None => String::from("No channel topic found"),
} else { Some(topic) => topic.to_string(),
String::from("No channel topic found")
}; };
let _ = message let _ = message