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::{
framework::standard::{macros::command, Args, CommandResult},
framework::standard::{macros::command, Args, CommandError, CommandResult},
model::channel::Message,
prelude::*,
};
@ -8,36 +8,32 @@ use serenity::{
#[command]
#[aliases("what's this")]
async fn define(ctx: &Context, message: &Message, args: Args) -> CommandResult {
let text: String = args.rest().trim().to_string();
let defs = &urbandict::get_definitions(&text);
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());
}
}
}
if args.is_empty() {
return Err("No arguments!".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(())
}

View File

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

View File

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

View File

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

View File

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