maxbot 0.7.6

Автоматизация работы с чат-ботами на платформе 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
//! Высокоуровневый диспетчер событий с регистрацией обработчиков и длительным опросом.
//!
//! Вдохновлён проектами `maxoxide` и `teloxide`.

use std::future::Future;
use std::sync::Arc;
use std::time::Duration;

use log::{error, info, warn};

use crate::Attachment;
use crate::Message;
use crate::SendMessageParamsBuilder;
use crate::api::messages::EditMessageParams;
use crate::attachments::InlineKeyboard;
use crate::client::MaxClient;
use crate::error::Result;
use crate::types::{NewMessageBody, Update};

// -----------------------------------------------------------------------------
// Контекст
// -----------------------------------------------------------------------------

/// Контекст, передаваемый каждому обработчику.
///
/// Содержит ссылку на клиент бота и обновление, которое вызвало этот обработчик.
#[derive(Clone)]
pub struct Context {
    pub(crate) bot: Arc<MaxClient>,
    pub update: Update,
}

impl Context {
    pub fn new(bot: Arc<MaxClient>, update: Update) -> Self {
        Self { bot, update }
    }

    /// Возвращает ссылку на клиент бота.
    pub fn bot(&self) -> &MaxClient {
        &self.bot
    }

    /// Возвращает сообщение, если обновление является созданным или отредактированным сообщением.
    pub fn message(&self) -> Option<&Message> {
        match &self.update {
            Update::MessageCreated { message, .. } => Some(message),
            Update::MessageEdited { message, .. } => Some(message),
            _ => None,
        }
    }

    /// Возвращает идентификатор чата, если обновление связано с чатом.
    pub fn chat_id(&self) -> Option<i64> {
        match &self.update {
            Update::MessageCreated { message, .. } => message.recipient.chat_id,
            Update::MessageEdited { message, .. } => message.recipient.chat_id,
            Update::MessageCallback { message, .. } => message.as_ref().and_then(|m| m.recipient.chat_id),
            Update::BotStarted { chat_id, .. } => Some(*chat_id),
            Update::BotAdded { chat_id, .. } => Some(*chat_id),
            Update::BotRemoved { chat_id, .. } => Some(*chat_id),
            Update::UserAdded { chat_id, .. } => Some(*chat_id),
            Update::UserRemoved { chat_id, .. } => Some(*chat_id),
            Update::ChatTitleChanged { chat_id, .. } => Some(*chat_id),
            _ => None,
        }
    }

    /// Возвращает идентификатор пользователя — инициатора обновления.
    pub fn user_id(&self) -> Option<i64> {
        match &self.update {
            Update::MessageCreated { message, .. } => message.sender.as_ref().map(|u| u.user_id),
            Update::MessageEdited { message, .. } => message.sender.as_ref().map(|u| u.user_id),
            Update::MessageCallback { callback, .. } => Some(callback.user.user_id),
            Update::BotStarted { user, .. } => Some(user.user_id),
            Update::BotAdded { user, .. } => Some(user.user_id),
            Update::BotRemoved { user, .. } => Some(user.user_id),
            Update::UserAdded { user, .. } => Some(user.user_id),
            Update::UserRemoved { user, .. } => Some(user.user_id),
            Update::ChatTitleChanged { user, .. } => Some(user.user_id),
            _ => None,
        }
    }

    /// Возвращает текст сообщения, если это обновление является сообщением.
    pub fn text(&self) -> Option<&str> {
        match &self.update {
            Update::MessageCreated { message, .. } => message.body.as_ref().and_then(|b| b.text.as_deref()),
            Update::MessageEdited { message, .. } => message.body.as_ref().and_then(|b| b.text.as_deref()),
            _ => None,
        }
    }

    /// Отправляет простой текстовый ответ в тот же чат.
    pub async fn reply_text(&self, text: &str) -> Result<Vec<String>> {
        let chat_id = self.chat_id().ok_or_else(|| {
            crate::error::Error::InvalidInput("Cannot reply: update has no chat_id".into())
        })?;
        let params = SendMessageParamsBuilder::new()
            .text(text)
            .chat_id(chat_id)
            .build();
        self.bot.send_message(params).await
    }

