maxbot 0.2.2

Автоматизация работы с чат-ботами на платформе MAX (max.ru)
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
use crate::attachments::{Attachment, AttachmentSource};
use crate::client::MaxClient;
use crate::error::Result;
use crate::utils;
use serde_json::json;
use std::time::Duration;

// -----------------------------------------------------------------------------
// Параметры отправки сообщения (обычная структура)
// -----------------------------------------------------------------------------

/// Параметры для отправки сообщения.
///
/// Содержит все возможные настройки: получатель, текст, форматирование,
/// вложения, уведомления и т.д. Обычно создаётся через [`SendMessageParamsBuilder`].
#[derive(Debug, Clone, Default)]
pub struct SendMessageParams {
    /// Идентификатор чата (если сообщение в групповой чат).
    pub chat_id: Option<i64>,
    /// Идентификатор пользователя (если личное сообщение).
    pub user_id: Option<i64>,
    /// Текст сообщения.
    pub text: String,
    /// Формат текста: `"markdown"` или `"html"`.
    pub format: Option<String>,
    /// Отправлять ли уведомление (по умолчанию `true`).
    pub notify: Option<bool>,
    /// Отключить предпросмотр ссылок.
    pub disable_link_preview: Option<bool>,
    /// Идентификатор сообщения, на которое нужно ответить (`mid`).
    pub reply_mid: Option<String>,
    /// Список вложений.
    pub attachments: Vec<Attachment>,
    /// Максимальное количество повторных попыток при ошибках (по умолчанию 3).
    pub max_retries: usize,
}

// -----------------------------------------------------------------------------
// Builder для SendMessageParams
// -----------------------------------------------------------------------------

/// Построитель параметров для отправки сообщения.
///
/// Позволяет удобно задавать параметры цепочкой методов.
///
/// # Пример
///
/// ```no_run
/// use maxbot::{SendMessageParamsBuilder, Attachment};
///
/// let params = SendMessageParamsBuilder::new()
///     .text("Привет!")
///     .chat_id(123456789)
///     .format_markdown()
///     .attachment(Attachment::image_local("cat.jpg"))
///     .build();
/// ```
pub struct SendMessageParamsBuilder {
    chat_id: Option<i64>,
    user_id: Option<i64>,
    text: String,
    format: Option<String>,
    notify: Option<bool>,
    disable_link_preview: Option<bool>,
    reply_mid: Option<String>,
    attachments: Vec<Attachment>,
    max_retries: usize,
}

impl SendMessageParamsBuilder {
    /// Создаёт новый пустой построитель.
    pub fn new() -> Self {
        Self {
            text: String::new(),
            chat_id: None,
            user_id: None,
            format: None,
            notify: Some(true),
            disable_link_preview: None,
            reply_mid: None,
            attachments: vec![],
            max_retries: 3,
        }
    }

