Skip to content

Commit

Permalink
feat: add ping command
Browse files Browse the repository at this point in the history
  • Loading branch information
Plarpoon committed Apr 11, 2024
1 parent 741a958 commit 3f4e9a6
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ edition = "2021"
dotenv = "0.15.0"
poise = "0.6.1"
tokio = { version = "1.37.0", features = ["full", "rt-multi-thread"] }
env_logger = "0.11.3"
env_logger = "0.11.3"
anyhow = "1.0.82"
regex = "1.10.4"
32 changes: 32 additions & 0 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::process::Command;
use std::str;
use crate::{Context, Error};

/// Show this help menu
Expand Down Expand Up @@ -76,3 +78,33 @@ pub async fn getvotes(

Ok(())
}

/// Ping a server and return the average time
///
/// This command pings Cloudflare's DNS server (1.1.1.1) 10 times and returns the average time.
/// ```
/// ~ping
/// ```
#[poise::command(prefix_command, slash_command)]
pub async fn ping(ctx: Context<'_>) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let output = Command::new("ping")
.args(&["-c", "10", "1.1.1.1"])
.output()
.expect("Failed to execute command");

let output_str = str::from_utf8(&output.stdout).unwrap();
let lines: Vec<&str> = output_str.split('\n').collect();
let avg_line = lines
.iter()
.find(|line| line.contains("avg"))
.ok_or_else(|| anyhow::anyhow!("Could not find avg in ping output"))?;

let re = regex::Regex::new(r"(\d+\.\d+)/").unwrap();
let cap = re.captures(avg_line).ok_or_else(|| anyhow::anyhow!("Could not find avg in ping output"))?;
let avg = &cap[1];

let response = format!("Pong! 🏓\nThe average of 10 pings to Cloudflare's DNS (1.1.1.1) is\n{} ms", avg);
ctx.say(response).await?;

Ok(())
}
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ async fn main() {
// FrameworkOptions contains all of poise's configuration option in one struct
// Every option can be omitted to use its default value
let options = poise::FrameworkOptions {
commands: vec![commands::help(), commands::vote(), commands::getvotes()],
commands: vec![commands::help(), commands::vote(), commands::getvotes(), commands::ping()],
prefix_options: poise::PrefixFrameworkOptions {
prefix: Some("~".into()),
edit_tracker: Some(Arc::new(poise::EditTracker::for_timespan(
Expand Down

0 comments on commit 3f4e9a6

Please sign in to comment.