    /// Отправляет ответ в формате Markdown.
    pub async fn reply_markdown(&self, text: &str) -> Result<Vec<String>> {
        let chat_id = self.chat_id().ok_or_else(|| {
            crate::error::Error::InvalidInput("Cannot reply: update has no chat_id".into())
        })?;
        let params = SendMessageParamsBuilder::new()
            .text(text)
            .chat_id(chat_id)
            .format_markdown()
            .build();
        self.bot.send_message(params).await
    }

    /// Отвечает на запрос обратного вызова необязательным уведомлением и/или заменяющим сообщением.
    ///
    /// Работает только если обновление имеет тип `MessageCallback`.
    pub async fn answer_callback(
        &self,
        notification: Option<&str>,
        new_message: Option<crate::api::messages::SendMessageParams>,
    ) -> Result<bool> {
        match &self.update {
            Update::MessageCallback { callback, .. } => {
                let message_json = if let Some(params) = new_message {
                    let mut body = serde_json::Map::new();
                    if !params.text.is_empty() {
                        body.insert("text".into(), params.text.into());
                    }
                    if let Some(fmt) = params.format {
                        body.insert("format".into(), fmt.into());
                    }
                    if let Some(disable) = params.disable_link_preview {
                        body.insert("disable_link_preview".into(), disable.into());
                    }
                    if !params.attachments.is_empty() {
                        // Подготовка вложений
                        let attachments_json = crate::api::messages::prepare_attachments_json(&self.bot, &params.attachments).await?;
                        body.insert("attachments".into(), attachments_json);
                    }
                    Some(serde_json::Value::Object(body))
                } else {
                    None
                };
                self.bot
                    .answer_callback_query(&callback.callback_id, message_json, notification)
                    .await
            }
            _ => Err(crate::error::Error::InvalidInput(
                "answer_callback only works on MessageCallback updates".into(),
            )),
        }
    }

    /// Отвечает на запрос обратного вызова, передавая новое сообщение в виде сырого JSON.
    pub async fn answer_callback_raw(
        &self,
        notification: Option<&str>,
        message_json: Option<serde_json::Value>,
    ) -> Result<bool> {
        match &self.update {
            Update::MessageCallback { callback, .. } => {
                self.bot
                    .answer_callback_query(&callback.callback_id, message_json, notification)
                    .await
            }
            _ => Err(crate::error::Error::InvalidInput(
                "answer_callback_raw only works on MessageCallback updates".into(),
            )),
        }
    }

    /// Редактирует текст текущего сообщения (только если update содержит message).
    pub async fn edit_text(&self, new_text: &str) -> Result<()> {
        let message = self
            .message()
            .ok_or_else(|| crate::error::Error::InvalidInput(
                "edit_text can only be used on MessageCreated or MessageEdited updates".into()
            ))?;
        let message_id = message.message_id().ok_or_else(|| {
            crate::error::Error::InvalidInput("Message has no body or mid".into())
        })?;
        let params = EditMessageParams {
            text: Some(new_text.to_string()),
            ..Default::default()
        };
        self.bot.edit_message(message_id, params).await
    }

    /// Заменяет inline-клавиатуру у текущего сообщения.
    pub async fn edit_keyboard(&self, keyboard: InlineKeyboard) -> Result<()> {
        let message = self
            .message()
            .ok_or_else(|| crate::error::Error::InvalidInput(
                "edit_keyboard can only be used on MessageCreated or MessageEdited updates".into()
            ))?;
        let message_id = message.message_id().ok_or_else(|| {
            crate::error::Error::InvalidInput("Message has no body or mid".into())
        })?;
        let params = EditMessageParams {
            inline_keyboard: Some(keyboard),
            ..Default::default()
        };
        self.bot.edit_message(message_id, params).await
    }