    /// Устанавливает текст сообщения.
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.text = text.into();
        self
    }

    /// Указывает идентификатор чата-получателя.
    pub fn chat_id(mut self, id: i64) -> Self {
        self.chat_id = Some(id);
        self
    }

    /// Указывает идентификатор пользователя-получателя (для личных сообщений).
    pub fn user_id(mut self, id: i64) -> Self {
        self.user_id = Some(id);
        self
    }

    /// Включает Markdown-форматирование текста.
    pub fn format_markdown(mut self) -> Self {
        self.format = Some("markdown".to_string());
        self
    }

    /// Включает HTML-форматирование текста.
    pub fn format_html(mut self) -> Self {
        self.format = Some("html".to_string());
        self
    }

    /// Отключает звуковое уведомление у получателя.
    pub fn silent(mut self) -> Self {
        self.notify = Some(false);
        self
    }

    /// Отключает предпросмотр ссылок в сообщении.
    pub fn disable_preview(mut self) -> Self {
        self.disable_link_preview = Some(true);
        self
    }

    /// Устанавливает сообщение, на которое нужно ответить.
    ///
    /// # Аргументы
    ///
    /// * `mid` - строковый идентификатор сообщения.
    pub fn reply_to(mut self, mid: impl Into<String>) -> Self {
        self.reply_mid = Some(mid.into());
        self
    }

    /// Добавляет одно вложение к сообщению.
    pub fn attachment(mut self, att: Attachment) -> Self {
        self.attachments.push(att);
        self
    }

    /// Заменяет все вложения переданным вектором.
    pub fn attachments(mut self, atts: Vec<Attachment>) -> Self {
        self.attachments = atts;
        self
    }

    /// Устанавливает максимальное число повторных попыток при ошибках отправки.
    pub fn max_retries(mut self, retries: usize) -> Self {
        self.max_retries = retries;
        self
    }

    /// Строит финальную структуру [`SendMessageParams`].
    pub fn build(self) -> SendMessageParams {
        SendMessageParams {
            chat_id: self.chat_id,
            user_id: self.user_id,
            text: self.text,
            format: self.format,
            notify: self.notify,
            disable_link_preview: self.disable_link_preview,
            reply_mid: self.reply_mid,
            attachments: self.attachments,
            max_retries: self.max_retries,
        }
    }
}

impl Default for SendMessageParamsBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// -----------------------------------------------------------------------------
// Параметры для получения списка сообщений
// -----------------------------------------------------------------------------

/// Параметры для получения списка сообщений чата.
#[derive(Debug, Clone, Default)]
pub struct GetMessagesParams {
    /// Идентификатор чата.
    pub chat_id: i64,
    /// Маркер для постраничного вывода (обычно `mid` последнего сообщения из предыдущего ответа).
    pub marker: Option<String>,
    /// Количество сообщений (1–100).
    pub count: Option<u32>,
}

// -----------------------------------------------------------------------------
// Параметры для редактирования сообщения
// -----------------------------------------------------------------------------

/// Параметры для редактирования сообщения.
#[derive(Debug, Clone, Default)]
pub struct EditMessageParams {
    /// Новый текст сообщения.
    pub text: Option<String>,
    /// Формат текста: `"markdown"` или `"html"`.
    pub format: Option<String>,
    /// Новый список вложений (полностью заменяет существующие).
    pub attachments: Vec<Attachment>,
    /// Новая inline-клавиатура (если требуется заменить).
    pub inline_keyboard: Option<crate::attachments::InlineKeyboard>,
    /// Отключить предпросмотр ссылок.
    pub disable_link_preview: Option<bool>,
}

// -----------------------------------------------------------------------------
// Реализация методов MaxClient
// -----------------------------------------------------------------------------

