dingtalk-sdk 1.0.3

Dingtalk SDK for Rust.
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
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use hmac::{Hmac, Mac};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::time::{SystemTime, UNIX_EPOCH};
use thiserror::Error;

/// Custom error type for DingTalk operations.
#[derive(Error, Debug)]
pub enum DingTalkError {
    #[error("HTTP error: {0}")]
    HttpError(#[from] reqwest::Error),

    #[error("Timestamp generation failed")]
    TimestampError(#[from] std::time::SystemTimeError),

    #[error("Serialization error: {0}")]
    SerializationError(#[from] serde_json::Error),

    #[error("HMAC error")]
    HmacError,

    #[error("API error: {0}")]
    ApiError(String),
}

/// ----------------------- Webhook Bot Section -----------------------

#[allow(dead_code)]
#[derive(Serialize)]
#[serde(tag = "msgtype")]
enum Message {
    #[serde(rename = "text")]
    Text {
        text: TextContent,
        #[serde(skip_serializing_if = "Option::is_none")]
        at: Option<At>,
    },
    #[serde(rename = "link")]
    Link {
        link: LinkContent,
        #[serde(skip_serializing_if = "Option::is_none")]
        at: Option<At>,
    },
    #[serde(rename = "markdown")]
    Markdown {
        markdown: MarkdownContent,
        #[serde(skip_serializing_if = "Option::is_none")]
        at: Option<At>,
    },
    #[serde(rename = "actionCard")]
    ActionCard {
        #[serde(rename = "actionCard")]
        action_card: ActionCardContent,
    },
    #[serde(rename = "feedCard")]
    FeedCard {
        #[serde(rename = "feedCard")]
        feed_card: FeedCardContent,
    },
}

#[derive(Serialize)]
struct TextContent {
    content: String,
}

#[derive(Serialize)]
struct LinkContent {
    title: String,
    text: String,
    #[serde(rename = "messageUrl")]
    message_url: String,
    #[serde(rename = "picUrl", skip_serializing_if = "Option::is_none")]
    pic_url: Option<String>,
}

#[derive(Serialize)]
struct MarkdownContent {
    title: String,
    text: String,
}

#[derive(Serialize)]
struct ActionCardContent {
    title: String,
    text: String,
    #[serde(rename = "btnOrientation", skip_serializing_if = "Option::is_none")]
    btn_orientation: Option<String>,
    #[serde(rename = "singleTitle", skip_serializing_if = "Option::is_none")]
    single_title: Option<String>,
    #[serde(rename = "singleURL", skip_serializing_if = "Option::is_none")]
    single_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    btns: Option<Vec<ActionCardButton>>,
}

#[derive(Serialize)]
pub struct ActionCardButton {
    title: String,
    #[serde(rename = "actionURL")]
    action_url: String,
}

#[derive(Serialize)]
struct FeedCardContent {
    links: Vec<FeedCardLink>,
}

#[derive(Serialize)]
pub struct FeedCardLink {
    title: String,
    #[serde(rename = "messageURL")]
    message_url: String,
    #[serde(rename = "picURL")]
    pic_url: String,
}

#[derive(Serialize)]
struct At {
    #[serde(rename = "atMobiles", skip_serializing_if = "Option::is_none")]
    at_mobiles: Option<Vec<String>>,
    #[serde(rename = "atUserIds", skip_serializing_if = "Option::is_none")]
    at_user_ids: Option<Vec<String>>,
    #[serde(rename = "isAtAll", skip_serializing_if = "Option::is_none")]
    is_at_all: Option<bool>,
}

/// Implementation of the DingTalk Webhook Bot.
pub struct DingTalkRobot {
    token: String,
    secret: Option<String>,
    client: Client,
}

impl DingTalkRobot {
    /// Creates a new instance of `DingTalkRobot`.
    ///
    /// # Arguments
    ///
    /// * `token` - The access token for the DingTalk bot.
    /// * `secret` - An optional secret for signature generation.
    pub fn new(token: String, secret: Option<String>) -> Self {
        DingTalkRobot {
            token,
            secret,
            client: Client::builder()
                .no_proxy()
                .build()
                .expect("build Client error"),
        }
    }

    /// Creates a URL-encoded signature based on the given timestamp.
    ///
    /// The signature is generated by signing the string composed of the timestamp and secret.
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The current timestamp as a string.
    ///
    /// # Returns
    ///
    /// A `Result` containing the URL-encoded signature or a `DingTalkError` if an error occurs.
    fn create_signature(&self, timestamp: &str) -> Result<String, DingTalkError> {
        if let Some(ref secret) = self.secret {
            let string_to_sign = format!("{}\n{}", timestamp, secret);
            let key = secret.as_bytes();
            let mut mac =
                Hmac::<Sha256>::new_from_slice(key).map_err(|_| DingTalkError::HmacError)?;
            mac.update(string_to_sign.as_bytes());
            let result = mac.finalize().into_bytes();
            // Use the recommended STANDARD engine for base64 encoding
            let base64_result = STANDARD.encode(&result);
            let url_encoded_result = urlencoding::encode(&base64_result).to_string();
            Ok(url_encoded_result)
        } else {
            Ok(String::new())
        }
    }

    /// Sends a message to the DingTalk Webhook.
    ///
    /// This method constructs the request URL with the necessary signature (if a secret is provided)
    /// and sends the HTTP POST request with the given message payload. Non-2xx responses are treated as errors.
    ///
    /// # Arguments
    ///
    /// * `message` - A reference to the message to be sent.
    ///
    /// # Returns
    ///
    /// A `Result` containing the response text or a `DingTalkError`.
    async fn send_message(&self, message: &Message) -> Result<String, DingTalkError> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)?
            .as_millis()
            .to_string();
        let sign = self.create_signature(&timestamp)?;

        let url = if self.secret.is_some() {
            format!(
                "https://oapi.dingtalk.com/robot/send?access_token={}&timestamp={}&sign={}",
                self.token, timestamp, sign
            )
        } else {
            format!(
                "https://oapi.dingtalk.com/robot/send?access_token={}",
                self.token
            )
        };

        println!("URL: {}", url);

        let response = self
            .client
            .post(url)
            .json(message)
            .send()
            .await?
            .error_for_status()?; // Convert non-2xx HTTP responses into errors

        let response_text = response.text().await?;
        Ok(response_text)
    }

    /// Sends a text message.
    ///
    /// # Arguments
    ///
    /// * `content` - The content of the text message.
    /// * `at_mobiles` - Optional list of mobile numbers to mention.
    /// * `at_user_ids` - Optional list of user IDs to mention.
    /// * `is_at_all` - Optional flag indicating whether to mention all users.
    ///
    /// # Returns
    ///
    /// A `Result` containing the response text or a `DingTalkError`.
    pub async fn send_text_message(
        &self,
        content: &str,
        at_mobiles: Option<Vec<String>>,
        at_user_ids: Option<Vec<String>>,
        is_at_all: Option<bool>,
    ) -> Result<String, DingTalkError> {
        let at = if at_mobiles.is_some() || at_user_ids.is_some() || is_at_all.is_some() {
            Some(At {
                at_mobiles,
                at_user_ids,
                is_at_all,
            })
        } else {
            None
        };

        let message = Message::Text {
            text: TextContent {
                content: content.to_string(),
            },
            at,
        };
        self.send_message(&message).await
    }

    /// Sends a link message.
    ///
    /// # Arguments
    ///
    /// * `title` - The title of the link message.
    /// * `text` - The descriptive text of the message.
    /// * `message_url` - The URL that the message should link to.
    /// * `pic_url` - Optional URL for the picture.
    ///
    /// # Returns
    ///
    /// A `Result` containing the response text or a `DingTalkError`.
    pub async fn send_link_message(
        &self,
        title: &str,
        text: &str,
        message_url: &str,
        pic_url: Option<&str>,
    ) -> Result<String, DingTalkError> {
        let message = Message::Link {
            link: LinkContent {
                title: title.to_string(),
                text: text.to_string(),
                message_url: message_url.to_string(),
                pic_url: pic_url.map(|s| s.to_string()),
            },
            at: None,
        };
        self.send_message(&message).await
    }

    /// Sends a Markdown message.
    ///
    /// # Arguments
    ///
    /// * `title` - The title of the Markdown message.
    /// * `text` - The Markdown formatted content.
    /// * `at_mobiles` - Optional list of mobile numbers to mention.
    /// * `at_user_ids` - Optional list of user IDs to mention.
    /// * `is_at_all` - Optional flag indicating whether to mention all users.
    ///
    /// # Returns
    ///
    /// A `Result` containing the response text or a `DingTalkError`.
    pub async fn send_markdown_message(
        &self,
        title: &str,
        text: &str,
        at_mobiles: Option<Vec<String>>,
        at_user_ids: Option<Vec<String>>,
        is_at_all: Option<bool>,
    ) -> Result<String, DingTalkError> {
        let at = if at_mobiles.is_some() || at_user_ids.is_some() || is_at_all.is_some() {
            Some(At {
                at_mobiles,
                at_user_ids,
                is_at_all,
            })
        } else {
            None
        };

        let message = Message::Markdown {
            markdown: MarkdownContent {
                title: title.to_string(),
                text: text.to_string(),
            },
            at,
        };
        self.send_message(&message).await
    }

    /// Sends an ActionCard message with a single redirection button.
    ///
    /// This version uses a single button that redirects to the provided URL.
    ///
    /// # Arguments
    ///
    /// * `title` - The title of the ActionCard message.
    /// * `text` - The content of the message.
    /// * `single_title` - The title of the single button.
    /// * `single_url` - The URL to redirect when the button is clicked.
    /// * `btn_orientation` - Optional button orientation.
    ///
    /// # Returns
    ///
    /// A `Result` containing the response text or a `DingTalkError`.
    pub async fn send_action_card_message_single(
        &self,
        title: &str,
        text: &str,
        single_title: &str,
        single_url: &str,
        btn_orientation: Option<&str>,
    ) -> Result<String, DingTalkError> {
        let message = Message::ActionCard {
            action_card: ActionCardContent {
                title: title.to_string(),
                text: text.to_string(),
                btn_orientation: btn_orientation.map(|s| s.to_string()),
                single_title: Some(single_title.to_string()),
                single_url: Some(single_url.to_string()),
                btns: None,
            },
        };
        self.send_message(&message).await
    }

    /// Sends an ActionCard message with multiple buttons, each having its own URL.
    ///
    /// # Arguments
    ///
    /// * `title` - The title of the ActionCard message.
    /// * `text` - The content of the message.
    /// * `btns` - A vector of `ActionCardButton` representing the buttons.
    /// * `btn_orientation` - Optional button orientation.
    ///
    /// # Returns
    ///
    /// A `Result` containing the response text or a `DingTalkError`.
    pub async fn send_action_card_message_multi(
        &self,
        title: &str,
        text: &str,
        btns: Vec<ActionCardButton>,
        btn_orientation: Option<&str>,
    ) -> Result<String, DingTalkError> {
        let message = Message::ActionCard {
            action_card: ActionCardContent {
                title: title.to_string(),
                text: text.to_string(),
                btn_orientation: btn_orientation.map(|s| s.to_string()),
                single_title: None,
                single_url: None,
                btns: Some(btns),
            },
        };
        self.send_message(&message).await
    }

    /// Sends a FeedCard message.
    ///
    /// # Arguments
    ///
    /// * `links` - A vector of `FeedCardLink` representing the individual links.
    ///
    /// # Returns
    ///
    /// A `Result` containing the response text or a `DingTalkError`.
    pub async fn send_feed_card_message(
        &self,
        links: Vec<FeedCardLink>,
    ) -> Result<String, DingTalkError> {
        let message = Message::FeedCard {
            feed_card: FeedCardContent { links },
        };
        self.send_message(&message).await
    }
}

/// ----------------------- Enterprise Bot Section -----------------------

/// Struct representing message parameters used to generate the `msgParam` field.
#[derive(Serialize)]
struct MsgParam {
    title: String,
    text: String,
}

/// Custom serializer that converts a struct into a JSON string.
///
/// This is used to ensure the field is serialized as a JSON string rather than a nested object.
fn serialize_to_json_string<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
    T: ?Sized + Serialize,
{
    let s = serde_json::to_string(value).map_err(serde::ser::Error::custom)?;
    serializer.serialize_str(&s)
}

/// Enterprise group message request struct.
///
/// Field names are in snake_case and renamed to match the API requirements.
#[derive(Serialize)]
struct GroupMessageRequest<'a> {
    #[serde(rename = "msgParam", serialize_with = "serialize_to_json_string")]
    msg_param: MsgParam,
    #[serde(rename = "msgKey")]
    msg_key: &'a str,
    #[serde(rename = "robotCode")]
    robot_code: &'a str,
    #[serde(rename = "openConversationId")]
    open_conversation_id: &'a str,
}