    /// Общий метод редактирования сообщения.
    pub async fn edit_message(&self, params: EditMessageParams) -> Result<()> {
        let message = self
            .message()
            .ok_or_else(|| crate::error::Error::InvalidInput(
                "edit_message can only be used on MessageCreated or MessageEdited updates".into()
            ))?;
        let message_id = message.message_id().ok_or_else(|| {
            crate::error::Error::InvalidInput("Message has no body or mid".into())
        })?;
        self.bot.edit_message(message_id, params).await
    }

    /// Отвечает на callback только всплывающим уведомлением (не меняя сообщение).
    pub async fn answer_callback_notification(&self, notification: &str) -> Result<bool> {
        match &self.update {
            Update::MessageCallback { callback, .. } => {
                self.bot
                    .answer_callback_query(&callback.callback_id, None, Some(notification))
                    .await
            }
            _ => Err(crate::error::Error::InvalidInput(
                "answer_callback_* only works on MessageCallback updates".into(),
            )),
        }
    }

    /// Отвечает на callback, полностью заменяя сообщение (текст + клавиатура + вложения).
    pub async fn answer_callback_replace(&self, message: NewMessageBody) -> Result<bool> {
        match &self.update {
            Update::MessageCallback { callback, .. } => {
                // Конвертируем NewMessageBody в JSON
                let value = serde_json::to_value(message).map_err(crate::error::Error::Json)?;
                self.bot
                    .answer_callback_query(&callback.callback_id, Some(value), None)
                    .await
            }
            _ => Err(crate::error::Error::InvalidInput(
                "answer_callback_* only works on MessageCallback updates".into(),
            )),
        }
    }

    /// Отвечает на callback, изменяя только текст сообщения (клавиатура и вложения остаются).
    pub async fn answer_callback_edit_text(&self, new_text: &str) -> Result<bool> {
        match &self.update {
            Update::MessageCallback { callback, .. } => {
                let new_message = serde_json::json!({ "text": new_text });
                self.bot
                    .answer_callback_query(&callback.callback_id, Some(new_message), None)
                    .await
            }
            _ => Err(crate::error::Error::InvalidInput(
                "answer_callback_* only works on MessageCallback updates".into(),
            )),
        }
    }

    /// Отвечает на callback, изменяя только клавиатуру.
    pub async fn answer_callback_edit_keyboard(&self, keyboard: InlineKeyboard) -> Result<bool> {
        match &self.update {
            Update::MessageCallback { callback, .. } => {
                let new_keyboard = Attachment::inline_keyboard(keyboard);
                let attachments = vec![new_keyboard];
                let new_message = serde_json::json!({ "attachments": attachments });
                self.bot
                    .answer_callback_query(&callback.callback_id, Some(new_message), None)
                    .await
            }
            _ => Err(crate::error::Error::InvalidInput(
                "answer_callback_* only works on MessageCallback updates".into(),
            )),
        }
    }
}

// -----------------------------------------------------------------------------
// Контекст для старта бота
// -----------------------------------------------------------------------------

/// Контекст, передаваемый обработчикам, запускаемым при старте бота (до начала polling).
#[derive(Clone)]
pub struct StartContext {
    pub(crate) bot: Arc<MaxClient>,
}

impl StartContext {
    pub fn new(bot: Arc<MaxClient>) -> Self {
        Self { bot }
    }

    /// Возвращает ссылку на клиент бота.
    pub fn bot(&self) -> &MaxClient {
        &self.bot
    }
}

// -----------------------------------------------------------------------------
// Контекст для периодических задач
// -----------------------------------------------------------------------------

/// Контекст, передаваемый периодическим задачам.
#[derive(Clone)]
pub struct ScheduledTaskContext {
    pub(crate) bot: Arc<MaxClient>,
}

impl ScheduledTaskContext {
    pub fn new(bot: Arc<MaxClient>) -> Self {
        Self { bot }
    }

    /// Возвращает ссылку на клиент бота.
    pub fn bot(&self) -> &MaxClient {
        &self.bot
    }
}

// -----------------------------------------------------------------------------
// Типаж обработчика.
// -----------------------------------------------------------------------------

