2018-02-22 02:50:49 -06:00
|
|
|
use modules::EventLoop;
|
2018-02-18 16:29:30 -06:00
|
|
|
use toml::value::Table;
|
2017-02-16 13:00:17 -06:00
|
|
|
|
2017-02-19 02:55:30 -06:00
|
|
|
use std::sync::Arc;
|
2017-02-25 21:11:25 -06:00
|
|
|
use std::sync::mpsc::Receiver;
|
|
|
|
use transformable_channels::mpsc::ExtSender;
|
2017-02-16 13:00:17 -06:00
|
|
|
|
2018-02-22 20:52:47 -06:00
|
|
|
use regex;
|
|
|
|
use regex::Regex;
|
|
|
|
|
2017-02-25 20:17:46 -06:00
|
|
|
use event::{Event, Envelope};
|
2017-02-16 13:00:17 -06:00
|
|
|
use rand;
|
|
|
|
|
|
|
|
pub struct RandomModule {
|
2018-02-22 20:52:47 -06:00
|
|
|
pattern: Regex,
|
2017-02-16 13:00:17 -06:00
|
|
|
responses: Vec<String>
|
|
|
|
}
|
|
|
|
|
|
|
|
impl RandomModule {
|
2018-02-22 02:50:49 -06:00
|
|
|
pub fn new (_: &Table, configuration: &Table) -> Box<EventLoop> {
|
2018-02-22 20:52:47 -06:00
|
|
|
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");
|
2017-02-16 13:00:17 -06:00
|
|
|
|
|
|
|
let responses = configuration.get("responses")
|
2018-02-18 16:29:30 -06:00
|
|
|
.and_then(|value| value.as_array())
|
2017-02-16 13:00:17 -06:00
|
|
|
.map(|value| value.to_vec())
|
|
|
|
.unwrap_or(vec![])
|
|
|
|
.into_iter()
|
|
|
|
.map(|value| { String::from(value.as_str().unwrap()) })
|
|
|
|
.collect();
|
|
|
|
|
2018-02-22 02:50:49 -06:00
|
|
|
Box::new(RandomModule {
|
2018-02-22 20:52:47 -06:00
|
|
|
pattern: pattern,
|
2018-02-22 02:50:49 -06:00
|
|
|
responses: responses
|
|
|
|
})
|
2017-02-16 13:00:17 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-09 22:44:33 -05:00
|
|
|
impl EventLoop for RandomModule {
|
2018-02-22 02:40:22 -06:00
|
|
|
fn run(&self, _: Box<ExtSender<Event>>, receiver: Receiver<Arc<Envelope>>) {
|
2017-02-16 13:00:17 -06:00
|
|
|
let mut rng = rand::thread_rng();
|
|
|
|
|
|
|
|
loop {
|
|
|
|
match receiver.recv() {
|
2017-02-25 20:17:46 -06:00
|
|
|
Ok(envelope) => {
|
2018-02-22 20:52:47 -06:00
|
|
|
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);
|
2017-02-16 13:00:17 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-02-17 02:38:15 -06:00
|
|
|
Err(error) => { error!("Error {:?}", error) }
|
2017-02-16 13:00:17 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|