impl MaxClient {
    /// Отправляет сообщение с разбиением длинного текста, поддержкой вложений и
    /// автоматическим откатом в случае ошибки.
    ///
    /// Если текст превышает [`MAX_MESSAGE_LEN`][crate::utils::MAX_MESSAGE_LEN], он
    /// разбивается на несколько фрагментов. Вложения (изображения, видео и т.д.)
    /// прикрепляются только к первому фрагменту, inline‑клавиатура — к последнему.
    ///
    /// # Возвращаемое значение
    ///
    /// Вектор идентификаторов (`mid`) всех отправленных фрагментов сообщения.
    ///
    /// # Ошибки
    ///
    /// Если при отправке какого‑либо фрагмента происходит ошибка, все уже отправленные
    /// фрагменты удаляются, и возвращается ошибка.
    pub async fn send_message(&self, params: SendMessageParams) -> Result<Vec<String>> {
        // Проверка получателя
        if (params.chat_id.is_none() && params.user_id.is_none()) ||
           (params.chat_id.is_some() && params.user_id.is_some()) {
            return Err(crate::error::Error::InvalidInput(
                "Exactly one of chat_id or user_id must be specified".into(),
            ));
        }

        // Подготовка вложений
        let mut ready_attachments = Vec::new();    // (type, token) – файловые
        let mut content_attachments = Vec::new();  // (type, payload) – sticker, contact, location, share
        let mut keyboard_attachments = Vec::new(); // (type, payload) – inline_keyboard

        for att in &params.attachments {
            match att {
                // Файловые типы
                Attachment::Image { source, .. } |
                Attachment::Video { source, .. } |
                Attachment::Audio { source, .. } |
                Attachment::File { source, .. } => {
                    let token = match source {
                        AttachmentSource::LocalFile(path) => {
                            let file_type = att.get_type();
                            let tok = self.upload_file(path, file_type).await?;
                            tokio::time::sleep(Duration::from_millis(500)).await; // пауза для обработки
                            tok
                        }
                        AttachmentSource::Token(tok) => tok.clone(),
                    };
                    ready_attachments.push((att.get_type(), token));
                }
                // Стикер
                Attachment::Sticker { code } => {
                    let payload = json!({ "code": code });
                    content_attachments.push((att.get_type(), json!({ "payload": payload })));
                }
                // Контакт
                Attachment::Contact(data) => {
                    let mut payload = serde_json::Map::new();
                    if let Some(name) = &data.name {
                        payload.insert("name".into(), name.clone().into());
                    }
                    if let Some(contact_id) = data.contact_id {
                        payload.insert("contact_id".into(), contact_id.into());
                    }
                    if let Some(vcf_info) = &data.vcf_info {
                        payload.insert("vcf_info".into(), vcf_info.clone().into());
                    }
                    if let Some(vcf_phone) = &data.vcf_phone {
                        payload.insert("vcf_phone".into(), vcf_phone.clone().into());
                    }
                    content_attachments.push((att.get_type(), json!({ "payload": payload })));
                }
                // Inline-клавиатура
                Attachment::InlineKeyboard(keyboard) => {
                    let mut buttons_json = Vec::new();
                    for row in &keyboard.buttons {
                        let mut row_json = Vec::new();
                        for btn in row {
                            let mut btn_json = serde_json::Map::new();
                            btn_json.insert("type".into(), btn.r#type.clone().into());
                            btn_json.insert("text".into(), btn.text.clone().into());
                            if let Some(payload) = &btn.payload {
                                btn_json.insert("payload".into(), payload.clone().into());
                            }
                            if let Some(url) = &btn.url {
                                btn_json.insert("url".into(), url.clone().into());
                            }
                            if let Some(quick) = btn.quick {
                                btn_json.insert("quick".into(), quick.into());
                            }
                            if let Some(web_app) = &btn.web_app {
                                btn_json.insert("web_app".into(), web_app.clone().into());
                            }
                            if let Some(contact_id) = btn.contact_id {
                                btn_json.insert("contact_id".into(), contact_id.into());
                            }
                            if let Some(app_payload) = &btn.app_payload {
                                btn_json.insert("payload".into(), app_payload.clone().into());
                            }
                            if let Some(msg_text) = &btn.message_text {
                                btn_json.insert("text".into(), msg_text.clone().into());
                            }
                            row_json.push(serde_json::Value::Object(btn_json));
                        }
                        buttons_json.push(serde_json::Value::Array(row_json));
                    }
                    let payload = json!({ "buttons": buttons_json });
                    keyboard_attachments.push((att.get_type(), json!({ "payload": payload })));
                }
                // Геолокация
                Attachment::Location { latitude, longitude } => {
                    let payload = json!({ "latitude": latitude, "longitude": longitude });
                    content_attachments.push((att.get_type(), payload));
                }
                // Отсылка (share)
                Attachment::Share(data) => {
                    let mut payload = serde_json::Map::new();
                    if let Some(url) = &data.url {
                        payload.insert("url".into(), url.clone().into());
                    }
                    if let Some(token) = &data.token {
                        payload.insert("token".into(), token.clone().into());
                    }
                    content_attachments.push((att.get_type(), json!({ "payload": payload })));
                }
            }
        }

        // Разбивка текста на фрагменты
        let fragments = utils::split_text(&params.text, params.format.as_deref());
        let fragments = if fragments.is_empty() &&
            ready_attachments.is_empty() &&
            content_attachments.is_empty()
        {
            return Err(crate::error::Error::InvalidInput(
                "Empty message text and no attachments".into(),
            ));
        } else if fragments.is_empty() {
            vec!["".to_string()]
        } else {
            fragments
        };

        // GET-параметры (передаются в URL)
        let mut get_params = Vec::new();
        if let Some(disable) = params.disable_link_preview {
            get_params.push(("disable_link_preview", disable.to_string()));
        }

        // Формирование link для reply (если задан)
        let reply_link = params
            .reply_mid
            .as_ref()
            .map(|mid| json!({ "type": "reply", "mid": mid }));

        let mut sent_ids = Vec::new();

        for (i, fragment_text) in fragments.iter().enumerate() {
            let mut body = json!({
                "text": fragment_text,
            });
            if let Some(fmt) = &params.format {
                body["format"] = json!(fmt);
            }
            if let Some(notify) = params.notify {
                body["notify"] = json!(notify);
            }

            // Первый фрагмент: файловые вложения + вложения содержимого + reply
            if i == 0 {
                if !body["attachments"].is_array() {
                    body["attachments"] = serde_json::Value::Array(vec![]);
                }
                let attachments_array = body["attachments"].as_array_mut().unwrap();
                for (att_type, token) in &ready_attachments {
                    attachments_array.push(json!({
                        "type": att_type,
                        "payload": { "token": token }
                    }));
                }
                for (att_type, payload) in &content_attachments {
                    let mut attachment = json!({ "type": att_type });
                    if let Some(p) = payload.as_object() {
                        for (k, v) in p {
                            attachment[k] = v.clone();
                        }
                    } else {
                        attachment["payload"] = payload.clone();
                    }
                    attachments_array.push(attachment);
                }
                if let Some(link) = &reply_link {
                    body["link"] = link.clone();
                }
            }
            // Последний фрагмент: клавиатура (если есть)
            if i == fragments.len() - 1 && !keyboard_attachments.is_empty() {
                if !body["attachments"].is_array() {
                    body["attachments"] = serde_json::Value::Array(vec![]);
                }
                let attachments_array = body["attachments"].as_array_mut().unwrap();
                for (att_type, payload) in &keyboard_attachments {
                    let mut attachment = json!({ "type": att_type });
                    if let Some(p) = payload.as_object() {
                        for (k, v) in p {
                            attachment[k] = v.clone();
                        }
                    } else {
                        attachment["payload"] = payload.clone();
                    }
                    attachments_array.push(attachment);
                }
            }

            match self.send_fragment_with_retry(
                params.chat_id,
                params.user_id,
                body,
                &get_params,
                i == 0,                 // is_first
                params.max_retries,
            ).await {
                Ok(mid) => sent_ids.push(mid),
                Err(e) => {
                    // Откат: удалить все успешно отправленные фрагменты
                    if !sent_ids.is_empty() {
                        let _ = self.delete_messages(&sent_ids).await;
                    }
                    return Err(e);
                }
            }
        }

        Ok(sent_ids)
    }

    /// Удобный метод для отправки сообщения с использованием построителя.
    ///
    /// Эквивалентен вызову `send_message(builder.build())`.
    pub async fn send_message_builder(
        &self,
        builder: SendMessageParamsBuilder,
    ) -> Result<Vec<String>> {
        self.send_message(builder.build()).await
    }

    /// Пересылает существующее сообщение в другой чат или пользователю.
    ///
    /// # Аргументы
    ///
    /// * `chat_id` / `user_id` — получатель (должен быть указан ровно один).
    /// * `forward_mid` — строковый идентификатор (`mid`) пересылаемого сообщения.
    /// * `notify` — отправлять ли уведомление (по умолчанию `true`).
    /// * `disable_link_preview` — отключить предпросмотр ссылок.
    ///
    /// # Возвращаемое значение
    ///
    /// Идентификатор (`mid`) нового пересланного сообщения.
    pub async fn forward_message(
        &self,
        chat_id: Option<i64>,
        user_id: Option<i64>,
        forward_mid: &str,
        notify: Option<bool>,
        disable_link_preview: Option<bool>,
    ) -> Result<String> {
        // Проверка получателя
        if (chat_id.is_none() && user_id.is_none()) ||
           (chat_id.is_some() && user_id.is_some()) {
            return Err(crate::error::Error::InvalidInput(
                "Exactly one of chat_id or user_id must be specified".into(),
            ));
        }

        let mut query = Vec::new();
        if let Some(cid) = chat_id {
            query.push(("chat_id", cid.to_string()));
        }
        if let Some(uid) = user_id {
            query.push(("user_id", uid.to_string()));
        }
        if let Some(disable) = disable_link_preview {
            query.push(("disable_link_preview", disable.to_string()));
        }
        // Обязательный параметр: message_id (строковый mid)
        query.push(("message_id", forward_mid.to_string()));

        let body = json!({
            "link": {
                "type": "forward",
                "mid": forward_mid
            },
            "notify": notify.unwrap_or(true),
        });

        let resp: serde_json::Value = self.request_with_rate_limit(
            reqwest::Method::POST,
            "/messages",
            &query,
            Some(body),
        ).await?;

        let new_mid = resp["message"]["body"]["mid"]
            .as_str()
            .ok_or_else(|| crate::error::Error::Api {
                code: 500,
                message: "No message ID in forward response".into(),
            })?;
        Ok(new_mid.to_string())
    }

    /// Удаляет одно сообщение по его идентификатору `mid`.
    pub async fn delete_message(&self, message_id: &str) -> Result<()> {
        self.request_with_rate_limit::<serde_json::Value>(
            reqwest::Method::DELETE,
            "/messages",
            &[("message_id", message_id.to_string())],
            None,
        ).await?;
        Ok(())
    }

    /// Удаляет несколько сообщений последовательно.
    ///
    /// Ошибки при удалении отдельных сообщений игнорируются (выводится предупреждение в stderr).
    pub async fn delete_messages(&self, message_ids: &[String]) -> Result<()> {
        for id in message_ids {
            if let Err(e) = self.delete_message(id).await {
                eprintln!("Warning: failed to delete message {}: {}", id, e);
            }
        }
        Ok(())
    }

    /// Возвращает постраничный список сообщений из указанного чата.
    ///
    /// Сообщения возвращаются в обратном хронологическом порядке (от новых к старым).
    ///
    /// # Аргументы
    ///
    /// * `params` - параметры запроса ([`GetMessagesParams`]).
    ///
    /// # Возвращаемое значение
    ///
    /// Кортеж `(сообщения, следующий_маркер)`. Если `следующий_маркер` равен `None`,
    /// достигнут конец истории чата.
    ///
    /// # Пример
    ///
    /// ```no_run
    /// # use maxbot::{MaxClient, GetMessagesParams};
    /// # async fn example(client: &MaxClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let (messages, next_marker) = client.get_messages(GetMessagesParams {
    ///     chat_id: 123456789,
    ///     count: Some(50),
    ///     ..Default::default()
    /// }).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_messages(
        &self,
        params: GetMessagesParams,
    ) -> Result<(Vec<crate::types::Message>, Option<String>)> {
        let mut query = vec![("chat_id", params.chat_id.to_string())];
        if let Some(m) = &params.marker {
            query.push(("marker", m.clone()));
        }
        if let Some(c) = params.count {
            query.push(("count", c.to_string()));
        }
        let resp: serde_json::Value = self
            .request_with_rate_limit(reqwest::Method::GET, "/messages", &query, None)
            .await?;
        let messages: Vec<crate::types::Message> =
            serde_json::from_value(resp["messages"].clone())?;
        let next_marker = resp
            .get("marker")
            .and_then(|v| v.as_str())
            .map(String::from);
        Ok((messages, next_marker))
    }