/// Тип для упакованной асинхронной функции-обработчика обновлений.
pub type HandlerFn = Arc<
    dyn Fn(Context) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send>> + Send + Sync,
>;

/// Тип для упакованной асинхронной функции-обработчика старта.
pub type StartHandlerFn = Arc<
    dyn Fn(StartContext) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send>> + Send + Sync,
>;

/// Тип для упакованной асинхронной функции-периодической задачи.
pub type ScheduledTaskFn = Arc<
    dyn Fn(ScheduledTaskContext) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send>>
        + Send
        + Sync,
>;

/// Преобразует переданную функцию-обработчик обновлений в `HandlerFn`.
fn make_handler<H, F>(handler: H) -> HandlerFn
where
    H: Fn(Context) -> F + Send + Sync + 'static,
    F: Future<Output = Result<()>> + Send + 'static,
{
    Arc::new(move |ctx| Box::pin(handler(ctx)))
}

/// Преобразует переданную функцию-обработчик старта в `StartHandlerFn`.
fn make_start_handler<H, F>(handler: H) -> StartHandlerFn
where
    H: Fn(StartContext) -> F + Send + Sync + 'static,
    F: Future<Output = Result<()>> + Send + 'static,
{
    Arc::new(move |ctx| Box::pin(handler(ctx)))
}

/// Преобразует переданную функцию-периодическую задачу в `ScheduledTaskFn`.
fn make_scheduled_task<H, F>(handler: H) -> ScheduledTaskFn
where
    H: Fn(ScheduledTaskContext) -> F + Send + Sync + 'static,
    F: Future<Output = Result<()>> + Send + 'static,
{
    Arc::new(move |ctx| Box::pin(handler(ctx)))
}

// -----------------------------------------------------------------------------
// Фильтр.
// -----------------------------------------------------------------------------

/// Определяет, какие обновления интересуют обработчик.
#[derive(Clone)]
pub enum Filter {
    /// Любые обновления.
    Any,
    /// Новые сообщения (`MessageCreated`).
    Message,
    /// Отредактированные сообщения (`MessageEdited`).
    EditedMessage,
    /// Нажатия на inline-кнопки (`MessageCallback`).
    Callback,
    /// Событие запуска бота (`BotStarted`).
    BotStarted,
    /// Бот добавлен в чат (`BotAdded`).
    BotAdded,
    /// Конкретная команда (например, `"/start"`).
    Command(String),
    /// Конкретная полезная нагрузка обратного вызова.
    CallbackPayload(String),
    Custom(Arc<dyn Fn(&Update) -> bool + Send + Sync>),
}

impl Filter {
    /// Проверяет, соответствует ли обновление данному фильтру.
    fn matches(&self, update: &Update) -> bool {
        match self {
            Filter::Any => true,
            Filter::Message => matches!(update, Update::MessageCreated { .. }),
            Filter::EditedMessage => matches!(update, Update::MessageEdited { .. }),
            Filter::Callback => matches!(update, Update::MessageCallback { .. }),
            Filter::BotStarted => matches!(update, Update::BotStarted { .. }),
            Filter::BotAdded => matches!(update, Update::BotAdded { .. }),
            Filter::Command(cmd) => {
                if let Update::MessageCreated { message, .. } = update {
                    message
                        .body
                        .as_ref()
                        .and_then(|b| b.text.as_deref())
                        .map(|t| t.starts_with(cmd))
                        .unwrap_or(false)
                } else {
                    false
                }
            }
            Filter::CallbackPayload(payload) => {
                if let Update::MessageCallback { callback, .. } = update {
                    callback.payload == *payload
                } else {
                    false
                }
            }
            Filter::Custom(pred) => pred(update),
        }
    }
}

// -----------------------------------------------------------------------------
// Диспетчер.
// -----------------------------------------------------------------------------

