slacko 0.2.2

Comprehensive Rust SDK for the Slack API with stealth mode support
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//! Chat API
//!
//! Methods for posting, updating, and deleting messages.

use crate::client::SlackClient;
use crate::error::Result;
use crate::types::Message;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Chat API client
pub struct ChatApi {
    client: SlackClient,
}

impl ChatApi {
    pub(crate) fn new(client: SlackClient) -> Self {
        Self { client }
    }

    /// Post a message to a channel
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID or name
    /// * `text` - Message text
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use slacko::{SlackClient, AuthConfig};
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = SlackClient::new(AuthConfig::oauth("token"))?;
    /// let response = client.chat()
    ///     .post_message("C12345", "Hello, world!")
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn post_message(&self, channel: &str, text: &str) -> Result<PostMessageResponse> {
        let params = PostMessageRequest::new(channel).text(text);
        self.client.post("chat.postMessage", &params).await
    }

    /// Post a message with full options
    pub async fn post_message_with_options(
        &self,
        params: PostMessageRequest,
    ) -> Result<PostMessageResponse> {
        self.client.post("chat.postMessage", &params).await
    }

    /// Post a message with Block Kit blocks
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID or name
    /// * `blocks` - Block Kit blocks (use MessageBuilder)
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use slacko::{SlackClient, AuthConfig};
    /// # use slacko::blocks::MessageBuilder;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = SlackClient::new(AuthConfig::oauth("token"))?;
    /// let message = MessageBuilder::new()
    ///     .text("Fallback text")
    ///     .header("Welcome!")
    ///     .section("*This* is a Block Kit message")
    ///     .build();
    ///
    /// client.chat().post_message_blocks("C12345", message).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn post_message_blocks(
        &self,
        channel: &str,
        message: Value,
    ) -> Result<PostMessageResponse> {
        let mut params = serde_json::from_value::<PostMessageRequest>(message)?;
        params.channel = channel.to_string();

        self.client.post("chat.postMessage", &params).await
    }

    /// Update an existing message
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID
    /// * `ts` - Message timestamp
    /// * `text` - New message text
    pub async fn update_message(
        &self,
        channel: &str,
        ts: &str,
        text: &str,
    ) -> Result<UpdateMessageResponse> {
        let params = UpdateMessageRequest {
            channel: channel.to_string(),
            ts: ts.to_string(),
            text: Some(text.to_string()),
            blocks: None,
            as_user: None,
        };

        self.client.post("chat.update", &params).await
    }

    /// Delete a message
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID
    /// * `ts` - Message timestamp
    pub async fn delete_message(&self, channel: &str, ts: &str) -> Result<DeleteMessageResponse> {
        let params = DeleteMessageRequest {
            channel: channel.to_string(),
            ts: ts.to_string(),
            as_user: None,
        };

        self.client.post("chat.delete", &params).await
    }

    /// Post an ephemeral message (only visible to one user)
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID
    /// * `user` - User ID to show the message to
    /// * `text` - Message text
    pub async fn post_ephemeral(
        &self,
        channel: &str,
        user: &str,
        text: &str,
    ) -> Result<PostEphemeralResponse> {
        let params = PostEphemeralRequest {
            channel: channel.to_string(),
            user: user.to_string(),
            text: Some(text.to_string()),
            blocks: None,
            as_user: None,
        };

        self.client.post("chat.postEphemeral", &params).await
    }

    /// Get a permalink for a message
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID
    /// * `message_ts` - Message timestamp
    pub async fn get_permalink(
        &self,
        channel: &str,
        message_ts: &str,
    ) -> Result<GetPermalinkResponse> {
        let params = [("channel", channel), ("message_ts", message_ts)];

        self.client.get("chat.getPermalink", &params).await
    }

    /// Schedule a message to be sent later
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID
    /// * `text` - Message text
    /// * `post_at` - Unix timestamp when to send
    pub async fn schedule_message(
        &self,
        channel: &str,
        text: &str,
        post_at: i64,
    ) -> Result<ScheduleMessageResponse> {
        let params = ScheduleMessageRequest {
            channel: channel.to_string(),
            text: Some(text.to_string()),
            post_at,
            blocks: None,
            as_user: None,
        };

        self.client.post("chat.scheduleMessage", &params).await
    }

    /// Delete a scheduled message
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID
    /// * `scheduled_message_id` - Scheduled message ID to delete
    pub async fn delete_scheduled_message(
        &self,
        channel: &str,
        scheduled_message_id: &str,
    ) -> Result<DeleteScheduledMessageResponse> {
        let params = DeleteScheduledMessageRequest {
            channel: channel.to_string(),
            scheduled_message_id: scheduled_message_id.to_string(),
        };

        self.client
            .post("chat.deleteScheduledMessage", &params)
            .await
    }

    /// Provide custom unfurl behavior for URLs in messages
    ///
    /// This method allows apps to provide custom rich previews for URLs
    /// shared in messages. Your app must be subscribed to the `link_shared`
    /// event to receive URLs that need unfurling.
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID where the URL was shared
    /// * `ts` - Timestamp of the message containing the URL
    /// * `unfurls` - JSON object mapping URLs to unfurl attachments
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use slacko::{SlackClient, AuthConfig};
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = SlackClient::new(AuthConfig::oauth("token"))?;
    /// use serde_json::json;
    ///
    /// let unfurls = json!({
    ///     "https://example.com/page": {
    ///         "text": "Custom unfurl for example.com",
    ///         "color": "#36a64f"
    ///     }
    /// });
    ///
    /// client.chat().unfurl("C12345", "1234567890.123456", unfurls).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn unfurl(
        &self,
        channel: &str,
        ts: &str,
        unfurls: serde_json::Value,
    ) -> Result<UnfurlResponse> {
        let params = UnfurlRequest {
            channel: channel.to_string(),
            ts: ts.to_string(),
            unfurls,
            user_auth_message: None,
            user_auth_required: None,
            user_auth_url: None,
        };

        self.client.post("chat.unfurl", &params).await
    }

    /// Provide custom unfurl behavior with full options
    pub async fn unfurl_with_options(&self, params: UnfurlRequest) -> Result<UnfurlResponse> {
        self.client.post("chat.unfurl", &params).await
    }

    /// List scheduled messages
    ///
    /// Returns a list of scheduled messages for a channel or the entire workspace.
    ///
    /// # Arguments
    ///
    /// * `channel` - Optional channel ID to filter by
    pub async fn scheduled_messages_list(
        &self,
        channel: Option<&str>,
    ) -> Result<ScheduledMessagesListResponse> {
        let params = ScheduledMessagesListRequest {
            channel: channel.map(|c| c.to_string()),
            cursor: None,
            latest: None,
            oldest: None,
            limit: None,
            team_id: None,
        };

        self.client
            .post("chat.scheduledMessages.list", &params)
            .await
    }

    /// List scheduled messages with full options
    pub async fn scheduled_messages_list_with_options(
        &self,
        params: ScheduledMessagesListRequest,
    ) -> Result<ScheduledMessagesListResponse> {
        self.client
            .post("chat.scheduledMessages.list", &params)
            .await
    }

    /// Send a /me message
    ///
    /// Sends a message with the /me prefix, which displays as an action.
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID
    /// * `text` - Message text (will be prefixed with the user's name)
    pub async fn me_message(&self, channel: &str, text: &str) -> Result<MeMessageResponse> {
        let params = MeMessageRequest {
            channel: channel.to_string(),
            text: text.to_string(),
        };

        self.client.post("chat.meMessage", &params).await
    }

    // ========== Streaming Methods for AI/LLM Apps ==========

    /// Start a text stream for AI/LLM responses
    ///
    /// Initiates a streaming message that can be appended to in real-time.
    /// This is designed for AI-enabled Slack apps to provide streaming responses.
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID
    /// * `thread_ts` - Optional thread timestamp to reply in
    pub async fn start_stream(
        &self,
        channel: &str,
        thread_ts: Option<&str>,
    ) -> Result<StartStreamResponse> {
        let params = StartStreamRequest {
            channel: channel.to_string(),
            thread_ts: thread_ts.map(|s| s.to_string()),
        };

        self.client.post("chat.startStream", &params).await
    }

    /// Append text to an existing stream
    ///
    /// Adds content to a streaming message started with `start_stream`.
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID
    /// * `stream_id` - Stream ID from start_stream response
    /// * `text` - Text to append to the stream
    pub async fn append_stream(
        &self,
        channel: &str,
        stream_id: &str,
        text: &str,
    ) -> Result<AppendStreamResponse> {
        let params = AppendStreamRequest {
            channel: channel.to_string(),
            stream_id: stream_id.to_string(),
            text: text.to_string(),
        };

        self.client.post("chat.appendStream", &params).await
    }

    /// Stop/finalize a text stream
    ///
    /// Completes a streaming message and converts it to a regular message.
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel ID
    /// * `stream_id` - Stream ID from start_stream response
    pub async fn stop_stream(&self, channel: &str, stream_id: &str) -> Result<StopStreamResponse> {
        let params = StopStreamRequest {
            channel: channel.to_string(),
            stream_id: stream_id.to_string(),
        };

        self.client.post("chat.stopStream", &params).await
    }
}