/// Enterprise private message request struct.
#[derive(Serialize)]
struct OtoMessageRequest<'a> {
    #[serde(rename = "msgParam", serialize_with = "serialize_to_json_string")]
    msg_param: MsgParam,
    #[serde(rename = "msgKey")]
    msg_key: &'a str,
    #[serde(rename = "robotCode")]
    robot_code: &'a str,
    #[serde(rename = "userIds", skip_serializing_if = "Vec::is_empty")]
    user_ids: Vec<&'a str>,
}

/// Implementation of the Enterprise Bot interface.
pub struct EnterpriseDingTalkRobot {
    appkey: String,
    appsecret: String,
    robot_code: String,
    client: Client,
}

impl EnterpriseDingTalkRobot {
    /// Creates a new instance of `EnterpriseDingTalkRobot`.
    ///
    /// # Arguments
    ///
    /// * `appkey` - The application key.
    /// * `appsecret` - The application secret.
    /// * `robot_code` - The robot code.
    pub fn new(appkey: String, appsecret: String, robot_code: String) -> Self {
        EnterpriseDingTalkRobot {
            appkey,
            appsecret,
            robot_code,
            client: Client::builder()
                .no_proxy()
                .build()
                .expect("build Client error"),
        }
    }

    /// Retrieves the access token.
    ///
    /// # Returns
    ///
    /// A `Result` containing the access token string or a `DingTalkError`.
    pub async fn get_access_token(&self) -> Result<String, DingTalkError> {
        let url = format!(
            "https://oapi.dingtalk.com/gettoken?appkey={}&appsecret={}",
            self.appkey, self.appsecret
        );
        let res = self
            .client
            .get(&url)
            .send()
            .await?
            .json::<GetTokenResponse>()
            .await?;
        if res.errcode != 0 {
            return Err(DingTalkError::ApiError(res.errmsg));
        }
        res.access_token
            .ok_or_else(|| DingTalkError::ApiError("No access token returned".to_string()))
    }