/// Диспетчер направляет входящие обновления зарегистрированным обработчикам.
///
/// Обработчики перебираются в порядке регистрации; выполняется первый подходящий.
pub struct Dispatcher {
    bot: Arc<MaxClient>,
    handlers: Vec<(Filter, HandlerFn)>,
    error_handler: Option<Arc<dyn Fn(crate::error::Error) + Send + Sync>>,
    poll_timeout: u32,
    poll_limit: u32,
    start_handlers: Vec<StartHandlerFn>,
    scheduled_tasks: Vec<(Duration, ScheduledTaskFn)>,
}

impl Dispatcher {
    /// Создаёт новый диспетчер для переданного клиента бота.
    pub fn new(bot: MaxClient) -> Self {
        Self {
            bot: Arc::new(bot),
            handlers: Vec::new(),
            error_handler: None,
            poll_timeout: 30,
            poll_limit: 100,
            start_handlers: Vec::new(),
            scheduled_tasks: Vec::new(),
        }
    }

    /// Устанавливает глобальный обработчик ошибок, вызываемый при ошибках в обработчиках.
    pub fn on_error<F>(mut self, f: F) -> Self
    where
        F: Fn(crate::error::Error) + Send + Sync + 'static,
    {
        self.error_handler = Some(Arc::new(f));
        self
    }

    /// Устанавливает задержку длительного опроса в секундах (по умолчанию 30, максимум 90).
    pub fn poll_timeout(mut self, secs: u32) -> Self {
        self.poll_timeout = secs;
        self
    }

    /// Устанавливает максимальное количество обновлений за один запрос (по умолчанию 100, максимум 100).
    pub fn poll_limit(mut self, limit: u32) -> Self {
        self.poll_limit = limit;
        self
    }

    // -------------------------------------------------------------------------
    // Регистрация обработчиков.
    // -------------------------------------------------------------------------

