From a6331d50b8d800165eeee8474eb52158b4899823 Mon Sep 17 00:00:00 2001 From: Joscha Date: Mon, 27 Feb 2023 12:04:00 +0100 Subject: [PATCH] Implement Command for Uptime --- CHANGELOG.md | 3 ++ src/bot/botrulez/uptime.rs | 60 ++++++++++++++++++++++++++------------ 2 files changed, 44 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5718f8c..d26a07d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ Procedure when bumping the version number: ## Unreleased +### Added +- `bot::botrulez::Uptime` now implements `bot::command::Command` + ## v0.3.1 - 2023-02-26 ### Added diff --git a/src/bot/botrulez/uptime.rs b/src/bot/botrulez/uptime.rs index a892ed3..8b1856f 100644 --- a/src/bot/botrulez/uptime.rs +++ b/src/bot/botrulez/uptime.rs @@ -4,7 +4,7 @@ use time::macros::format_description; use time::{Duration, OffsetDateTime, UtcOffset}; use crate::api::Message; -use crate::bot::command::{ClapCommand, Context}; +use crate::bot::command::{ClapCommand, Command, Context}; use crate::conn; pub fn format_time(t: OffsetDateTime) -> String { @@ -51,6 +51,45 @@ pub trait HasStartTime { fn start_time(&self) -> OffsetDateTime; } +impl Uptime { + fn formulate_reply(&self, ctx: &Context, bot: &B, connected: bool) -> String { + let start = bot.start_time(); + let now = OffsetDateTime::now_utc(); + + let mut reply = format!( + "/me has been up since {} ({})", + format_time(start), + format_duration(start - now), + ); + + if connected { + let since = ctx.joined.since; + reply.push_str(&format!( + ", connected since {} ({})", + format_time(since), + format_duration(since - now), + )); + } + + reply + } +} + +#[async_trait] +impl Command for Uptime +where + B: HasStartTime + Send, + E: From, +{ + async fn execute(&self, arg: &str, msg: &Message, ctx: &Context, bot: &mut B) -> Result<(), E> { + if arg.trim().is_empty() { + let reply = self.formulate_reply(ctx, bot, false); + ctx.reply(msg.id, reply).await?; + } + Ok(()) + } +} + /// Show how long the bot has been online. #[derive(Parser)] pub struct Args { @@ -74,24 +113,7 @@ where ctx: &Context, bot: &mut B, ) -> Result<(), E> { - let start = bot.start_time(); - let now = OffsetDateTime::now_utc(); - - let mut reply = format!( - "/me has been up since {} ({})", - format_time(start), - format_duration(start - now), - ); - - if args.connected { - let since = ctx.joined.since; - reply.push_str(&format!( - ", connected since {} ({})", - format_time(since), - format_duration(since - now), - )); - } - + let reply = self.formulate_reply(ctx, bot, args.connected); ctx.reply(msg.id, reply).await?; Ok(()) }