summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: a230a7e5d43d8ee36ccafe5271b3b6948383572b (plain)
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#![feature(custom_derive,plugin)]
#![plugin(serde_macros)]
extern crate hyper;
extern crate irc;
extern crate serde;
extern crate serde_json;

use std::collections::HashMap;
use std::io::Read;

use hyper::Client;
use hyper::header::Connection;

use irc::client::prelude::*;

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct WikiPage {
    ns: u32,
    pageid: u32,
    title: String,
    extract: String,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct WikiRedirect {
    from: String,
    to: String,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct WikiQueryResponse {
    batchcomplete: String,
    query: WikiQuery,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct WikiQuery {
    redirects: Option<Vec<WikiRedirect>>,
    normalized: Option<Vec<WikiRedirect>>,
    pages: HashMap<String, WikiPage>,
}

const CHANNEL: &'static str = "#opensourcecornell";

fn user_agent() -> hyper::header::UserAgent {
    hyper::header::UserAgent("lidavidm_irc_bot/0.1 (https://git.lidavidm.me; li.davidm96@gmail.com) hyper/0.7.2".to_owned())
}

fn query_page(article: &str) -> serde_json::Result<WikiQueryResponse>{
    let client = Client::new();
    let mut res = client
        .get(&format!("https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&explaintext=&titles={}&redirects=", article.replace(" ", "%20")))
        .header(user_agent())
        .header(Connection::close())
        .send().unwrap();

    let mut body = String::new();
    res.read_to_string(&mut body).unwrap();

    serde_json::from_str(&body)
}

fn emote_action(action: &str) -> Option<&str> {
    if action == "shrugs" {
        Some("¯\\_(ツ)_/¯")
    }
    else {
        None
    }
}

fn extract_username(prefix: Option<String>) -> Option<String> {
    prefix.and_then(|p| p.split("!").next().map(|s| s.to_owned()))
}

struct IrcBot<T: IrcRead, U: IrcWrite> {
    server: IrcServer<T, U>,
}

impl<T: IrcRead, U: IrcWrite> IrcBot<T, U> {
    fn new(server: IrcServer<T, U>) -> IrcBot<T, U> {
        IrcBot {
            server: server,
        }
    }

    fn wiki_query(&self, origin: &str, article: &str) {
        let response = query_page(article);

        if let Ok(q) = response {
            for page in q.query.pages.values() {
                let url = format!("https://en.wikipedia.org/?curid={}", page.pageid);
                self.server.send_privmsg(origin, &format!("{}: {}", page.title, url)).unwrap();
                self.server.send_privmsg(origin, &page.extract).unwrap();
                break;
            }
        }
        else {
            self.server.send_privmsg(origin, "Sorry, I couldn't retrieve the wiki page.").unwrap();
            println!("{:?}", response);
        }
    }

    fn emote(&self, username: &str, action: &str) {
        if let Some(reply) = emote_action(action) {
            self.server.send_privmsg(
                CHANNEL,
                &(username.to_owned() + " is " + reply)[..]).unwrap();
        }
    }

    fn handle_privmsg(&self, origin: &str, username: &str, msg: &str) {
        if msg.starts_with("!wiki") {
            let article = msg[5..].trim();
            self.wiki_query(origin, article);
        }
        else if msg.starts_with("\u{1}ACTION") {
            let action = msg[8..msg.len() - 1].trim();
            self.emote(&username, action);
        }
        else if msg.starts_with("/me") {
            let action = msg[3..].trim();
            self.emote(&username, action);
        }
    }

    fn process_messages(&self) {
        for message in self.server.iter() {
            let message = message.unwrap();
            println!("{:?}", message);
            if &message.command[..] == "PRIVMSG" {
                if let Some(msg) = message.suffix {
                    if let Some(username) = extract_username(message.prefix) {
                        let origin = &message.args[0];

                        self.handle_privmsg(origin, &username, &msg);
                    }
                }
            }
        }
    }
}

fn main() {
    let config = Config {
        nickname: Some(format!("lidavidm_prime")),
        server: Some(format!("irc.freenode.net")),
        channels: Some(vec![CHANNEL.to_string()]),
        .. Default::default()
    };

    let server = IrcServer::from_config(config).unwrap();
    server.identify().unwrap();

    let bot = IrcBot::new(server);
    bot.process_messages();
}