aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 0aba61c7d3d9a1a522d27009bdba6b4ade398990 (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
#![cfg_attr(all(test, feature = "bench"), feature(test))]
#[cfg(all(test, feature = "bench"))]
extern crate test;

use anyhow::Result;

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

use tracing::info;

pub mod config;
pub mod hooks;
pub mod util;

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 mut config: config::Config = toml::from_str(&config_str)?;

        match std::env::var("CATINATOR_PASSWORD") {
            Ok(var) => {
                info!("using password from env var");
                config.user.password = var
            }
            Err(_) => (),
        }

        let irc_client = Client::from_config(config.clone().into()).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)
    }

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