    /// Sends an enterprise group chat message.
    ///
    /// # Arguments
    ///
    /// * `open_conversation_id` - The conversation ID of the group chat.
    /// * `title` - The title of the message.
    /// * `text` - The content of the message.
    ///
    /// # Returns
    ///
    /// A `Result` containing the response text or a `DingTalkError`.
    pub async fn send_group_message(
        &self,
        open_conversation_id: &str,
        title: &str,
        text: &str,
    ) -> Result<String, DingTalkError> {
        let access_token = self.get_access_token().await?;
        let url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send";
        let req_body = GroupMessageRequest {
            msg_param: MsgParam {
                title: title.to_string(),
                text: text.to_string(),
            },
            msg_key: "sampleMarkdown",
            robot_code: &self.robot_code,
            open_conversation_id,
        };
        let response = self
            .client
            .post(url)
            .header("x-acs-dingtalk-access-token", access_token)
            .json(&req_body)
            .send()
            .await?
            .error_for_status()?
            .text()
            .await?;
        Ok(response)
    }

    /// Sends an enterprise private chat message.
    ///
    /// # Arguments
    ///
    /// * `user_id` - The user ID of the recipient.
    /// * `title` - The title of the message.
    /// * `text` - The content of the message.
    ///
    /// # Returns
    ///
    /// A `Result` containing the response text or a `DingTalkError`.
    pub async fn send_oto_message(
        &self,
        user_id: &str,
        title: &str,
        text: &str,
    ) -> Result<String, DingTalkError> {
        let access_token = self.get_access_token().await?;
        let url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend";
        let req_body = OtoMessageRequest {
            msg_param: MsgParam {
                title: title.to_string(),
                text: text.to_string(),
            },
            msg_key: "sampleMarkdown",
            robot_code: &self.robot_code,
            user_ids: vec![user_id],
        };
        let response = self
            .client
            .post(url)
            .header("x-acs-dingtalk-access-token", access_token)
            .json(&req_body)
            .send()
            .await?
            .error_for_status()?
            .text()
            .await?;
        Ok(response)
    }

