feat(command): add /broadcast

The `/broadcast` command has been added, which can send a message to all connected clients.
This commit is contained in:
MedzikUser 2022-08-19 22:27:42 +02:00
parent 9f66c2b9d2
commit d15ec0c93e
No known key found for this signature in database
GPG Key ID: A5FAC1E185C112DB
3 changed files with 64 additions and 4 deletions

54
src/commands/broadcast.rs Normal file
View File

@ -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 <message>"
}
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(())
}
}

View File

@ -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"
}

View File

@ -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<Box<dyn Command>> {
vec![Box::new(Help), Box::new(Disconnect), Box::new(ID)]
vec![
Box::new(Broadcast),
Box::new(Disconnect),
Box::new(Help),
Box::new(Id),
]
}