2017-02-16 13:00:17 -06:00
|
|
|
use modules::Module;
|
|
|
|
use toml::Table;
|
|
|
|
|
2017-02-19 02:55:30 -06:00
|
|
|
use std::sync::Arc;
|
2017-02-25 20:17:46 -06:00
|
|
|
use std::sync::mpsc::{Sender, Receiver};
|
2017-02-16 13:00:17 -06:00
|
|
|
|
2017-02-19 05:37:56 -06:00
|
|
|
use helpers::command::split_command;
|
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 {
|
|
|
|
prefix: String,
|
|
|
|
responses: Vec<String>
|
|
|
|
}
|
|
|
|
|
|
|
|
impl RandomModule {
|
|
|
|
pub fn new (configuration: &Table) -> Box<Module> {
|
|
|
|
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 {
|
2017-02-25 20:17:46 -06:00
|
|
|
fn run(&self, _: Sender<Envelope>, 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) => {
|
|
|
|
match *envelope.event {
|
2017-02-19 05:37:56 -06:00
|
|
|
Event::Message { ref message } => {
|
|
|
|
debug!("Received message... {:?}", 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);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
_ => {}
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|