telegram_bot_oxidebot 0.1.3

Telegram Bot for oxidebot framework
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
//! A small, forward-compatible Telegram Bot API client.
//!
//! The adapter used to depend on `telegram_bot_api_rs`, whose public schema is
//! frozen at Bot API 7.9.  Updates are intentionally decoded as a map here: a
//! new Telegram update kind can therefore be forwarded as a raw event instead
//! of making the whole `getUpdates` response fail to deserialize.

use std::{collections::BTreeMap, fmt, sync::Arc, time::Duration};

use anyhow::{Context as _, Result};
use reqwest::multipart::{Form, Part};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::{Map, Value};

pub const BOT_API_VERSION: &str = "10.2";

#[derive(Clone)]
pub struct TelegramClient {
    token: Arc<str>,
    api_base: Arc<str>,
    client: reqwest::Client,
}

impl fmt::Debug for TelegramClient {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TelegramClient")
            .field("token", &"<redacted>")
            .field("api_base", &self.api_base)
            .finish_non_exhaustive()
    }
}

impl TelegramClient {
    pub fn new(token: impl Into<String>) -> Result<Self> {
        Self::with_api_base(token, "https://api.telegram.org")
    }

    /// Creates a client for Telegram or a compatible local Bot API server.
    pub fn with_api_base(token: impl Into<String>, api_base: impl Into<String>) -> Result<Self> {
        let token = token.into();
        anyhow::ensure!(
            !token.trim().is_empty(),
            "Telegram bot token cannot be empty"
        );
        anyhow::ensure!(
            token
                .chars()
                .all(|character| character.is_ascii_alphanumeric() || "_:-".contains(character)),
            "Telegram bot token contains invalid characters"
        );

        let api_base = api_base.into().trim_end_matches('/').to_owned();
        let client = reqwest::Client::builder()
            .connect_timeout(Duration::from_secs(15))
            .user_agent(concat!(
                env!("CARGO_PKG_NAME"),
                "/",
                env!("CARGO_PKG_VERSION")
            ))
            .build()
            .context("failed to create Telegram HTTP client")?;

        Ok(Self {
            token: token.into(),
            api_base: api_base.into(),
            client,
        })
    }

    fn method_url(&self, method: &str) -> String {
        format!("{}/bot{}/{}", self.api_base, self.token, method)
    }

    pub fn file_url(&self, path: &str) -> String {
        format!("{}/file/bot{}/{}", self.api_base, self.token, path)
    }

    pub async fn call<P, T>(&self, method: &str, payload: &P) -> Result<T>
    where
        P: Serialize + ?Sized,
        T: DeserializeOwned,
    {
        validate_method(method)?;
        let response = self
            .client
            .post(self.method_url(method))
            .json(payload)
            .send()
            .await
            .with_context(|| format!("Telegram {method} request failed"))?;
        self.decode_response(method, response).await
    }

    pub async fn call_multipart<T>(&self, method: &str, form: Form) -> Result<T>
    where
        T: DeserializeOwned,
    {
        validate_method(method)?;
        let response = self
            .client
            .post(self.method_url(method))
            .multipart(form)
            .send()
            .await
            .with_context(|| format!("Telegram {method} upload failed"))?;
        self.decode_response(method, response).await
    }

    async fn decode_response<T>(&self, method: &str, response: reqwest::Response) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let status = response.status();
        let body = response
            .bytes()
            .await
            .with_context(|| format!("failed to read Telegram {method} response"))?;
        let response: ApiResponse<T> = serde_json::from_slice(&body).with_context(|| {
            let preview = String::from_utf8_lossy(&body);
            let preview: String = preview.chars().take(500).collect();
            format!("Telegram {method} returned invalid JSON (HTTP {status}): {preview}")
        })?;