// Request/Response types

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct PostMessageRequest {
    pub channel: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thread_ts: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocks: Option<Vec<Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attachments: Option<Vec<Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub as_user: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon_emoji: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reply_broadcast: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unfurl_links: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unfurl_media: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mrkdwn: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parse: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub link_names: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

impl PostMessageRequest {
    pub fn new(channel: &str) -> Self {
        Self {
            channel: channel.to_string(),
            ..Default::default()
        }
    }

    pub fn text(mut self, text: &str) -> Self {
        self.text = Some(text.to_string());
        self
    }

    pub fn thread_ts(mut self, ts: &str) -> Self {
        self.thread_ts = Some(ts.to_string());
        self
    }

    pub fn blocks(mut self, blocks: Vec<Value>) -> Self {
        self.blocks = Some(blocks);
        self
    }

    pub fn attachments(mut self, attachments: Vec<Value>) -> Self {
        self.attachments = Some(attachments);
        self
    }

    pub fn reply_broadcast(mut self, broadcast: bool) -> Self {
        self.reply_broadcast = Some(broadcast);
        self
    }

    pub fn unfurl_links(mut self, unfurl: bool) -> Self {
        self.unfurl_links = Some(unfurl);
        self
    }

    pub fn unfurl_media(mut self, unfurl: bool) -> Self {
        self.unfurl_media = Some(unfurl);
        self
    }

    pub fn as_user(mut self, as_user: bool) -> Self {
        self.as_user = Some(as_user);
        self
    }

    pub fn username(mut self, username: &str) -> Self {
        self.username = Some(username.to_string());
        self
    }

    pub fn icon_emoji(mut self, emoji: &str) -> Self {
        self.icon_emoji = Some(emoji.to_string());
        self
    }

    pub fn icon_url(mut self, url: &str) -> Self {
        self.icon_url = Some(url.to_string());
        self
    }

    pub fn mrkdwn(mut self, enabled: bool) -> Self {
        self.mrkdwn = Some(enabled);
        self
    }

    pub fn parse(mut self, mode: &str) -> Self {
        self.parse = Some(mode.to_string());
        self
    }

    pub fn link_names(mut self, enabled: bool) -> Self {
        self.link_names = Some(enabled);
        self
    }

    pub fn metadata(mut self, metadata: Value) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

#[derive(Debug, Deserialize)]
pub struct PostMessageResponse {
    pub channel: String,
    pub ts: String,
    pub message: Message,
}

#[derive(Debug, Serialize)]
pub struct UpdateMessageRequest {
    pub channel: String,
    pub ts: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocks: Option<Vec<Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub as_user: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct UpdateMessageResponse {
    pub channel: String,
    pub ts: String,
    pub text: String,
}

#[derive(Debug, Serialize)]
pub struct DeleteMessageRequest {
    pub channel: String,
    pub ts: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub as_user: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct DeleteMessageResponse {
    pub channel: String,
    pub ts: String,
}

#[derive(Debug, Serialize)]
pub struct PostEphemeralRequest {
    pub channel: String,
    pub user: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocks: Option<Vec<Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub as_user: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct PostEphemeralResponse {
    pub message_ts: String,
}

#[derive(Debug, Deserialize)]
pub struct GetPermalinkResponse {
    pub permalink: String,
}

#[derive(Debug, Serialize)]
pub struct ScheduleMessageRequest {
    pub channel: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    pub post_at: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocks: Option<Vec<Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub as_user: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct ScheduleMessageResponse {
    pub channel: String,
    pub scheduled_message_id: String,
    pub post_at: i64,
}

#[derive(Debug, Serialize)]
pub struct DeleteScheduledMessageRequest {
    pub channel: String,
    pub scheduled_message_id: String,
}

#[derive(Debug, Deserialize)]
pub struct DeleteScheduledMessageResponse {}

/// Provide custom unfurl behavior for URLs in messages
///
/// # Arguments
///
/// * `channel` - Channel ID
/// * `ts` - Message timestamp
/// * `unfurls` - Map of URLs to unfurl definitions
#[derive(Debug, Serialize)]
pub struct UnfurlRequest {
    pub channel: String,
    pub ts: String,
    pub unfurls: serde_json::Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_auth_message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_auth_required: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_auth_url: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct UnfurlResponse {}

#[derive(Debug, Serialize, Default)]
pub struct ScheduledMessagesListRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channel: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latest: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub oldest: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub team_id: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct ScheduledMessagesListResponse {
    pub scheduled_messages: Vec<ScheduledMessage>,
    #[serde(default)]
    pub response_metadata: Option<ResponseMetadata>,
}

#[derive(Debug, Deserialize)]
pub struct ScheduledMessage {
    pub id: String,
    pub channel_id: String,
    pub post_at: i64,
    pub date_created: i64,
    #[serde(default)]
    pub text: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct ResponseMetadata {
    #[serde(default)]
    pub next_cursor: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct MeMessageRequest {
    pub channel: String,
    pub text: String,
}

#[derive(Debug, Deserialize)]
pub struct MeMessageResponse {
    pub channel: String,
    pub ts: String,
}

// ========== Streaming Types ==========

#[derive(Debug, Serialize)]
pub struct StartStreamRequest {
    pub channel: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thread_ts: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct StartStreamResponse {
    pub channel: String,
    pub stream_id: String,
    pub ts: String,
}

#[derive(Debug, Serialize)]
pub struct AppendStreamRequest {
    pub channel: String,
    pub stream_id: String,
    pub text: String,
}

#[derive(Debug, Deserialize)]
pub struct AppendStreamResponse {}

#[derive(Debug, Serialize)]
pub struct StopStreamRequest {
    pub channel: String,
    pub stream_id: String,
}

#[derive(Debug, Deserialize)]
pub struct StopStreamResponse {
    pub channel: String,
    pub ts: String,
}