actually add random module
This commit is contained in:
parent
26e56ebee9
commit
166805d1c2
60
src/modules/random.rs
Normal file
60
src/modules/random.rs
Normal file
@ -0,0 +1,60 @@
|
||||
use modules::Module;
|
||||
use toml::Table;
|
||||
|
||||
use std::sync::mpsc::Receiver;
|
||||
use event::Event;
|
||||
|
||||
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 {
|
||||
fn consume_events (&self, receiver: Receiver<Event>) {
|
||||
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) => { }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user