aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 1e3be9142d8f8a981390e2072fc65bb3b356e253 (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
#![feature(test)]
extern crate test;

use anyhow::Result;

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

pub mod config;
pub mod hooks;

pub use macros::catinator;

#[macro_export]
macro_rules! reply {
    ( $msg:expr, $text:expr ) => {
        bot.send_privmsg($msg.response_target().unwrap(), $text.as_str())?;
    };
}


pub struct Bot {
    pub config: config::Config,
    pub irc_client: irc::client::Client,
}

impl Bot {
    pub async fn new(config_path: &str) -> Result<Bot> {
        use std::fs;

        let config_str = fs::read_to_string(config_path)?;
        let config: config::Config = toml::from_str(&config_str)?;

        let irc_config: Config = config.clone().into();

        let irc_client = Client::from_config(irc_config.clone()).await?;

        Ok(Bot { irc_client, config })
    }

    pub async fn sasl_init(&self) -> Result<()> {
        self.irc_client
            .send_cap_req(&vec![irc::client::prelude::Capability::Sasl])?;
        self.irc_client
            .send(Command::NICK(self.config.user.nickname.clone()))?;
        self.irc_client.send(Command::USER(
            self.config.user.nickname.clone(),
            "0".to_owned(),
            self.config.user.realname.clone(),
        ))?;
        self.irc_client.send_sasl_plain()?;

        Ok(())
    }

    pub fn send_privmsg(
        &self,
        target: &str,
        message: &str,
    ) -> std::result::Result<(), irc::error::Error> {
        self.irc_client.send_privmsg(target, message)
    }

    pub fn send_notice(
        &self,
        target: &str,
        message: &str,
    ) -> std::result::Result<(), irc::error::Error> {
        self.irc_client.send_notice(target, message)
    }
}