        if response.ok {
            response
                .result
                .ok_or_else(|| anyhow::anyhow!("Telegram {method} succeeded without a result"))
        } else {
            Err(TelegramApiError {
                method: method.to_owned(),
                http_status: status.as_u16(),
                error_code: response.error_code,
                description: response
                    .description
                    .unwrap_or_else(|| "unknown Telegram API error".to_owned()),
                parameters: response.parameters,
            }
            .into())
        }
    }

    pub async fn get_updates(&self, config: &GetUpdatesConfig) -> Result<Vec<Update>> {
        self.call("getUpdates", config).await
    }

    pub async fn get_me(&self) -> Result<User> {
        self.call("getMe", &EmptyPayload {}).await
    }

    pub async fn get_file(&self, file_id: &str) -> Result<TelegramFile> {
        self.call("getFile", &serde_json::json!({ "file_id": file_id }))
            .await
    }
}

fn validate_method(method: &str) -> Result<()> {
    anyhow::ensure!(!method.is_empty(), "Telegram API method cannot be empty");
    anyhow::ensure!(
        method
            .chars()
            .all(|character| character.is_ascii_alphanumeric() || character == '_'),
        "invalid Telegram API method {method:?}"
    );
    Ok(())
}

#[derive(Debug, Deserialize)]
struct ApiResponse<T> {
    ok: bool,
    result: Option<T>,
    #[serde(default)]
    error_code: Option<i64>,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    parameters: Option<ResponseParameters>,
}

/// Additional recovery information returned with a failed Telegram request.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
pub struct ResponseParameters {
    #[serde(default)]
    pub migrate_to_chat_id: Option<i64>,
    #[serde(default)]
    pub retry_after: Option<u64>,
}

/// A structured Bot API error that can be recovered with
/// [`anyhow::Error::downcast_ref`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TelegramApiError {
    pub method: String,
    pub http_status: u16,
    pub error_code: Option<i64>,
    pub description: String,
    pub parameters: Option<ResponseParameters>,
}

impl fmt::Display for TelegramApiError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "Telegram {} failed (HTTP {}, API code {}): {}",
            self.method,
            self.http_status,
            self.error_code.unwrap_or_default(),
            self.description
        )?;
        if let Some(parameters) = &self.parameters {
            if let Some(chat_id) = parameters.migrate_to_chat_id {
                write!(formatter, "; migrated to chat {chat_id}")?;
            }
            if let Some(seconds) = parameters.retry_after {
                write!(formatter, "; retry after {seconds}s")?;
            }
        }
        Ok(())
    }
}

impl std::error::Error for TelegramApiError {}

#[derive(Serialize)]
struct EmptyPayload {}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GetUpdatesConfig {
    #[serde(default = "default_limit")]
    pub limit: u8,
    #[serde(default = "default_timeout")]
    pub timeout: u16,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_updates: Option<Vec<String>>,
}

const fn default_limit() -> u8 {
    100
}

const fn default_timeout() -> u16 {
    60
}

