overhaul random module to use regex instead of prefix match

This commit is contained in:
Adrian Malacoda 2018-02-22 20:52:47 -06:00
parent 240fb7f70e
commit c774988fc9
2 changed files with 25 additions and 19 deletions

View File

@ -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<String>
}
impl RandomModule {
pub fn new (_: &Table, configuration: &Table) -> Box<EventLoop> {
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) }

View File

@ -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**?"]