maxbot 0.1.0

Автоматизация работы с чат-ботами MAX
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
use serde_json::json;
use std::time::Duration;
use crate::client::MaxClient;
use crate::error::Result;
use crate::attachments::{Attachment, AttachmentSource};
use crate::utils;

// -----------------------------------------------------------------------------
// Параметры отправки сообщения (обычная структура)
// -----------------------------------------------------------------------------
#[derive(Debug, Clone, Default)]
pub struct SendMessageParams {
    pub chat_id: Option<i64>,
    pub user_id: Option<i64>,
    pub text: String,
    pub format: Option<String>,      // "markdown" или "html"
    pub notify: Option<bool>,
    pub disable_link_preview: Option<bool>,
    pub reply_mid: Option<String>,
    pub attachments: Vec<Attachment>,
    pub max_retries: usize,
}

// -----------------------------------------------------------------------------
// Builder для SendMessageParams
// -----------------------------------------------------------------------------
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
    }

    pub fn format_markdown(mut self) -> Self {
        self.format = Some("markdown".to_string());
        self
    }

    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
    }

    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
    }

    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()
    }
}

// -----------------------------------------------------------------------------
// Реализация методов MaxClient
// -----------------------------------------------------------------------------
impl MaxClient {
    /// Отправка сообщения с разбиением на фрагменты, поддержкой вложений и откатом.
    /// Возвращает список идентификаторов (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)
    }

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

    /// Пересылка сообщения (forward)
    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(())
    }

    /// Удаление нескольких сообщений (последовательно, игнорирует ошибки отдельных)
    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(())
    }

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

    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())
    }
}