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
use anyhow::{anyhow, Error, Result};
use serde::{Deserialize, Serialize};
mod tests;
#[derive(Debug, Serialize, Deserialize)]
pub struct Webhook {
    //r#type: i8,
    id: String,
    name: String,
    token: String,
    avatar: Option<String>,
    channel_id: String,
    guild_id: String,
}
pub struct Client {
    reqwest: reqwest::blocking::Client,
    endpoint: String,
    id: String,
    token: String,
}

impl Webhook {
    // Can't get w/o token since we're not authenticating against Discord Bot API
    pub fn get_webhook(hook: Client) -> Result<Webhook, Error> {
        let client = hook.reqwest;
        let id = hook.id;
        let token = hook.token;
        // Sets url for reqwest to get
        let endpoint: &str =
            &("https://discord.com/api/webhooks/".to_owned() + &id.to_string() + "/" + &token);
        let resp = client.get(endpoint).send()?;
        let respmod = resp.text().unwrap().to_string();
        let webhook: Webhook = serde_json::from_str(&respmod)?;

        Ok(webhook)
    }
    //
    pub fn delete_webhook(hook: Client) -> Result<reqwest::blocking::Response, Error> {
        let client = hook.reqwest;
        let endpoint: &str =
            &("https://discord.com/api/webhooks/".to_owned() + &hook.id + "/" + &hook.token);
        let resp = client.delete(endpoint).send()?;
        if resp.status() != 204 {
            return Err(anyhow!("{}", resp.status()));
        }
        Ok(resp)
    }
    pub fn execute_webhook(
        hookclient: Client,
        body: &'static str,
    ) -> Result<reqwest::blocking::Response, Error> {
        let client = hookclient.reqwest;

        let res = client
            .post(hookclient.endpoint)
            .body(body)
            .header("Content-Type", "application/json")
            .send()?;

        Ok(res)
    }
    pub fn edit_message(
        hookclient: Client,
        body: &'static str,
        message_id: &str,
    ) -> Result<reqwest::blocking::Response, Error> {
        let client = hookclient.reqwest;
        let endpoint: &str = &(hookclient.endpoint + "/messages/" + message_id);
        let res = client
            .patch(endpoint)
            .body(body)
            .header("Content-Type", "application/json")
            .send();
        Ok(res.unwrap())
    }
    pub fn new(id: &str, token: &str) -> Result<Client, Error> {
        Ok(Client {
            id: id.to_string(),
            token: token.to_string(),
            reqwest: reqwest::blocking::Client::new(),
            endpoint: "https://discord.com/api/webhooks/".to_owned()
                + &id.to_string()
                + "/"
                + &token,
        })
    }
}