slack-morphism 2.29.0

Slack Morphism is a modern client library for Slack Web/Events API/Socket Mode and Block Kit
Documentation
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//!
//! Support for Slack Files API methods
//!

use crate::api::{
    SlackApiUsersConversationsRequest, SlackApiUsersConversationsResponse,
    SlackApiUsersProfileSetRequest, SlackApiUsersProfileSetResponse,
};
use crate::blocks::*;
use crate::models::*;
use crate::multipart_form::FileMultipartData;
use crate::ratectl::*;
use crate::{ClientResult, SlackClientHttpConnector};
use crate::{SlackApiScrollableRequest, SlackApiScrollableResponse, SlackClientSession};
use futures_util::future::BoxFuture;
use futures_util::FutureExt;
use rsb_derive::Builder;
use rvstruct::ValueStruct;
use serde::{Deserialize, Serialize, Serializer};
use serde_with::skip_serializing_none;
use url::Url;

impl<'a, SCHC> SlackClientSession<'a, SCHC>
where
    SCHC: SlackClientHttpConnector + Send,
{
    ///
    /// https://api.slack.com/methods/files.info
    ///
    pub async fn files_info(
        &self,
        req: &SlackApiFilesInfoRequest,
    ) -> ClientResult<SlackApiFilesInfoResponse> {
        self.http_session_api
            .http_get(
                "files.info",
                &vec![("file", Some(req.file.value()))],
                Some(&SLACK_TIER4_METHOD_CONFIG),
            )
            .await
    }

    ///
    /// https://api.slack.com/methods/files.list
    ///
    pub async fn files_list(
        &self,
        req: &SlackApiFilesListRequest,
    ) -> ClientResult<SlackApiFilesListResponse> {
        self.http_session_api
            .http_get(
                "files.list",
                &vec![
                    ("channel", req.channel.as_ref().map(|x| x.value())),
                    ("user", req.user.as_ref().map(|x| x.value())),
                    ("types", req.types.as_ref()),
                    ("count", req.count.map(|x| x.to_string()).as_ref()),
                    ("page", req.page.map(|x| x.to_string()).as_ref()),
                    ("ts_from", req.ts_from.map(|x| x.to_string()).as_ref()),
                    ("ts_to", req.ts_to.map(|x| x.to_string()).as_ref()),
                    (
                        "show_files_hidden_by_limit",
                        req.show_files_hidden_by_limit
                            .map(|x| x.to_string())
                            .as_ref(),
                    ),
                ],
                Some(&SLACK_TIER3_METHOD_CONFIG),
            )
            .await
    }

    ///
    /// https://api.slack.com/methods/files.upload
    ///
    #[deprecated(
        note = "Deprecated by Slack. Use `getUploadURLExternal/files_upload_via_url/completeUploadExternal` instead."
    )]
    pub async fn files_upload(
        &self,
        req: &SlackApiFilesUploadRequest,
    ) -> ClientResult<SlackApiFilesUploadResponse> {
        let maybe_file = req.binary_content.as_ref().map(|file_data| {
            let filename = req.filename.clone().unwrap_or("file".to_string());
            let file_content_type = req.file_content_type.clone().unwrap_or_else(|| {
                let file_mime = mime_guess::MimeGuess::from_path(&filename).first_or_octet_stream();
                file_mime.to_string()
            });
            FileMultipartData {
                name: filename,
                content_type: file_content_type,
                data: file_data.as_slice(),
            }
        });
        self.http_session_api
            .http_post_multipart_form(
                "files.upload",
                maybe_file,
                &vec![
                    (
                        "channels",
                        req.channels
                            .as_ref()
                            .map(|xs| {
                                xs.iter()
                                    .map(|x| x.to_string())
                                    .collect::<Vec<String>>()
                                    .join(",")
                            })
                            .as_ref(),
                    ),
                    ("content", req.content.as_ref()),
                    ("filename", req.filename.as_ref()),
                    ("filetype", req.filetype.as_ref().map(|x| x.value())),
                    ("initial_comment", req.initial_comment.as_ref()),
                    ("thread_ts", req.thread_ts.as_ref().map(|x| x.value())),
                    ("title", req.title.as_ref()),
                ],
                Some(&SLACK_TIER2_METHOD_CONFIG),
            )
            .await
    }

    ///
    /// https://api.slack.com/methods/files.getUploadURLExternal
    ///
    pub async fn get_upload_url_external(
        &self,
        req: &SlackApiFilesGetUploadUrlExternalRequest,
    ) -> ClientResult<SlackApiFilesGetUploadUrlExternalResponse> {
        self.http_session_api
            .http_get(
                "files.getUploadURLExternal",
                &vec![
                    ("filename", Some(&req.filename)),
                    ("length", Some(&req.length.to_string())),
                    ("alt_txt", req.alt_txt.as_ref()),
                    ("snippet_type", req.snippet_type.as_ref().map(|v| v.value())),
                ],
                Some(&SLACK_TIER4_METHOD_CONFIG),
            )
            .await
    }

    pub async fn files_upload_via_url(
        &self,
        req: &SlackApiFilesUploadViaUrlRequest,
    ) -> ClientResult<SlackApiFilesUploadViaUrlResponse> {
        self.http_session_api
            .http_post_uri_binary(
                req.upload_url.value().clone(),
                req.content_type.clone(),
                &req.content,
                Some(&SLACK_TIER4_METHOD_CONFIG),
            )
            .await
    }

    ///
    /// https://api.slack.com/methods/files.completeUploadExternal
    ///
    pub async fn files_complete_upload_external(
        &self,
        req: &SlackApiFilesCompleteUploadExternalRequest,
    ) -> ClientResult<SlackApiFilesCompleteUploadExternalResponse> {
        self.http_session_api
            .http_post(
                "files.completeUploadExternal",
                req,
                Some(&SLACK_TIER4_METHOD_CONFIG),
            )
            .await
    }

    ///
    /// https://api.slack.com/methods/files.delete
    ///
    pub async fn files_delete(
        &self,
        req: &SlackApiFilesDeleteRequest,
    ) -> ClientResult<SlackApiFilesDeleteResponse> {
        self.http_session_api
            .http_post("files.delete", req, Some(&SLACK_TIER3_METHOD_CONFIG))
            .await
    }
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesInfoRequest {
    pub file: SlackFileId,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesInfoResponse {
    pub file: SlackFile,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesListRequest {
    pub channel: Option<SlackChannelId>,
    pub user: Option<SlackUserId>,
    pub types: Option<String>,
    pub count: Option<u32>,
    pub page: Option<u32>,
    pub ts_from: Option<i64>,
    pub ts_to: Option<i64>,
    pub show_files_hidden_by_limit: Option<bool>,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesListResponse {
    pub files: Vec<SlackFile>,
    pub paging: Option<SlackApiFilesListPaging>,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesListPaging {
    pub count: Option<u32>,
    pub total: Option<u32>,
    pub page: Option<u32>,
    pub pages: Option<u32>,
}

impl<SCHC> SlackApiScrollableRequest<SCHC> for SlackApiFilesListRequest
where
    SCHC: SlackClientHttpConnector + Send + Sync + Clone + 'static,
{
    type ResponseType = SlackApiFilesListResponse;
    type CursorType = u32;
    type ResponseItemType = SlackFile;

    fn with_new_cursor(&self, new_cursor: Option<&Self::CursorType>) -> Self {
        self.clone().opt_page(new_cursor.cloned())
    }

    fn scroll<'a, 's>(
        &'a self,
        session: &'a SlackClientSession<'s, SCHC>,
    ) -> BoxFuture<'a, ClientResult<Self::ResponseType>> {
        async move { session.files_list(self).await }.boxed()
    }
}

impl SlackApiScrollableResponse for SlackApiFilesListResponse {
    type CursorType = u32;
    type ResponseItemType = SlackFile;

    fn next_cursor(&self) -> Option<Self::CursorType> {
        self.paging
            .as_ref()
            .into_iter()
            .filter_map(|paging| match (paging.page, paging.pages) {
                (Some(page), Some(pages)) if page < pages => Some(page + 1),
                _ => None,
            })
            .next()
    }

    fn scrollable_items<'a>(&'a self) -> Box<dyn Iterator<Item = &'a Self::ResponseItemType> + 'a> {
        Box::new(self.files.iter())
    }
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesUploadRequest {
    #[serde(serialize_with = "to_csv")]
    pub channels: Option<Vec<SlackChannelId>>,
    pub content: Option<String>,
    pub binary_content: Option<Vec<u8>>,
    pub filename: Option<String>,
    pub filetype: Option<SlackFileType>,
    pub initial_comment: Option<String>,
    pub thread_ts: Option<SlackTs>,
    pub title: Option<String>,
    pub file_content_type: Option<String>,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesUploadResponse {
    pub file: SlackFile,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesGetUploadUrlExternalRequest {
    pub filename: String,
    pub length: usize,
    pub alt_txt: Option<String>,
    pub snippet_type: Option<SlackFileSnippetType>,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesGetUploadUrlExternalResponse {
    pub upload_url: SlackFileUploadUrl,
    pub file_id: SlackFileId,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesUploadViaUrlRequest {
    pub upload_url: SlackFileUploadUrl,
    pub content: Vec<u8>,
    pub content_type: String,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesUploadViaUrlResponse {}

///
/// https://api.slack.com/methods/files.completeUploadExternal
///
/// `initial_comment` and `blocks` are mutually exclusive: when `initial_comment` is set,
/// Slack ignores `blocks`.
///
#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesCompleteUploadExternalRequest {
    pub files: Vec<SlackApiFilesComplete>,
    pub channel_id: Option<SlackChannelId>,
    #[serde(serialize_with = "to_csv")]
    pub channels: Option<Vec<SlackChannelId>>,
    pub initial_comment: Option<String>,
    /// Blocks for the file share message.
    ///
    /// Note: as of September 2026 Slack answers `internal_error` when this contains a
    /// `markdown` block, in every request encoding, while the same block is accepted by
    /// `chat.postMessage`. `section` and `rich_text` blocks work. Tracked upstream in
    /// https://github.com/slackapi/python-slack-sdk/issues/1756
    pub blocks: Option<Vec<SlackBlock>>,
    pub thread_ts: Option<SlackTs>,
    pub username: Option<String>,
    pub icon_url: Option<Url>,
    pub icon_emoji: Option<SlackEmoji>,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesCompleteUploadExternalResponse {
    pub files: Vec<SlackFile>,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesComplete {
    pub id: SlackFileId,
    pub title: Option<String>,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesDeleteRequest {
    pub file: SlackFileId,
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)]
pub struct SlackApiFilesDeleteResponse {}

fn to_csv<S: Serializer>(x: &Option<Vec<SlackChannelId>>, s: S) -> Result<S::Ok, S::Error> {
    match x {
        None => s.serialize_none(),
        Some(ids) => {
            let y: Vec<String> = ids.iter().map(|v| v.0.clone()).collect();
            y.join(",").serialize(s)
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_slack_api_files_complete_upload_external_request_serialization() {
        let payload =
            include_str!("./fixtures/slack_api_files_complete_upload_external_request.json");
        let expected: serde_json::Value = serde_json::from_str(payload).unwrap();

        let request =
            SlackApiFilesCompleteUploadExternalRequest::new(vec![SlackApiFilesComplete::new(
                SlackFileId("F123456".into()),
            )])
            .opt_channel_id(Some(SlackChannelId("C123456".into())))
            .with_channels(vec![
                SlackChannelId("C1".into()),
                SlackChannelId("C2".into()),
            ])
            .with_blocks(vec![SlackMarkdownBlock::new("*bold* text".into()).into()])
            .with_thread_ts(SlackTs("1234567890.123456".into()))
            .with_username("test-bot".into())
            .with_icon_url(Url::parse("https://example.com/icon.png").unwrap())
            .with_icon_emoji(SlackEmoji::new(":tada:".into()));

        let actual = serde_json::to_value(&request).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_slack_api_files_complete_upload_external_request_minimal() {
        let request =
            SlackApiFilesCompleteUploadExternalRequest::new(vec![SlackApiFilesComplete::new(
                SlackFileId("F123456".into()),
            )]);

        let actual = serde_json::to_value(&request).unwrap();
        let expected: serde_json::Value =
            serde_json::from_str(r#"{"files":[{"id":"F123456"}]}"#).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_slack_api_files_complete_upload_external_response() {
        let payload =
            include_str!("./fixtures/slack_api_files_complete_upload_external_response.json");
        let model: SlackApiFilesCompleteUploadExternalResponse =
            serde_json::from_str(payload).unwrap();

        assert_eq!(model.files.len(), 1);
        assert_eq!(model.files[0].id, SlackFileId("F123456".into()));
        assert_eq!(model.files[0].title, Some("test-file".into()));
    }
}