impl Default for GetUpdatesConfig {
    fn default() -> Self {
        Self {
            limit: default_limit(),
            timeout: default_timeout(),
            offset: None,
            allowed_updates: None,
        }
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct Update {
    pub update_id: i64,
    #[serde(flatten)]
    pub data: Map<String, Value>,
}

impl Update {
    pub fn kind(&self) -> Option<&str> {
        self.data.keys().next().map(String::as_str)
    }

    pub fn value(&self) -> Option<&Value> {
        self.data.values().next()
    }

    pub fn decode<T: DeserializeOwned>(&self, name: &str) -> Result<T> {
        let value = self
            .data
            .get(name)
            .cloned()
            .ok_or_else(|| anyhow::anyhow!("update does not contain {name}"))?;
        serde_json::from_value(value)
            .with_context(|| format!("failed to decode Telegram {name} update"))
    }
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct User {
    pub id: i64,
    #[serde(default)]
    pub is_bot: bool,
    #[serde(default)]
    pub first_name: String,
    #[serde(default)]
    pub last_name: Option<String>,
    #[serde(default)]
    pub username: Option<String>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Chat {
    pub id: i64,
    #[serde(rename = "type", default)]
    pub kind: String,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub username: Option<String>,
    #[serde(default)]
    pub first_name: Option<String>,
    #[serde(default)]
    pub last_name: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct ChatFullInfo {
    pub id: i64,
    #[serde(rename = "type", default)]
    pub kind: String,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub username: Option<String>,
    #[serde(default)]
    pub first_name: Option<String>,
    #[serde(default)]
    pub last_name: Option<String>,
    #[serde(default)]
    pub bio: Option<String>,
    #[serde(default)]
    pub birthdate: Option<Birthdate>,
    #[serde(default)]
    pub photo: Option<ChatPhoto>,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct Birthdate {
    pub day: u32,
    pub month: u32,
    #[serde(default)]
    pub year: Option<i32>,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct ChatPhoto {
    pub small_file_id: String,
    pub big_file_id: String,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct Message {
    pub message_id: i64,
    #[serde(default)]
    pub date: i64,
    pub chat: Chat,
    #[serde(default)]
    pub from: Option<User>,
    #[serde(default)]
    pub sender_chat: Option<Chat>,
    #[serde(default)]
    pub text: Option<String>,
    #[serde(default)]
    pub entities: Option<Vec<MessageEntity>>,
    #[serde(default)]
    pub photo: Option<Vec<PhotoSize>>,
    #[serde(default)]
    pub animation: Option<Animation>,
    #[serde(default)]
    pub audio: Option<Audio>,
    #[serde(default)]
    pub video: Option<Video>,
    #[serde(default)]
    pub video_note: Option<VideoNote>,
    #[serde(default)]
    pub document: Option<Document>,
    #[serde(default)]
    pub sticker: Option<Sticker>,
    #[serde(default)]
    pub voice: Option<Voice>,
    #[serde(default)]
    pub caption: Option<String>,
    #[serde(default)]
    pub caption_entities: Option<Vec<MessageEntity>>,
    #[serde(default)]
    pub venue: Option<Venue>,
    #[serde(default)]
    pub location: Option<Location>,
    #[serde(default)]
    pub new_chat_members: Option<Vec<User>>,
    #[serde(default)]
    pub left_chat_member: Option<User>,
    #[serde(default)]
    pub rich_message: Option<Value>,
    #[serde(default)]
    pub live_photo: Option<Value>,
    #[serde(default)]
    pub paid_media: Option<Value>,
    #[serde(default)]
    pub story: Option<Value>,
    #[serde(default)]
    pub contact: Option<Value>,
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct MessageEntity {
    #[serde(rename = "type")]
    pub kind: String,
    pub offset: usize,
    pub length: usize,
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub user: Option<User>,
    #[serde(default)]
    pub custom_emoji_id: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct PhotoSize {
    pub file_id: String,
    #[serde(default)]
    pub width: u64,
    #[serde(default)]
    pub height: u64,
    #[serde(default)]
    pub file_size: Option<u64>,
}

macro_rules! telegram_media_type {
    ($name:ident) => {
        #[derive(Clone, Debug, Default, Deserialize)]
        pub struct $name {
            pub file_id: String,
            #[serde(default)]
            pub file_name: Option<String>,
            #[serde(default)]
            pub mime_type: Option<String>,
            #[serde(default)]
            pub duration: i64,
            #[serde(default)]
            pub file_size: Option<u64>,
        }
    };
}

telegram_media_type!(Animation);
telegram_media_type!(Audio);
telegram_media_type!(Video);
telegram_media_type!(VideoNote);
telegram_media_type!(Document);
telegram_media_type!(Voice);

#[derive(Clone, Debug, Default, Deserialize)]
pub struct Sticker {
    pub file_id: String,
    #[serde(default)]
    pub emoji: Option<String>,
    #[serde(default)]
    pub file_size: Option<u64>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Location {
    pub latitude: f64,
    pub longitude: f64,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct Venue {
    pub location: Location,
    pub title: String,
    pub address: String,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct MessageReactionUpdated {
    pub chat: Chat,
    pub message_id: i64,
    #[serde(default)]
    pub user: Option<User>,
    #[serde(default)]
    pub actor_chat: Option<Chat>,
    #[serde(default)]
    pub old_reaction: Vec<ReactionType>,
    #[serde(default)]
    pub new_reaction: Vec<ReactionType>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ReactionType {
    #[serde(rename = "type")]
    pub kind: String,
    #[serde(default)]
    pub emoji: Option<String>,
    #[serde(default)]
    pub custom_emoji_id: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct ChatMemberUpdated {
    pub chat: Chat,
    pub from: User,
    pub date: i64,
    pub old_chat_member: ChatMember,
    pub new_chat_member: ChatMember,
    #[serde(default)]
    pub via_join_request: Option<bool>,
    #[serde(default)]
    pub via_chat_folder_invite_link: Option<bool>,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct ChatMember {
    pub status: String,
    pub user: User,
    #[serde(default)]
    pub is_member: Option<bool>,
    #[serde(default)]
    pub can_send_messages: Option<bool>,
    #[serde(default)]
    pub until_date: Option<i64>,
    #[serde(default)]
    pub custom_title: Option<String>,
}

impl ChatMember {
    pub fn is_present(&self) -> bool {
        match self.status.as_str() {
            "creator" | "administrator" | "member" => true,
            "restricted" => self.is_member.unwrap_or(true),
            _ => false,
        }
    }

    pub fn is_admin(&self) -> bool {
        matches!(self.status.as_str(), "creator" | "administrator")
    }

    pub fn is_muted(&self) -> bool {
        self.status == "restricted" && self.can_send_messages == Some(false)
    }
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct ChatJoinRequest {
    pub chat: Chat,
    pub from: User,
    #[serde(default)]
    pub user_chat_id: i64,
    #[serde(default)]
    pub bio: Option<String>,
    #[serde(default)]
    pub query_id: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize)]
pub struct TelegramFile {
    pub file_id: String,
    #[serde(default)]
    pub file_unique_id: String,
    #[serde(default)]
    pub file_size: Option<u64>,
    #[serde(default)]
    pub file_path: Option<String>,
}

#[derive(Debug)]
pub struct Upload {
    pub name: String,
    pub bytes: Vec<u8>,
    pub mime: Option<String>,
}

impl Upload {
    pub fn into_part(self) -> Result<Part> {
        let mut part = Part::bytes(self.bytes).file_name(self.name);
        if let Some(mime) = self.mime {
            part = part
                .mime_str(&mime)
                .with_context(|| format!("invalid upload MIME type {mime}"))?;
        }
        Ok(part)
    }
}

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

    #[test]
    fn unknown_bot_api_10_2_update_stays_decodable() {
        let update: Update = serde_json::from_value(serde_json::json!({
            "update_id": 42,
            "subscription": {
                "id": "sub",
                "new_field_from_a_future_api": true
            }
        }))
        .unwrap();

        assert_eq!(update.kind(), Some("subscription"));
        assert_eq!(update.value().unwrap()["new_field_from_a_future_api"], true);
    }

    #[test]
    fn client_debug_never_contains_the_token() {
        let client = TelegramClient::with_api_base("123:top-secret", "http://localhost").unwrap();
        let debug = format!("{client:?}");
        assert!(!debug.contains("top-secret"));
        assert!(debug.contains("<redacted>"));
    }

    #[test]
    fn restricted_member_presence_uses_is_member() {
        let mut member = ChatMember {
            status: "restricted".to_owned(),
            is_member: Some(false),
            ..Default::default()
        };
        assert!(!member.is_present());
        member.is_member = Some(true);
        assert!(member.is_present());
    }

    #[test]
    fn method_names_cannot_escape_the_bot_api_path() {
        assert!(validate_method("sendRichMessage").is_ok());
        assert!(validate_method("future_method_1").is_ok());
        assert!(validate_method("../getMe").is_err());
        assert!(validate_method("").is_err());
    }

    #[test]
    fn api_errors_preserve_all_response_parameters() {
        let error = TelegramApiError {
            method: "sendMessage".to_owned(),
            http_status: 429,
            error_code: Some(429),
            description: "Too Many Requests".to_owned(),
            parameters: Some(ResponseParameters {
                migrate_to_chat_id: Some(-1_001),
                retry_after: Some(5),
            }),
        };

        assert!(error.to_string().contains("migrated to chat -1001"));
        assert!(error.to_string().contains("retry after 5s"));
    }
}