From 472f02d15390709c011966c6b019b1f27c21bd8a Mon Sep 17 00:00:00 2001 From: projectmoon Date: Thu, 5 Nov 2020 23:03:22 +0000 Subject: [PATCH] Execute commands even when surrounded by weird whitespace. --- src/bot.rs | 18 ++++++------------ src/commands.rs | 1 + src/commands/parser.rs | 15 +++++++++++++++ 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/src/bot.rs b/src/bot.rs index 2cd526b..6d23c63 100644 --- a/src/bot.rs +++ b/src/bot.rs @@ -6,7 +6,7 @@ use crate::error::BotError; use crate::state::DiceBotState; use async_trait::async_trait; use dirs; -use log::{debug, error, info, trace, warn}; +use log::{debug, error, info, warn}; use matrix_sdk::Error as MatrixError; use matrix_sdk::{ self, @@ -136,10 +136,11 @@ impl DiceBot { let mut results = Vec::with_capacity(msg_body.lines().count()); for command in msg_body.lines() { - let ctx = Context::new(&self.db, &room_id.as_str(), &sender_username, &command); - - if let Some(cmd_result) = execute_command(&ctx).await { - results.push(cmd_result); + if !command.is_empty() { + let ctx = Context::new(&self.db, &room_id.as_str(), &sender_username, &command); + if let Some(cmd_result) = execute_command(&ctx).await { + results.push(cmd_result); + } } } @@ -230,13 +231,6 @@ async fn should_process<'a>( (String::new(), String::new()) }; - //Command parser can handle non-commands, but faster to - //not parse them. - if !msg_body.starts_with("!") { - trace!("Ignoring non-command: {}", msg_body); - return Err(BotError::ShouldNotProcessError); - } - Ok((msg_body, sender_username)) } diff --git a/src/commands.rs b/src/commands.rs index 471b379..991991e 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -55,6 +55,7 @@ pub fn parse(s: &str) -> Result, BotError> { } } +#[derive(Debug)] pub struct CommandResult { pub plain: String, pub html: String, diff --git a/src/commands/parser.rs b/src/commands/parser.rs index 57e90a4..92b538e 100644 --- a/src/commands/parser.rs +++ b/src/commands/parser.rs @@ -163,6 +163,21 @@ mod tests { assert!(result.is_err()); } + #[test] + fn newline_test() { + assert!(parse_command("\n!roll 1d4").is_ok()); + } + + #[test] + fn whitespace_and_newline_test() { + assert!(parse_command(" \n!roll 1d4").is_ok()); + } + + #[test] + fn newline_and_whitespace_test() { + assert!(parse_command("\n !cthroll 50").is_ok()); + } + #[test] fn word_with_exclamation_mark_test() { let result1 = parse_command("hello !notacommand");