Add comments, do minor cleanup

This commit is contained in:
Agatha Rose 2020-06-11 19:51:17 +03:00
parent e6de3ed9f9
commit 0a1cc50c82
No known key found for this signature in database
GPG Key ID: 3F9F2317B3D5C3AC
1 changed files with 40 additions and 14 deletions

View File

@ -54,13 +54,14 @@ impl EventHandler for Handler {
#[group] #[group]
#[commands( #[commands(
init, ping, halt, list_srv, host, ship, bottom_rng, headpat, uwu, gayculator, sausage, help, init, ping, halt, servers, host, ship, bottom_rng, headpat, uwu, gayculator, sausage, help,
embed, define, owo, info, echo, desc, pinned, brainfuck embed, define, owo, info, echo, desc, pinned, brainfuck
)] )]
struct General; struct General;
lazy_static! { lazy_static! {
static ref OWNERS: std::vec::Vec<serenity::model::id::UserId> = static ref OWNERS: std::vec::Vec<serenity::model::id::UserId> =
/* Agatha's Id Julia's Id */
vec![UserId(254310746450690048), UserId(687740609703706630)]; vec![UserId(254310746450690048), UserId(687740609703706630)];
} }
@ -75,6 +76,7 @@ fn main() {
let mut client = Client::new(&env::var("DISCORD_TOKEN").expect("Invalid token"), Handler) let mut client = Client::new(&env::var("DISCORD_TOKEN").expect("Invalid token"), Handler)
.expect("Error creating client"); .expect("Error creating client");
// Updates stored data, used for ping command
{ {
let mut data = client.data.write(); let mut data = client.data.write();
data.insert::<ShardManagerContainer>(Arc::clone(&client.shard_manager)); data.insert::<ShardManagerContainer>(Arc::clone(&client.shard_manager));
@ -92,14 +94,22 @@ fn main() {
}) })
.on_dispatch_error(|ctx, msg, error| { .on_dispatch_error(|ctx, msg, error| {
if let DispatchError::CheckFailed("Owner", Reason::Unknown) = error { if let DispatchError::CheckFailed("Owner", Reason::Unknown) = error {
// triggers if user is not owner
let _ = msg.channel_id.say(&ctx.http, "nyo"); let _ = msg.channel_id.say(&ctx.http, "nyo");
} else if let DispatchError::Ratelimited(seconds) = error { } else if let DispatchError::Ratelimited(_) = error {
let _ = msg // triggers if rate limited
.channel_id eprintln!(
.say(&ctx.http, &format!("Try again in {} seconds.", seconds)); "{}",
format!(
"Rate limited in {} with message {}",
msg.channel_id.to_string().purple().bold(),
msg.content.purple()
)
);
} }
}) })
.after(|ctx, msg, cmd_name, error| { .after(|ctx, msg, cmd_name, error| {
// prints error in chat
if let Err(why) = error { if let Err(why) = error {
let _ = msg.channel_id.send_message(&ctx.http, |m| { let _ = msg.channel_id.send_message(&ctx.http, |m| {
m.embed(|e| { m.embed(|e| {
@ -109,6 +119,7 @@ fn main() {
.colour(0xff6961) .colour(0xff6961)
}) })
}); });
// prints error in console
eprintln!( eprintln!(
"{}", "{}",
format!("Error in {}: {}", cmd_name.purple(), &why.0.red().bold()) format!("Error in {}: {}", cmd_name.purple(), &why.0.red().bold())
@ -191,9 +202,6 @@ fn ping(ctx: &mut Context, message: &Message) -> CommandResult {
fn echo(ctx: &mut Context, message: &Message, args: Args) -> CommandResult { fn echo(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
let input: String = args.rest().trim().to_string(); let input: String = args.rest().trim().to_string();
if args.is_empty() { if args.is_empty() {
let _ = message
.channel_id
.say(&ctx.http, "Error: called without input!");
return Err(CommandError("Called without input".to_string())); return Err(CommandError("Called without input".to_string()));
} }
@ -205,6 +213,7 @@ fn echo(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
#[command] #[command]
#[checks(Owner)] #[checks(Owner)]
fn halt(ctx: &mut Context) -> CommandResult { fn halt(ctx: &mut Context) -> CommandResult {
// Workaround for discord not doing this automatically
ctx.set_presence(None, OnlineStatus::Offline); ctx.set_presence(None, OnlineStatus::Offline);
use std::{thread, time}; use std::{thread, time};
@ -216,7 +225,7 @@ fn halt(ctx: &mut Context) -> CommandResult {
#[command] #[command]
#[checks(Owner)] #[checks(Owner)]
fn list_srv(ctx: &mut Context, message: &Message) -> CommandResult { fn servers(ctx: &mut Context, message: &Message) -> CommandResult {
let mut list = String::new(); let mut list = String::new();
let cache = ctx.cache.read(); let cache = ctx.cache.read();
for (index, guild_lock) in cache.guilds.values().enumerate() { for (index, guild_lock) in cache.guilds.values().enumerate() {
@ -225,6 +234,7 @@ fn list_srv(ctx: &mut Context, message: &Message) -> CommandResult {
} }
let _ = message let _ = message
.channel_id .channel_id
// Add zero width space to all mentions
.say(&ctx.http, list.replace("@", "@\u{200B}")); .say(&ctx.http, list.replace("@", "@\u{200B}"));
Ok(()) Ok(())
@ -269,6 +279,7 @@ fn embed(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
url: Option<String>, url: Option<String>,
} }
// print documentation from src/embed-docs.txt
if &args.rest().trim().to_string() == "help" { if &args.rest().trim().to_string() == "help" {
let mut file = fs::File::open("./src/embed-docs.txt")?; let mut file = fs::File::open("./src/embed-docs.txt")?;
let mut help_string = String::new(); let mut help_string = String::new();
@ -362,10 +373,12 @@ fn embed(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
Ok(()) Ok(())
} }
// generate a random number using a keysmash as seed
#[command] #[command]
fn bottom_rng(ctx: &mut Context, message: &Message, mut args: Args) -> CommandResult { fn bottom_rng(ctx: &mut Context, message: &Message, mut args: Args) -> CommandResult {
use rand::{rngs::StdRng, SeedableRng}; use rand::{rngs::StdRng, SeedableRng};
// 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 messages = message
.channel_id .channel_id
@ -374,6 +387,7 @@ fn bottom_rng(ctx: &mut Context, message: &Message, mut args: Args) -> CommandRe
let _ = message.channel_id.say(&ctx.http, format!("Error: {}", e)); let _ = message.channel_id.say(&ctx.http, format!("Error: {}", e));
} else { } else {
let mut messages = messages?; let mut messages = messages?;
// remove all messages by other users
messages.retain(|v| v.author != message.mentions[0]); messages.retain(|v| v.author != message.mentions[0]);
let mut input = String::new(); let mut input = String::new();
for msg in messages { for msg in messages {
@ -411,6 +425,7 @@ fn ship(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
.map(|x| x.to_owned()) .map(|x| x.to_owned())
.collect::<Vec<String>>(); .collect::<Vec<String>>();
// Concatenate names together
let shipname: Result<String, String> = match names.len() { let shipname: Result<String, String> = match names.len() {
0 => Err("Invalid input!".to_string()), 0 => Err("Invalid input!".to_string()),
1 => Ok(names[0].clone()), 1 => Ok(names[0].clone()),
@ -455,6 +470,7 @@ fn headpat(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
return Err(CommandError("Please specify a username!".to_string())); return Err(CommandError("Please specify a username!".to_string()));
} }
// Get username from first mention, otherwise use input text
let name = match message.mentions.len() { let name = match message.mentions.len() {
0 => args, 0 => args,
_ => message.mentions[0].name.as_str(), _ => message.mentions[0].name.as_str(),
@ -475,6 +491,7 @@ fn headpat(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
Ok(()) Ok(())
} }
// send a random uwu image
#[command] #[command]
fn uwu(ctx: &mut Context, message: &Message) -> CommandResult { fn uwu(ctx: &mut Context, message: &Message) -> CommandResult {
let images = [ let images = [
@ -552,7 +569,7 @@ fn help(ctx: &mut Context, message: &Message) -> CommandResult {
true, true,
), ),
( (
"owo!embed ``[args]``", "owo!embed ``[args]`` *OR* help",
"Create an embed from a Toml object", "Create an embed from a Toml object",
true, true,
), ),
@ -562,13 +579,13 @@ fn help(ctx: &mut Context, message: &Message) -> CommandResult {
"Display channel's Nth pinned message. Channel name is optional", "Display channel's Nth pinned message. Channel name is optional",
true, true,
), ),
("owo!brainfuck ``input``", "execute input code", true), ("owo!brainfuck ``input``", "Execute input code", true),
("owo!ship ``[names]``", "*Shipping intensifies*", true), ("owo!ship ``[names]``", "*Shipping intensifies*", true),
("owo!headpat ``name``", "Headpat someone", true), ("owo!headpat ``name``", "Headpat someone", true),
("owo!owo ``text``", "owoify input text", true), ("owo!owo ``text``", "owoify input text", true),
("\u{200B}", "**Admin commands:**", false), ("\u{200B}", "**Admin commands:**", false),
("owo!halt", "Kill the bot process", true), ("owo!halt", "Kill the bot process", true),
("owo!list_srv", "List my servers", true), ("owo!servers", "List the servers I'm in", true),
("owo!host", "Display host info", true), ("owo!host", "Display host info", true),
]) ])
.color(0xffd1dc) .color(0xffd1dc)
@ -585,13 +602,15 @@ fn info(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
} }
let num = ctx.cache.read().guilds.len(); let num = ctx.cache.read().guilds.len();
// get developer's username
let aganame = OWNERS.clone()[0].to_user(ctx.http.clone())?.tag(); let aganame = OWNERS.clone()[0].to_user(ctx.http.clone())?.tag();
let _ = message.channel_id.send_message(&ctx.http, |m| m let _ = message.channel_id.send_message(&ctx.http, |m| m
.embed(|e| e .embed(|e| e
.title("Discordinator9000's info:") .title("Discordinator9000's info:")
.field("Author:", format!("{} / Agatha", aganame), false) .field("Author:", format!("{} / Agatha", aganame), false)
.field("Server count:", num , false) .field("Server count:", num , false)
.field("Invite:", "[Invite link](https://discordapp.com/api/oauth2/authorize?client_id=470350233419907129&permissions=2048&scope=bot)", false ) .field("Invite:", "[Invite link](https://discordapp.com/api/oauth2/authorize?client_id=470350233419907129&permissions=2048&scope=bot)", true )
.field("source:", "[Gitlab](https://gitlab.com/agathasorceress/rustcord)", true)
.footer(|f| f .footer(|f| f
.text("Written in Rust using Serenity, OwOify and a few other libraries")) .text("Written in Rust using Serenity, OwOify and a few other libraries"))
.thumbnail("https://cdn.discordapp.com/attachments/687011390434967621/704118007563157544/discordinator.png") .thumbnail("https://cdn.discordapp.com/attachments/687011390434967621/704118007563157544/discordinator.png")
@ -600,6 +619,7 @@ fn info(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
Ok(()) Ok(())
} }
// Urban Dictionary lookup
#[command] #[command]
#[aliases("what's this")] #[aliases("what's this")]
fn define(ctx: &mut Context, message: &Message, args: Args) -> CommandResult { fn define(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
@ -634,6 +654,7 @@ fn define(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
Ok(()) Ok(())
} }
// Text owoification
#[command] #[command]
fn owo(ctx: &mut Context, message: &Message, args: Args) -> CommandResult { fn owo(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
use owoify::OwOifiable; use owoify::OwOifiable;
@ -644,6 +665,7 @@ fn owo(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
Ok(()) Ok(())
} }
// Prints channel topic
#[command] #[command]
#[aliases("description", "topic")] #[aliases("description", "topic")]
fn desc(ctx: &mut Context, message: &Message) -> CommandResult { fn desc(ctx: &mut Context, message: &Message) -> CommandResult {
@ -678,9 +700,12 @@ fn desc(ctx: &mut Context, message: &Message) -> CommandResult {
Ok(()) Ok(())
} }
// Prints Nth pinned message
#[command] #[command]
fn pinned(ctx: &mut Context, message: &Message, mut args: Args) -> CommandResult { fn pinned(ctx: &mut Context, message: &Message, mut args: Args) -> CommandResult {
// defaults to latest pinned message if no args are provided
let mut idx = args.single::<usize>().unwrap_or(1); let mut idx = args.single::<usize>().unwrap_or(1);
// Makes pinned messages 1-indexed
if idx != 0 { if idx != 0 {
idx -= 1; idx -= 1;
} }
@ -724,6 +749,7 @@ fn pinned(ctx: &mut Context, message: &Message, mut args: Args) -> CommandResult
Ok(()) Ok(())
} }
// brainfuck interpreter
#[command] #[command]
#[aliases("bf", "brainfrick")] #[aliases("bf", "brainfrick")]
fn brainfuck(ctx: &mut Context, message: &Message, args: Args) -> CommandResult { fn brainfuck(ctx: &mut Context, message: &Message, args: Args) -> CommandResult {
@ -731,7 +757,7 @@ fn brainfuck(ctx: &mut Context, message: &Message, args: Args) -> CommandResult
let input = match args.rest().trim() { let input = match args.rest().trim() {
"" => { "" => {
return Err(CommandError("Empty input!".to_string())); return Err(CommandError("Called without input!".to_string()));
} }
v @ _ => v, v @ _ => v,
}; };