Skip to content

Commit

Permalink
refactor: clean code style and patterns
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanccn committed Nov 8, 2023
1 parent b846a6e commit 4240625
Show file tree
Hide file tree
Showing 10 changed files with 33 additions and 30 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@
.env
.env.*
!.env.example

# IDEs
.vscode/
.idea/
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ redis-macros = "0.2.1"
regex = "1.10.2"
reqwest = { version = "0.11.22", default-features = false, features = ["rustls-tls", "json", "brotli"] }
serde = { version = "1.0.190", features = ["derive"] }
serde_json = "1.0.107"
serde_json = "1.0.108"
tokio = { version = "1.33.0", features = ["full"] }

[profile.release]
Expand Down
2 changes: 1 addition & 1 deletion src/commands/owo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use anyhow::Result;

use crate::Context;

/// Pong!
/// owo
#[poise::command(slash_command, guild_only)]
pub async fn owo(ctx: Context<'_>) -> Result<()> {
ctx.say("owo").await?;
Expand Down
4 changes: 2 additions & 2 deletions src/commands/pomelo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ pub async fn pomelo(ctx: Context<'_>) -> Result<()> {
if let Some(guild) = ctx.guild_id() {
ctx.defer().await?;

let members = guild
let members: Vec<_> = guild
.members(&ctx, None, None)
.await?
.into_iter()
.filter(|m| !m.user.bot)
.collect::<Vec<serenity::Member>>();
.collect();

let mut nonmigrated_users: Vec<&serenity::UserId> = vec![];

Expand Down
11 changes: 4 additions & 7 deletions src/commands/self_timeout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,9 @@ pub async fn self_timeout(
#[description = "The duration to time yourself out for"] duration: String,
) -> Result<()> {
ctx.defer_ephemeral().await?;
let duration = humantime::parse_duration(&duration);

if let Ok(duration) = duration {
let member = ctx.author_member().await;

if let Some(mut member) = member {
if let Ok(duration) = humantime::parse_duration(&duration) {
if let Some(mut member) = ctx.author_member().await {
let start = chrono::Utc::now();
let end = start + duration;
let end_serenity = serenity::Timestamp::from_unix_timestamp(end.timestamp())?;
Expand All @@ -41,10 +38,10 @@ pub async fn self_timeout(
.await?;
} else {
ctx.say("Error: Member unavailable!").await?;
}
};
} else {
ctx.say("Error: Invalid duration!").await?;
}
};

Ok(())
}
6 changes: 2 additions & 4 deletions src/handlers/github_expansion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,8 @@ pub async fn handle(message: &serenity::Message, ctx: &serenity::Context) -> Res
.collect();

let idx_start = start - 1;
let idx_end = match end {
Some(end) => end,
None => start,
};
let idx_end = end.unwrap_or(start);

let selected_lines = &lines[idx_start..idx_end];

let embed = serenity::CreateEmbed::new()
Expand Down
15 changes: 11 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::{Error, Result};
use anyhow::{Context as AnyhowContext, Error, Result};
use owo_colors::OwoColorize;

use poise::{
Expand All @@ -19,12 +19,16 @@ mod presence_api;
mod reqwest_client;
mod utils;

#[deny(unsafe_code)]
#[tokio::main]
async fn main() -> Result<()> {
#[cfg(debug_assertions)]
dotenvy::dotenv().ok();

let mut client = Client::builder(std::env::var("DISCORD_TOKEN")?, GatewayIntents::all())
let token = std::env::var("DISCORD_TOKEN")
.context("Could not obtain DISCORD_TOKEN from environment!")?;

let mut client = Client::builder(token, GatewayIntents::all())
.framework(Framework::new(
FrameworkOptions {
commands: commands::to_vec(),
Expand Down Expand Up @@ -63,8 +67,11 @@ async fn main() -> Result<()> {
},
|ctx, ready, framework| {
Box::pin(async move {
let tag = ready.user.tag();
println!("{} to Discord as {}", "Connected".green(), tag.cyan());
println!(
"{} to Discord as {}",
"Connected".green(),
ready.user.tag().cyan()
);

let commands = &framework.options().commands;

Expand Down
4 changes: 1 addition & 3 deletions src/presence_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,7 @@ pub async fn serve() -> anyhow::Result<()> {
true => "127.0.0.1".to_owned(),
false => "0.0.0.0".to_owned(),
});
let port = std::env::var("PORT")
.unwrap_or("8080".to_owned())
.parse::<u16>()?;
let port = std::env::var("PORT").map_or(Ok(8080), |v| v.parse::<u16>())?;

println!(
"{} API server {}",
Expand Down
11 changes: 5 additions & 6 deletions src/utils/error_handling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,10 @@ impl ValfiskError<'_> {
}

pub async fn handle_report(&self) {
let channel_id = match std::env::var("ERROR_LOGS_CHANNEL") {
Ok(channel_id_str) => Some(channel_id_str.parse::<u64>()),
Err(_) => None,
};

if let Some(Ok(channel_id)) = channel_id {
if let Ok(channel_id) = match std::env::var("ERROR_LOGS_CHANNEL") {
Ok(channel_id_str) => channel_id_str.parse::<u64>().map_err(anyhow::Error::from),
Err(err) => Err(anyhow::Error::from(err)),
} {
let channel = ChannelId::new(channel_id);

let embed = CreateEmbed::new()
Expand Down Expand Up @@ -113,6 +111,7 @@ impl ValfiskError<'_> {
}
}

/// Log the error to the console, send an error reply to the command, and report the error in the error channel
pub async fn handle_all(&self) {
self.handle_log();
self.handle_reply().await;
Expand Down

0 comments on commit 4240625

Please sign in to comment.