From d15ec0c93e655802497dbb4980219a319b60fa2c Mon Sep 17 00:00:00 2001 From: MedzikUser Date: Fri, 19 Aug 2022 22:27:42 +0200 Subject: [PATCH] feat(command): add /broadcast The `/broadcast` command has been added, which can send a message to all connected clients. --- src/commands/broadcast.rs | 54 +++++++++++++++++++++++++++++++++++++++ src/commands/id.rs | 4 +-- src/commands/mod.rs | 10 ++++++-- 3 files changed, 64 insertions(+), 4 deletions(-) create mode 100644 src/commands/broadcast.rs diff --git a/src/commands/broadcast.rs b/src/commands/broadcast.rs new file mode 100644 index 0000000..8d26514 --- /dev/null +++ b/src/commands/broadcast.rs @@ -0,0 +1,54 @@ +use async_std::task; + +use crate::{plugins::prelude::*, CLIENTS}; + +pub struct Broadcast; + +#[async_trait] +impl Command for Broadcast { + fn name(&self) -> &'static str { + "/broadcast" + } + + fn aliases(&self) -> Vec<&'static str> { + vec![] + } + + fn help(&self) -> &'static str { + "Send message to all connected clients" + } + + fn usage(&self) -> &'static str { + "/broadcast " + } + + async fn execute(&self, client: &Client, args: Vec<&str>) -> anyhow::Result<()> { + if args.len() < 1 || args.join(" ").is_empty() { + client.send("Missing message")?; + return Ok(()); + } + + let msg = args.join(" "); + + let mut children = Vec::new(); + + // send message to all connected clients + for (_i, client) in CLIENTS.lock().unwrap().clone() { + let msg = msg.clone(); + let child = task::spawn(async move { + client + .send(msg) + .expect("failed to send broadcast message to client") + }); + + children.push(child); + } + + // wait for all task to complete + for child in children { + child.await; + } + + Ok(()) + } +} diff --git a/src/commands/id.rs b/src/commands/id.rs index d1e743e..739c855 100644 --- a/src/commands/id.rs +++ b/src/commands/id.rs @@ -1,9 +1,9 @@ use crate::plugins::prelude::*; -pub struct ID; +pub struct Id; #[async_trait] -impl Command for ID { +impl Command for Id { fn name(&self) -> &'static str { "/id" } diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 085ad3c..e6b4c45 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,11 +1,17 @@ +mod broadcast; mod disconnect; mod help; mod id; -use self::{disconnect::Disconnect, help::Help, id::ID}; +use self::{broadcast::Broadcast, disconnect::Disconnect, help::Help, id::Id}; use crate::plugins::prelude::*; /// Register default commands pub fn register_commands() -> Vec> { - vec![Box::new(Help), Box::new(Disconnect), Box::new(ID)] + vec![ + Box::new(Broadcast), + Box::new(Disconnect), + Box::new(Help), + Box::new(Id), + ] }