From aef9c4608ddfda124f11c638dfa1a3c82846f74a Mon Sep 17 00:00:00 2001 From: Johannes Heuel Date: Thu, 15 Feb 2024 13:26:25 +0100 Subject: [PATCH] add function to parse commands --- src/main.rs | 56 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 41 insertions(+), 15 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2ea05f2..913d3b1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,6 +30,35 @@ struct StateRef { standby: Standby, } +enum ChatCommand { + Play(Message, String), + Stop(Message), + Leave(Message), + Join(Message), + NotImplemented, +} + +fn parse_command(event: Event) -> Option { + match event { + Event::MessageCreate(msg_create) => { + if msg_create.guild_id.is_none() || !msg_create.content.starts_with('!') { + return None; + } + let split: Vec<&str> = msg_create.content.splitn(2, ' ').collect(); + match split.as_slice() { + ["!play", query] => { + Some(ChatCommand::Play(msg_create.0.clone(), query.to_string())) + } + ["!stop"] | ["!stop", _] => Some(ChatCommand::Stop(msg_create.0)), + ["!leave"] | ["!leave", _] => Some(ChatCommand::Leave(msg_create.0)), + ["!join"] | ["!join", _] => Some(ChatCommand::Join(msg_create.0)), + _ => Some(ChatCommand::NotImplemented), + } + } + _ => None, + } +} + fn spawn( fut: impl Future>> + Send + 'static, ) { @@ -119,18 +148,12 @@ async fn main() -> Result<(), Box> { state.standby.process(&event); state.songbird.process(&event).await; - if let Event::MessageCreate(msg) = event { - if msg.guild_id.is_none() || !msg.content.starts_with('!') { - continue; - } - - match msg.content.split(' ').next() { - Some("!join") => spawn(join(msg.0, Arc::clone(&state))), - Some("!leave") => spawn(leave(msg.0, Arc::clone(&state))), - Some("!play") => spawn(play(msg.0, Arc::clone(&state))), - Some("!stop") => spawn(stop(msg.0, Arc::clone(&state))), - _ => continue, - } + match parse_command(event) { + Some(ChatCommand::Play(msg, query)) => spawn(play(msg, Arc::clone(&state), query)), + Some(ChatCommand::Stop(msg)) => spawn(stop(msg, Arc::clone(&state))), + Some(ChatCommand::Leave(msg)) => spawn(leave(msg, Arc::clone(&state))), + Some(ChatCommand::Join(msg)) => spawn(join(msg, Arc::clone(&state))), + _ => {} } } @@ -166,7 +189,11 @@ async fn leave(msg: Message, state: State) -> Result<(), Box Result<(), Box> { +async fn play( + msg: Message, + state: State, + query: String, +) -> Result<(), Box> { tracing::debug!( "play command in channel {} by {}", msg.channel_id, @@ -177,8 +204,7 @@ async fn play(msg: Message, state: State) -> Result<(), Box