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
use std::collections::HashMap;

use reqwest::blocking::{multipart, Client as ReqwestClient};

pub struct Configurations {
    token: String,
    custom_url: Option<String>,
}
impl Configurations {
    pub fn new(token: String, custom_url: Option<String>) -> Configurations {
        Configurations { token, custom_url }
    }
}

pub struct TextMessage<'a> {
    pub content: &'a str,
    pub to: &'a str,
}
pub struct ImageMessage<'a> {
    pub image_path: &'a str,
    pub to: &'a str,
}

pub struct Client {
    // Each bot is given a unique authentication token when it is created. The token looks something like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11. You can learn about obtaining tokens and generating new ones in this document.
    base_url: String,
    reqwest: ReqwestClient,
}
impl Client {
    pub fn new(configurations: Configurations) -> Client {
        let reqwest = ReqwestClient::new();
        let base_url = match configurations.custom_url {
            Some(base_url) => format!("{}/bot{}", base_url, configurations.token),
            None => format!("https://api.telegram.org/bot{}", configurations.token),
        };
        Client { base_url, reqwest }
    }

    pub fn send_text(&self, message: TextMessage) {
        let mut body = HashMap::new();
        body.insert("chat_id", &message.to);
        body.insert("text", &message.content);
        self.reqwest
            .post(format!("{}/sendMessage", self.base_url))
            .json(&body)
            .send()
            .expect("Failed to send the request to telegram.");
    }

    pub fn send_image(&self, message: ImageMessage) {
        let body = multipart::Form::new()
            .text("chat_id", String::from(message.to))
            .file("photo", message.image_path)
            .unwrap_or_else(|_| panic!("Failed to load the file \"{}\"", &message.image_path));
        self.reqwest
            .post(format!("{}/sendPhoto", self.base_url))
            .multipart(body)
            .send()
            .expect("Failed to send the request to telegram.");
    }
}