    /// Replies to a message based on the provided data.
    ///
    /// Automatically determines whether to send a group chat or private chat message.
    ///
    /// # Arguments
    ///
    /// * `data` - The JSON value containing the original message data.
    /// * `title` - The title of the reply message.
    /// * `text` - The content of the reply message.
    ///
    /// # Returns
    ///
    /// A `Result` containing the response text or a `DingTalkError`.
    pub async fn reply_message(
        &self,
        data: &serde_json::Value,
        title: &str,
        text: &str,
    ) -> Result<String, DingTalkError> {
        let access_token = self.get_access_token().await?;
        let msg_param = MsgParam {
            title: title.to_string(),
            text: text.to_string(),
        };
        if data.get("conversationType").and_then(|v| v.as_str()) == Some("1") {
            let sender_staff_id = data
                .get("senderStaffId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| DingTalkError::ApiError("Missing senderStaffId".to_string()))?;
            let url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend";
            let req_body = OtoMessageRequest {
                msg_param,
                msg_key: "sampleMarkdown",
                robot_code: &self.robot_code,
                user_ids: vec![sender_staff_id],
            };
            let response = self
                .client
                .post(url)
                .header("x-acs-dingtalk-access-token", access_token)
                .json(&req_body)
                .send()
                .await?
                .error_for_status()?
                .text()
                .await?;
            Ok(response)
        } else {
            let conversation_id = data
                .get("conversationId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| DingTalkError::ApiError("Missing conversationId".to_string()))?;
            let url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send";
            let req_body = GroupMessageRequest {
                msg_param,
                msg_key: "sampleMarkdown",
                robot_code: &self.robot_code,
                open_conversation_id: conversation_id,
            };
            let response = self
                .client
                .post(url)
                .header("x-acs-dingtalk-access-token", access_token)
                .json(&req_body)
                .send()
                .await?
                .error_for_status()?
                .text()
                .await?;
            Ok(response)
        }
    }
}

#[derive(Deserialize)]
struct GetTokenResponse {
    errcode: i32,
    errmsg: String,
    access_token: Option<String>,
}