    /// Регистрирует обработчик для любых обновлений.
    pub fn on<H, F>(&mut self, handler: H) -> &mut Self
    where
        H: Fn(Context) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.handlers.push((Filter::Any, make_handler(handler)));
        self
    }

    /// Регистрирует обработчик для новых сообщений.
    pub fn on_message<H, F>(&mut self, handler: H) -> &mut Self
    where
        H: Fn(Context) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.handlers.push((Filter::Message, make_handler(handler)));
        self
    }

    /// Регистрирует обработчик для отредактированных сообщений.
    pub fn on_edited_message<H, F>(&mut self, handler: H) -> &mut Self
    where
        H: Fn(Context) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.handlers.push((Filter::EditedMessage, make_handler(handler)));
        self
    }

    /// Регистрирует обработчик для нажатий на inline-кнопки.
    pub fn on_callback<H, F>(&mut self, handler: H) -> &mut Self
    where
        H: Fn(Context) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.handlers.push((Filter::Callback, make_handler(handler)));
        self
    }

    /// Регистрирует обработчик для события запуска бота.
    pub fn on_bot_started<H, F>(&mut self, handler: H) -> &mut Self
    where
        H: Fn(Context) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.handlers.push((Filter::BotStarted, make_handler(handler)));
        self
    }

    /// Регистрирует обработчик для конкретной команды (например, `"/start"`).
    pub fn on_command<H, F>(&mut self, command: impl Into<String>, handler: H) -> &mut Self
    where
        H: Fn(Context) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.handlers
            .push((Filter::Command(command.into()), make_handler(handler)));
        self
    }

    /// Регистрирует обработчик для конкретного payload'а callback'а.
    pub fn on_callback_payload<H, F>(&mut self, payload: impl Into<String>, handler: H) -> &mut Self
    where
        H: Fn(Context) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.handlers.push((
            Filter::CallbackPayload(payload.into()),
            make_handler(handler),
        ));
        self
    }

    /// Регистрирует обработчик с пользовательским фильтром.
    pub fn on_filter<P, H, F>(&mut self, predicate: P, handler: H) -> &mut Self
    where
        P: Fn(&Update) -> bool + Send + Sync + 'static,
        H: Fn(Context) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.handlers
            .push((Filter::Custom(Arc::new(predicate)), make_handler(handler)));
        self
    }

    /// Регистрирует обработчик, который будет вызван один раз перед началом long polling.
    pub fn on_start<H, F>(&mut self, handler: H) -> &mut Self
    where
        H: Fn(StartContext) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.start_handlers.push(make_start_handler(handler));
        self
    }

    /// Регистрирует периодическую задачу, которая будет выполняться в фоне с указанным интервалом.
    pub fn task<H, F>(&mut self, interval: Duration, handler: H) -> &mut Self
    where
        H: Fn(ScheduledTaskContext) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.scheduled_tasks
            .push((interval, make_scheduled_task(handler)));
        self
    }

    // -------------------------------------------------------------------------
    // Внутренние методы диспетчеризации.
    // -------------------------------------------------------------------------

    /// Отправляет одно обновление первому подходящему обработчику.
    pub async fn dispatch(&self, update: Update) {
        for (filter, handler) in &self.handlers {
            if filter.matches(&update) {
                let ctx = Context::new(self.bot.clone(), update);
                if let Err(e) = handler(ctx).await {
                    self.handle_error(e);
                }
                break;
            }
        }
    }

    fn handle_error(&self, error: crate::error::Error) {
        if let Some(eh) = &self.error_handler {
            eh(error);
        } else {
            error!("Handler error: {}", error);
        }
    }

    /// Выполняет все зарегистрированные start-обработчики.
    async fn run_start_handlers(&self) {
        for handler in &self.start_handlers {
            let ctx = StartContext::new(self.bot.clone());
            if let Err(e) = handler(ctx).await {
                self.handle_error(e);
            }
        }
    }

    /// Запускает все периодические задачи в отдельных tokio-задачах.
    fn spawn_scheduled_tasks(&self) {
        for (interval, handler) in &self.scheduled_tasks {
            let interval = *interval;
            let handler = handler.clone();
            let bot = self.bot.clone();
            let error_handler = self.error_handler.clone();

            tokio::spawn(async move {
                loop {
                    tokio::time::sleep(interval).await;
                    let ctx = ScheduledTaskContext::new(bot.clone());
                    if let Err(e) = handler(ctx).await {
                        if let Some(eh) = &error_handler {
                            eh(e);
                        } else {
                            error!("Scheduled task error: {}", e);
                        }
                    }
                }
            });
        }
    }

    // -------------------------------------------------------------------------
    // Цикл длительного опроса.
    // -------------------------------------------------------------------------

    /// Запускает цикл длительного опроса. Работает бесконечно, пока процесс не будет завершён.
    pub async fn start_polling(self) {
        let me = match self.bot.get_me().await {
            Ok(me) => me,
            Err(e) => {
                error!("Failed to fetch bot info: {}", e);
                return;
            }
        };
        info!(
            "Bot @{} started (long polling)",
            me.user.username.as_deref().unwrap_or("unknown")
        );

        // Выполняем start-обработчики до начала основного цикла
        self.run_start_handlers().await;
        // Запускаем периодические задачи в фоне
        self.spawn_scheduled_tasks();

        let mut marker = None;
        loop {
            let params = crate::api::updates::GetUpdatesParams {
                marker,
                limit: Some(self.poll_limit),
                timeout: Some(self.poll_timeout),
                types: vec![], // Пустой список означает все типы
            };
            match self.bot.get_updates(params).await {
                Ok((updates, new_marker)) => {
                    marker = new_marker;
                    for update in updates {
                        self.dispatch(update).await;
                    }
                }
                Err(e) => {
                    warn!("Polling error: {} — retrying in 5s", e);
                    tokio::time::sleep(Duration::from_secs(5)).await;
                }
            }
        }
    }

    /// Отправляет сырое JSON-обновление (например, из webhook) в диспетчер.
    /// Сначала пытается десериализовать в типизированный `Update` и вызвать `dispatch`.
    pub async fn dispatch_raw(&self, raw: serde_json::Value) {
        match serde_json::from_value::<Update>(raw) {
            Ok(update) => self.dispatch(update).await,
            Err(e) => error!("Failed to parse update JSON: {}", e),
        }
    }
}