    /// Редактирует ранее отправленное сообщение.
    ///
    /// Можно изменить текст, форматирование, вложения и inline‑клавиатуру.
    /// Поля, оставленные как `None`, не изменяются.
    ///
    /// # Аргументы
    ///
    /// * `message_mid` - строковый идентификатор (`mid`) редактируемого сообщения.
    /// * `params` - параметры редактирования ([`EditMessageParams`]).
    ///
    /// # Пример
    ///
    /// ```no_run
    /// # use maxbot::{MaxClient, EditMessageParams};
    /// # async fn example(client: &MaxClient) -> Result<(), Box<dyn std::error::Error>> {
    /// let params = EditMessageParams {
    ///     text: Some("Обновлённый текст".to_string()),
    ///     ..Default::default()
    /// };
    /// client.edit_message("abc123mid", params).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn edit_message(&self, message_mid: &str, params: EditMessageParams) -> Result<()> {
        let mut body = serde_json::Map::new();
        if let Some(text) = params.text {
            body.insert("text".into(), text.into());
        }
        if let Some(format) = params.format {
            body.insert("format".into(), format.into());
        }
        if let Some(disable) = params.disable_link_preview {
            body.insert("disable_link_preview".into(), disable.into());
        }

        // Обработка вложений
        if !params.attachments.is_empty() || params.inline_keyboard.is_some() {
            let mut attachments_json = Vec::new();
            for att in &params.attachments {
                match att {
                    Attachment::Image { token, .. }
                    | Attachment::Video { token, .. }
                    | Attachment::Audio { token, .. }
                    | Attachment::File { token, .. } => {
                        if let Some(tok) = token {
                            attachments_json.push(serde_json::json!({
                                "type": att.get_type(),
                                "payload": { "token": tok }
                            }));
                        }
                    }
                    Attachment::Sticker { code } => {
                        attachments_json.push(serde_json::json!({
                            "type": "sticker",
                            "payload": { "code": code }
                        }));
                    }
                    Attachment::Contact(data) => {
                        let mut payload = serde_json::Map::new();
                        if let Some(name) = &data.name {
                            payload.insert("name".into(), name.clone().into());
                        }
                        if let Some(contact_id) = data.contact_id {
                            payload.insert("contact_id".into(), contact_id.into());
                        }
                        if let Some(vcf_info) = &data.vcf_info {
                            payload.insert("vcf_info".into(), vcf_info.clone().into());
                        }
                        if let Some(vcf_phone) = &data.vcf_phone {
                            payload.insert("vcf_phone".into(), vcf_phone.clone().into());
                        }
                        attachments_json.push(serde_json::json!({
                            "type": "contact",
                            "payload": payload
                        }));
                    }
                    Attachment::Location { latitude, longitude } => {
                        attachments_json.push(serde_json::json!({
                            "type": "location",
                            "payload": { "latitude": latitude, "longitude": longitude }
                        }));
                    }
                    Attachment::Share(data) => {
                        let mut payload = serde_json::Map::new();
                        if let Some(url) = &data.url {
                            payload.insert("url".into(), url.clone().into());
                        }
                        if let Some(token) = &data.token {
                            payload.insert("token".into(), token.clone().into());
                        }
                        attachments_json.push(serde_json::json!({
                            "type": "share",
                            "payload": payload
                        }));
                    }
                    Attachment::InlineKeyboard(_) => {} // обрабатывается отдельно
                }
            }
            if let Some(keyboard) = params.inline_keyboard {
                let mut buttons_json = Vec::new();
                for row in &keyboard.buttons {
                    let mut row_json = Vec::new();
                    for btn in row {
                        let mut btn_json = serde_json::Map::new();
                        btn_json.insert("type".into(), btn.r#type.clone().into());
                        btn_json.insert("text".into(), btn.text.clone().into());
                        if let Some(payload) = &btn.payload {
                            btn_json.insert("payload".into(), payload.clone().into());
                        }
                        if let Some(url) = &btn.url {
                            btn_json.insert("url".into(), url.clone().into());
                        }
                        if let Some(quick) = btn.quick {
                            btn_json.insert("quick".into(), quick.into());
                        }
                        if let Some(web_app) = &btn.web_app {
                            btn_json.insert("web_app".into(), web_app.clone().into());
                        }
                        if let Some(contact_id) = btn.contact_id {
                            btn_json.insert("contact_id".into(), contact_id.into());
                        }
                        if let Some(app_payload) = &btn.app_payload {
                            btn_json.insert("payload".into(), app_payload.clone().into());
                        }
                        if let Some(msg_text) = &btn.message_text {
                            btn_json.insert("text".into(), msg_text.clone().into());
                        }
                        row_json.push(serde_json::Value::Object(btn_json));
                    }
                    buttons_json.push(serde_json::Value::Array(row_json));
                }
                attachments_json.push(serde_json::json!({
                    "type": "inline_keyboard",
                    "payload": { "buttons": buttons_json }
                }));
            }
            if !attachments_json.is_empty() {
                body.insert("attachments".into(), attachments_json.into());
            }
        }

        self.request_with_rate_limit::<serde_json::Value>(
            reqwest::Method::PUT,
            "/messages",
            &[("message_id", message_mid.to_string())],
            Some(serde_json::Value::Object(body)),
        )
        .await?;
        Ok(())
    }

