use modules::Module; use toml::Table; use std::sync::mpsc::Receiver; use event::Event; use rand; pub struct RandomModule { prefix: String, responses: Vec } impl RandomModule { pub fn new (configuration: &Table) -> Box { let prefix = configuration.get("prefix") .and_then(|value| value.as_str()) .unwrap_or("!random "); let responses = configuration.get("responses") .and_then(|value| value.as_slice()) .map(|value| value.to_vec()) .unwrap_or(vec![]) .into_iter() .map(|value| { String::from(value.as_str().unwrap()) }) .collect(); Box::new(RandomModule { prefix: String::from(prefix), responses: responses }) } } impl Module for RandomModule { fn consume_events (&self, receiver: Receiver) { let mut rng = rand::thread_rng(); loop { match receiver.recv() { Ok(event) => { match event { Event::Message { content: message, channel, sender } => { if message.starts_with(self.prefix.as_str()) { let response = &rand::sample(&mut rng, &self.responses, 1)[0][..]; match channel { Some(channel) => channel.send(response), None => sender.send(response) } } } _ => () } } Err(error) => { } } } } }