Rustbot/src/commands/uptime.rs

53 lines
1.4 KiB
Rust
Raw Normal View History

2024-01-06 22:43:10 -05:00
use crate::Error;
use sysinfo::System;
use uptime_lib::get;
use std::time::{
Duration,
SystemTime,
UNIX_EPOCH
};
/// Retrieve host and bot uptimes
#[poise::command(slash_command)]
pub async fn uptime(ctx: poise::Context<'_, (), Error>) -> Result<(), Error> {
let mut sys = System::new_all();
sys.refresh_all();
// Fetch system's uptime
let sys_uptime = get().unwrap().as_secs();
// Fetch bot's process uptime
let curr_pid = sysinfo::get_current_pid().unwrap();
let now = SystemTime::now();
let mut proc_uptime = 0;
if let Some(process) = sys.process(curr_pid) {
let time_started = UNIX_EPOCH + Duration::from_secs(process.start_time());
proc_uptime = now.duration_since(time_started).unwrap().as_secs();
}
ctx.reply(format!("System: `{}`\nProcess: `{}`", format_duration(sys_uptime), format_duration(proc_uptime))).await?;
Ok(())
}
fn format_duration(secs: u64) -> String {
let days = secs / 86400;
let hours = (secs % 86400) / 3600;
let minutes = (secs % 3600) / 60;
let seconds = secs % 60;
let mut formatted_string = String::new();
if days > 0 {
formatted_string.push_str(&format!("{}d, ", days));
2024-01-06 22:43:10 -05:00
}
if hours > 0 || days > 0 {
formatted_string.push_str(&format!("{}h, ", hours));
2024-01-06 22:43:10 -05:00
}
if minutes > 0 || hours > 0 {
formatted_string.push_str(&format!("{}m, ", minutes));
2024-01-06 22:43:10 -05:00
}
formatted_string.push_str(&format!("{}s", seconds));
formatted_string
}