From c774988fc98fac9b9b10c806c36f14a86ec9306b Mon Sep 17 00:00:00 2001 From: Adrian Malacoda Date: Thu, 22 Feb 2018 20:52:47 -0600 Subject: [PATCH] overhaul random module to use regex instead of prefix match --- src/modules/random.rs | 38 +++++++++++++++++++------------------- tenquestionmarks.toml | 6 ++++++ 2 files changed, 25 insertions(+), 19 deletions(-) diff --git a/src/modules/random.rs b/src/modules/random.rs index 19a259a..0fd6ceb 100644 --- a/src/modules/random.rs +++ b/src/modules/random.rs @@ -5,20 +5,27 @@ use std::sync::Arc; use std::sync::mpsc::Receiver; use transformable_channels::mpsc::ExtSender; -use helpers::command::split_command; +use regex; +use regex::Regex; + use event::{Event, Envelope}; use rand; pub struct RandomModule { - prefix: String, + pattern: Regex, responses: Vec } impl RandomModule { pub fn new (_: &Table, configuration: &Table) -> Box { - let prefix = configuration.get("prefix") - .and_then(|value| value.as_str()) - .unwrap_or("?random"); + let pattern = configuration.get("pattern") + .and_then(|value| value.as_str()) + .map(String::from) + .or_else(|| configuration.get("prefix") + .and_then(|value| value.as_str()) + .map(|value| format!("^{}", regex::escape(value)))) + .and_then(|value| Regex::new(&value).ok()) + .expect("Invalid value for pattern"); let responses = configuration.get("responses") .and_then(|value| value.as_array()) @@ -29,7 +36,7 @@ impl RandomModule { .collect(); Box::new(RandomModule { - prefix: String::from(prefix), + pattern: pattern, responses: responses }) } @@ -42,20 +49,13 @@ impl EventLoop for RandomModule { loop { match receiver.recv() { Ok(envelope) => { - match envelope.event { - Event::Message { ref message } => { - debug!("Received message from module {:?}... {:?}", envelope.from, message.content); - match split_command(&message.content) { - Some((command, _)) => { - if command == self.prefix { - let response = &rand::sample(&mut rng, &self.responses, 1)[0][..]; - message.reply(response); - } - }, - _ => {} - } + if let Event::Message { ref message } = envelope.event { + debug!("Received message from module {:?}... {:?}", envelope.from, message.content); + if let Some(captures) = self.pattern.captures(&message.content) { + let mut response = String::new(); + captures.expand(&rand::sample(&mut rng, &self.responses, 1)[0], &mut response); + message.reply(&response); } - _ => () } } Err(error) => { error!("Error {:?}", error) } diff --git a/tenquestionmarks.toml b/tenquestionmarks.toml index 818a9d4..a840d4f 100644 --- a/tenquestionmarks.toml +++ b/tenquestionmarks.toml @@ -96,3 +96,9 @@ parents = ["stdin", "discord"] [logger] parents = ["stdin", "discord"] filters = [{ username = "Dave" }, { username = "Kevin" }] + +[icced] +type = "random" +parents = ["stdin", "discord"] +pattern = "\\bicc?ed?\\b" +responses = ["Did some carbon-based lifeform just say **I C E**?"]