messenger_rs/
slack_hook.rs

1use anyhow::Result;
2use reqwest::{Client, StatusCode};
3use serde::Serialize;
4use serde_json::json;
5
6#[derive(Debug, Clone)]
7pub struct SlackClient {
8    url: String,
9    client: Client,
10}
11
12impl SlackClient {
13    /// Create a new client.
14    pub fn new(url: String) -> Self {
15        SlackClient {
16            url,
17            client: Client::new(),
18        }
19    }
20
21    /// Send slack message through Slack's API.
22    pub async fn send_message<S: Serialize>(&self, message: S) -> Result<()> {
23        let data = json!({
24            "text": message
25        });
26        
27        let data = serde_json::to_string(&data)?;
28
29        let response = self
30            .client
31            .post(&self.url)
32            .body(data)
33            .send()
34            .await?;
35
36        if response.status() != StatusCode::OK {
37            return Err(anyhow::anyhow!("Slack API error: {}", response.text().await?));
38        }
39
40        Ok(())
41    }
42
43    /// Send slack message through Slack's API synchronously.
44    /// Ignores the future
45    pub fn send_message_sync<S: Serialize>(&self, message: S) -> Result<()> {
46
47        let data = json!({
48            "text": message
49        });
50        
51        let data = serde_json::to_string(&data)?;
52
53        self
54            .client
55            .post(&self.url)
56            .body(data)
57            .send();
58
59        Ok(())
60    }
61}