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
//! The Slack API definition of `chat.postMessage`.
//!
//! <https://api.slack.com/methods/chat.postMessage>

use sfr_types as st;

pub use st::ChatPostMessageResponse;

use crate::{Client, Request};

/// The request object for <https://api.slack.com/methods/chat.postMessage>.
#[derive(Debug)]
pub struct ChatPostMessage(st::ChatPostMessageRequest);

/// The code indicating the request handled in this file.
const API_CODE: &str = "chat.postMessage";

impl ChatPostMessage {
    /// Requests `chat.postMessage` to Slack.
    async fn request_inner(&self, client: &Client) -> Result<ChatPostMessageResponse, st::Error> {
        #[allow(clippy::missing_docs_in_private_items)] // https://github.com/rust-lang/rust-clippy/issues/13298
        const URL: &str = "https://slack.com/api/chat.postMessage";

        let response = client
            .client()
            .post(URL)
            .bearer_auth(client.token())
            .json(&self.0)
            .send()
            .await
            .map_err(|e| st::Error::failed_to_request_by_http(API_CODE, e))?;
        tracing::debug!("response = {response:?}");

        let body: serde_json::Value = response
            .json()
            .await
            .map_err(|e| st::Error::failed_to_read_json(API_CODE, e))?;
        tracing::debug!("body = {body:?}");

        body.try_into()
    }
}

impl From<st::ChatPostMessageRequest> for ChatPostMessage {
    fn from(inner: st::ChatPostMessageRequest) -> Self {
        Self(inner)
    }
}

impl Request for ChatPostMessage {
    type Response = ChatPostMessageResponse;

    async fn request(self, client: &Client) -> Result<Self::Response, st::Error> {
        self.request_inner(client).await
    }
}