use modules::EventLoop; use toml::value::Table; use std::sync::Arc; use std::sync::mpsc::Receiver; use transformable_channels::mpsc::ExtSender; use regex; use regex::Regex; use event::{Event, Envelope}; use rand; pub struct RandomModule { pattern: Regex, responses: Vec } impl RandomModule { pub fn new (_: &Table, configuration: &Table) -> Box { 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()) .map(|value| value.to_vec()) .unwrap_or(vec![]) .into_iter() .map(|value| { String::from(value.as_str().unwrap()) }) .collect(); Box::new(RandomModule { pattern: pattern, responses: responses }) } } impl EventLoop for RandomModule { fn run(&self, _: Box>, receiver: Receiver>) { let mut rng = rand::thread_rng(); loop { match receiver.recv() { Ok(envelope) => { 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) } } } } }