summaryrefslogtreecommitdiffstats
path: root/src/lib.rs
blob: 324e2738d7db7d258efcabf14ff4f9f9d07ca76d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]

//! Frippy is an IRC bot that runs plugins on each message
//! received.
//!
//! ## Example
//! ```no_run
//! extern crate frippy;
//!
//! frippy::run();
//! ```
//!
//! # Logging
//! Frippy uses the [log](https://docs.rs/log) crate so you can log events
//! which might be of interest.

#[macro_use]
extern crate log;
#[macro_use]
extern crate plugin_derive;

extern crate irc;
extern crate tokio_core;
extern crate futures;
extern crate glob;

mod plugin;
mod plugins;

use std::sync::Arc;

use irc::client::prelude::*;
use irc::error::Error as IrcError;

use tokio_core::reactor::Core;
use futures::future;
use glob::glob;

use plugin::*;

/// Runs the bot
///
/// # Remarks
///
/// This blocks the current thread while the bot is running
pub fn run() {

    // Load all toml files in the configs directory
    let mut configs = Vec::new();
    for toml in glob("configs/*.toml").unwrap() {
        match toml {
            Ok(path) => {
                info!("Loading {}", path.to_str().unwrap());
                match Config::load(path) {
                    Ok(v) => configs.push(v),
                    Err(e) => error!("Incorrect config file {}", e),
                }
            }
            Err(e) => error!("Failed to read path {}", e),
        }
    }

    // Without configs the bot would just idle
    if configs.is_empty() {
        error!("No config file found");
        return;
    }

    // The list of plugins in use
    let mut plugins = ThreadedPlugins::new();
    plugins.add(plugins::Help::new());
    plugins.add(plugins::Emoji::new());
    plugins.add(plugins::Currency::new());
    info!("Plugins loaded: {}", plugins);

    // Create an event loop to run the connections on.
    let mut reactor = Core::new().unwrap();

    // Open a connection and add work for each config
    for config in configs {
        let server =
            match IrcServer::new_future(reactor.handle(), &config).and_then(|f| reactor.run(f)) {
                Ok(v) => v,
                Err(e) => {
                    error!("Failed to connect: {}", e);
                    return;
                }
            };

        info!("Connected to server");

        match server.identify() {
            Ok(_) => info!("Identified"),
            Err(e) => error!("Failed to identify: {}", e),
        };

        // TODO Verify if we actually need to clone plugins twice
        let plugins = plugins.clone();

        let task = server
            .stream()
            .for_each(move |message| process_msg(&server, plugins.clone(), message))
            .map_err(|e| error!("Failed to process message: {}", e));

        reactor.handle().spawn(task);
    }

    // Run the main loop forever
    reactor.run(future::empty::<(), ()>()).unwrap();
}

fn process_msg(server: &IrcServer,
               mut plugins: ThreadedPlugins,
               message: Message)
               -> Result<(), IrcError> {

    if let Command::JOIN(ref channel, _, _) = message.command {
        if message.source_nickname().unwrap() == server.current_nickname() {
            info!("Joined {}", channel);
        }
    }

    // Check for possible command and save the result for later
    let command = PluginCommand::from(&server.current_nickname().to_lowercase(), &message);

    let message = Arc::new(message);
    plugins.execute_plugins(server, message);

    // If the message contained a command, handle it
    if let Some(command) = command {
        if let Err(e) = plugins.handle_command(server, command) {
            error!("Failed to handle command: {}", e);
        }
    }

    Ok(())
}


#[cfg(test)]
mod tests {}