discord_webhook/
client.rs

1use reqwest::{Body, Client, Method, StatusCode};
2
3use crate::models::{Message};
4
5pub type WebhookResult<Type> = std::result::Result<Type, Box<dyn std::error::Error + Send + Sync>>;
6
7/// A Client that sends webhooks for discord.
8pub struct WebhookClient {
9    client: Client,
10    url: String,
11}
12
13impl WebhookClient {
14    pub fn new(url: &str) -> Self {
15        let client = Client::new();
16        Self {
17            client,
18            url: url.to_owned(),
19        }
20    }
21
22    /// Example
23    /// ```rust
24    /// let client = WebhookClient::new("URL");
25    /// client.send(|message| message
26    ///     .content("content")
27    ///     .username("username")).await?;
28    /// ```
29    pub async fn send<Func>(&self, function: Func) -> WebhookResult<bool>
30    where
31        Func: Fn(&mut Message) -> &mut Message,
32    {
33        let mut message = Message::new();
34        function(&mut message);
35        let result = self.send_message(&message).await?;
36
37        Ok(result)
38    }
39
40    pub async fn send_message(&self, message: &Message) -> WebhookResult<bool> {
41        let body = serde_json::to_string(message)?;
42
43        let mut req = self.client.request(Method::POST, &self.url);
44
45        req = req
46            .header("content-type", "application/json")
47            .body(Body::from(body));
48
49        let req = req.build()?;
50
51        let response = self.client.execute(req).await?;
52
53        Ok(response.status() == StatusCode::OK)
54    }
55}