    // -------------------------------------------------------------------------
    // Внутренние вспомогательные методы
    // -------------------------------------------------------------------------

    async fn send_fragment_with_retry(
        &self,
        chat_id: Option<i64>,
        user_id: Option<i64>,
        body: serde_json::Value,
        get_params: &[(&str, String)],
        is_first: bool,
        max_retries: usize,
    ) -> Result<String> {
        let mut attempt = 0;
        let mut delay_sec = 1;          // для ошибки attachment.not.ready
        let mut rate_limit_delay_sec = 5; // для ошибки 429

        loop {
            match self.send_single_fragment(chat_id, user_id, body.clone(), get_params).await {
                Ok(mid) => return Ok(mid),
                Err(e) => {
                    if !is_first {
                        // Для не-первого фрагмента не повторяем при ошибках вложений
                        return Err(e);
                    }
                    attempt += 1;
                    if attempt >= max_retries {
                        return Err(e);
                    }
                    let err_str = e.to_string();
                    if err_str.contains("429") || err_str.contains("too.many.requests") {
                        tokio::time::sleep(Duration::from_secs(rate_limit_delay_sec)).await;
                        rate_limit_delay_sec *= 2;
                        continue;
                    }
                    if err_str.contains("attachment.not.ready") || err_str.contains("not.processed") {
                        tokio::time::sleep(Duration::from_secs(delay_sec)).await;
                        delay_sec *= 2;
                        continue;
                    }
                    return Err(e);
                }
            }
        }
    }

    async fn send_single_fragment(
        &self,
        chat_id: Option<i64>,
        user_id: Option<i64>,
        body: serde_json::Value,
        get_params: &[(&str, String)],
    ) -> Result<String> {
        let mut query = get_params.to_vec();
        if let Some(cid) = chat_id {
            query.push(("chat_id", cid.to_string()));
        }
        if let Some(uid) = user_id {
            query.push(("user_id", uid.to_string()));
        }

        let resp: serde_json::Value = self.request_with_rate_limit(
            reqwest::Method::POST,
            "/messages",
            &query,
            Some(body),
        ).await?;

        let mid = resp["message"]["body"]["mid"]
            .as_str()
            .ok_or_else(|| crate::error::Error::Api {
                code: 500,
                message: "No message ID in response (expected message.body.mid)".into(),
            })?;
        Ok(mid.to_string())
    }
}