maxoxide 2.0.0

Async Rust library for the Max messenger Bot API
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
use std::{
    future::Future,
    ops::{BitAnd, BitOr, Not},
    sync::Arc,
    time::Duration,
};

use regex::Regex;
use tracing::{error, info, warn};

use crate::{
    bot::Bot,
    errors::{MaxError, Result},
    types::{AttachmentKind, Message, Update},
};

// ────────────────────────────────────────────────
// Context
// ────────────────────────────────────────────────

/// Context passed to every update handler.
///
/// Provides a reference to the `Bot` and the typed `Update` that triggered it.
#[derive(Clone)]
pub struct Context {
    pub bot: Bot,
    pub update: Update,
}

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

/// Context passed to `on_start` handlers.
#[derive(Clone)]
pub struct StartContext {
    pub bot: Bot,
}

impl StartContext {
    pub fn new(bot: Bot) -> Self {
        Self { bot }
    }
}

/// Context passed to scheduled task handlers.
#[derive(Clone)]
pub struct ScheduledTaskContext {
    pub bot: Bot,
}

impl ScheduledTaskContext {
    pub fn new(bot: Bot) -> Self {
        Self { bot }
    }
}

/// Context passed to raw update handlers.
#[derive(Clone)]
pub struct RawUpdateContext {
    pub bot: Bot,
    pub raw: serde_json::Value,
}

impl RawUpdateContext {
    pub fn new(bot: Bot, raw: serde_json::Value) -> Self {
        Self { bot, raw }
    }
}

// ────────────────────────────────────────────────
// Handler traits
// ────────────────────────────────────────────────

/// A boxed async typed update handler function.
pub type HandlerFn = Arc<
    dyn Fn(Context) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send>> + Send + Sync,
>;

type StartHandlerFn = Arc<
    dyn Fn(StartContext) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send>>
        + Send
        + Sync,
>;

type ScheduledTaskFn = Arc<
    dyn Fn(ScheduledTaskContext) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send>>
        + Send
        + Sync,
>;

type RawUpdateHandlerFn = Arc<
    dyn Fn(RawUpdateContext) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send>>
        + Send
        + Sync,
>;

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

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

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

fn make_raw_update_handler<H, F>(handler: H) -> RawUpdateHandlerFn
where
    H: Fn(RawUpdateContext) -> F + Send + Sync + 'static,
    F: Future<Output = Result<()>> + Send + 'static,
{
    Arc::new(move |ctx| Box::pin(handler(ctx)))
}

// ────────────────────────────────────────────────
// Dispatcher
// ────────────────────────────────────────────────

/// The dispatcher routes incoming `Update`s to registered handlers.
///
/// Handlers are matched in registration order. The first matching typed handler wins.
///
/// # Example
/// ```no_run
/// use maxoxide::{Bot, Dispatcher, Context, Result};
///
/// #[tokio::main]
/// async fn main() {
///     let bot = Bot::from_env();
///     let mut dp = Dispatcher::new(bot);
///
///     dp.on_message(|ctx: Context| async move {
///         if let maxoxide::types::Update::MessageCreated { message, .. } = &ctx.update {
///             ctx.bot
///                 .send_text_to_chat(message.chat_id(), message.text().unwrap_or(""))
///                 .await?;
///         }
///         Ok(())
///     });
///
///     dp.start_polling().await;
/// }
/// ```
pub struct Dispatcher {
    bot: Bot,
    handlers: Vec<(Filter, HandlerFn)>,
    start_handlers: Vec<StartHandlerFn>,
    raw_update_handlers: Vec<RawUpdateHandlerFn>,
    scheduled_tasks: Vec<(Duration, ScheduledTaskFn)>,
    error_handler: Option<Arc<dyn Fn(MaxError) + Send + Sync>>,
    poll_timeout: u32,
    poll_limit: u32,
}

/// Determines which updates a handler is interested in.
#[non_exhaustive]
#[derive(Clone)]
pub enum Filter {
    /// Fires on any update.
    Any,
    /// Fires only when a new message arrives.
    Message,
    /// Fires only when a message is edited.
    EditedMessage,
    /// Fires only when an inline button is pressed.
    Callback,
    /// Fires when a user starts the bot for the first time.
    BotStarted,
    /// Fires when the bot is added to a chat.
    BotAdded,
    /// Fires when a new message arrives whose text starts with this command.
    Command(String),
    /// Fires when the callback payload equals this string.
    CallbackPayload(String),
    /// Fires when an update carries a message in the given chat.
    Chat(i64),
    /// Fires when an update carries a message from the given sender.
    Sender(i64),
    /// Fires when an update carries a message whose text equals this string.
    TextExact(String),
    /// Fires when an update carries a message whose text contains this string.
    TextContains(String),
    /// Fires when an update carries a message whose text matches this regex.
    TextRegex(Regex),
    /// Fires when an update carries a message with any attachment.
    HasAttachment,
    /// Fires when an update carries a message with a specific attachment type.
    HasAttachmentType(AttachmentKind),
    /// Fires when an update carries a file attachment.
    HasFile,
    /// Fires when an update carries image, video, or audio attachment.
    HasMedia,
    /// Fires on `Update::Unknown`.
    UnknownUpdate,
    /// Logical AND for filters.
    And(Vec<Filter>),
    /// Logical OR for filters.
    Or(Vec<Filter>),
    /// Logical NOT for filters.
    Not(Box<Filter>),
    /// Custom predicate.
    Custom(Arc<dyn Fn(&Update) -> bool + Send + Sync>),
}

impl Filter {
    pub fn any() -> Self {
        Self::Any
    }

    pub fn message() -> Self {
        Self::Message
    }

    pub fn edited_message() -> Self {
        Self::EditedMessage
    }

    pub fn callback() -> Self {
        Self::Callback
    }

    pub fn bot_started() -> Self {
        Self::BotStarted
    }

    pub fn bot_added() -> Self {
        Self::BotAdded
    }

    pub fn command(command: impl Into<String>) -> Self {
        Self::Command(command.into())
    }

    pub fn callback_payload(payload: impl Into<String>) -> Self {
        Self::CallbackPayload(payload.into())
    }

    pub fn chat(chat_id: i64) -> Self {
        Self::Chat(chat_id)
    }

    pub fn sender(user_id: i64) -> Self {
        Self::Sender(user_id)
    }

    pub fn text_exact(text: impl Into<String>) -> Self {
        Self::TextExact(text.into())
    }

    pub fn text_contains(text: impl Into<String>) -> Self {
        Self::TextContains(text.into())
    }

    pub fn text_regex(pattern: &str) -> Result<Self> {
        Regex::new(pattern)
            .map(Self::TextRegex)
            .map_err(|e| MaxError::Api {
                code: 0,
                message: format!("Invalid regex filter: {e}"),
            })
    }

    pub fn has_attachment() -> Self {
        Self::HasAttachment
    }

    pub fn has_attachment_type(kind: AttachmentKind) -> Self {
        Self::HasAttachmentType(kind)
    }

    pub fn has_file() -> Self {
        Self::HasFile
    }

    pub fn has_media() -> Self {
        Self::HasMedia
    }

    pub fn unknown_update() -> Self {
        Self::UnknownUpdate
    }

    pub fn and(self, other: Filter) -> Self {
        match (self, other) {
            (Self::And(mut filters), Self::And(other_filters)) => {
                filters.extend(other_filters);
                Self::And(filters)
            }
            (Self::And(mut filters), other) => {
                filters.push(other);
                Self::And(filters)
            }
            (this, Self::And(mut filters)) => {
                let mut combined = vec![this];
                combined.append(&mut filters);
                Self::And(combined)
            }
            (this, other) => Self::And(vec![this, other]),
        }
    }

    pub fn or(self, other: Filter) -> Self {
        match (self, other) {
            (Self::Or(mut filters), Self::Or(other_filters)) => {
                filters.extend(other_filters);
                Self::Or(filters)
            }
            (Self::Or(mut filters), other) => {
                filters.push(other);
                Self::Or(filters)
            }
            (this, Self::Or(mut filters)) => {
                let mut combined = vec![this];
                combined.append(&mut filters);
                Self::Or(combined)
            }
            (this, other) => Self::Or(vec![this, other]),
        }
    }

    pub fn negate(self) -> Self {
        Self::Not(Box::new(self))
    }

    pub(crate) fn matches(&self, update: &Update) -> bool {
        match self {
            Self::Any => true,
            Self::Message => matches!(update, Update::MessageCreated { .. }),
            Self::EditedMessage => matches!(update, Update::MessageEdited { .. }),
            Self::Callback => matches!(update, Update::MessageCallback { .. }),
            Self::BotStarted => matches!(update, Update::BotStarted { .. }),
            Self::BotAdded => matches!(update, Update::BotAdded { .. }),
            Self::Command(cmd) => {
                if let Update::MessageCreated { message, .. } = update {
                    message
                        .text()
                        .map(|t| t.starts_with(cmd.as_str()))
                        .unwrap_or(false)
                } else {
                    false
                }
            }
            Self::CallbackPayload(payload) => {
                if let Update::MessageCallback { callback, .. } = update {
                    callback.payload.as_deref() == Some(payload.as_str())
                } else {
                    false
                }
            }
            Self::Chat(chat_id) => message_from_update(update)
                .map(|message| message.chat_id() == *chat_id)
                .unwrap_or(false),
            Self::Sender(user_id) => message_from_update(update)
                .and_then(Message::sender_user_id)
                .map(|sender_user_id| sender_user_id == *user_id)
                .unwrap_or(false),
            Self::TextExact(text) => message_from_update(update)
                .and_then(Message::text)
                .map(|message_text| message_text == text)
                .unwrap_or(false),
            Self::TextContains(text) => message_from_update(update)
                .and_then(Message::text)
                .map(|message_text| message_text.contains(text))
                .unwrap_or(false),
            Self::TextRegex(regex) => message_from_update(update)
                .and_then(Message::text)
                .map(|message_text| regex.is_match(message_text))
                .unwrap_or(false),
            Self::HasAttachment => message_from_update(update)
                .map(Message::has_attachments)
                .unwrap_or(false),
            Self::HasAttachmentType(kind) => message_has_attachment_kind(update, *kind),
            Self::HasFile => message_has_attachment_kind(update, AttachmentKind::File),
            Self::HasMedia => {
                message_has_attachment_kind(update, AttachmentKind::Image)
                    || message_has_attachment_kind(update, AttachmentKind::Video)
                    || message_has_attachment_kind(update, AttachmentKind::Audio)
            }
            Self::UnknownUpdate => matches!(update, Update::Unknown { .. }),
            Self::And(filters) => filters.iter().all(|filter| filter.matches(update)),
            Self::Or(filters) => filters.iter().any(|filter| filter.matches(update)),
            Self::Not(filter) => !filter.matches(update),
            Self::Custom(f) => f(update),
        }
    }
}

impl BitAnd for Filter {
    type Output = Filter;

    fn bitand(self, rhs: Self) -> Self::Output {
        self.and(rhs)
    }
}

impl BitOr for Filter {
    type Output = Filter;

    fn bitor(self, rhs: Self) -> Self::Output {
        self.or(rhs)
    }
}

impl Not for Filter {
    type Output = Filter;

    fn not(self) -> Self::Output {
        self.negate()
    }
}

fn message_from_update(update: &Update) -> Option<&Message> {
    match update {
        Update::MessageCreated { message, .. } | Update::MessageEdited { message, .. } => {
            Some(message)
        }
        Update::MessageCallback {
            message: Some(message),
            ..
        } => Some(message),
        _ => None,
    }
}

fn message_has_attachment_kind(update: &Update, kind: AttachmentKind) -> bool {
    message_from_update(update)
        .and_then(|message| message.body.attachments.as_ref())
        .map(|attachments| {
            attachments
                .iter()
                .any(|attachment| attachment.kind() == kind)
        })
        .unwrap_or(false)
}

impl Dispatcher {
    /// Create a new dispatcher for the given bot.
    pub fn new(bot: Bot) -> Self {
        Self {
            bot,
            handlers: Vec::new(),
            start_handlers: Vec::new(),
            raw_update_handlers: Vec::new(),
            scheduled_tasks: Vec::new(),
            error_handler: None,
            poll_timeout: 30,
            poll_limit: 100,
        }
    }

    /// Set a global error handler called when a handler returns an error.
    pub fn on_error<F>(mut self, f: F) -> Self
    where
        F: Fn(MaxError) + Send + Sync + 'static,
    {
        self.error_handler = Some(Arc::new(f));
        self
    }

    /// Set the long-poll timeout in seconds (default: 30, max: 90).
    pub fn poll_timeout(mut self, secs: u32) -> Self {
        self.poll_timeout = secs;
        self
    }

    /// Set the long-poll update limit (default: 100).
    pub fn poll_limit(mut self, limit: u32) -> Self {
        self.poll_limit = limit;
        self
    }

    // ────────────────────────────────────────────────
    // Handler registration
    // ────────────────────────────────────────────────

    /// Register a handler that fires on any typed update.
    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.on_update(Filter::Any, handler)
    }

    /// Register a handler with an explicit filter.
    pub fn on_update<H, F>(&mut self, filter: Filter, handler: H) -> &mut Self
    where
        H: Fn(Context) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.handlers.push((filter, make_handler(handler)));
        self
    }

    /// Register a handler for new messages.
    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.on_update(Filter::Message, handler)
    }

    /// Register a handler for edited messages.
    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.on_update(Filter::EditedMessage, handler)
    }

    /// Register a handler for inline button callbacks.
    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.on_update(Filter::Callback, handler)
    }

    /// Register a handler that fires when the bot is started by a user.
    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.on_update(Filter::BotStarted, handler)
    }

    /// Register a handler for a specific bot command (e.g. `"/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.on_update(Filter::Command(command.into()), handler)
    }

    /// Register a handler for a specific callback payload value.
    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.on_update(Filter::CallbackPayload(payload.into()), handler)
    }

    /// Register a handler with a custom filter predicate.
    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.on_update(Filter::Custom(Arc::new(predicate)), handler)
    }

    /// Register a handler that runs once before polling starts.
    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
    }

    /// Register a periodic task that starts with polling.
    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
    }

    /// Register a handler that receives raw JSON for every incoming update.
    pub fn on_raw_update<H, F>(&mut self, handler: H) -> &mut Self
    where
        H: Fn(RawUpdateContext) -> F + Send + Sync + 'static,
        F: Future<Output = Result<()>> + Send + 'static,
    {
        self.raw_update_handlers
            .push(make_raw_update_handler(handler));
        self
    }

    // ────────────────────────────────────────────────
    // Dispatching
    // ────────────────────────────────────────────────

    /// Dispatch a raw JSON update through raw handlers and typed handlers.
    pub async fn dispatch_raw(&self, raw: serde_json::Value) {
        for handler in &self.raw_update_handlers {
            let ctx = RawUpdateContext::new(self.bot.clone(), raw.clone());
            if let Err(e) = handler(ctx).await {
                self.handle_error(e);
            }
        }

        match serde_json::from_value::<Update>(raw) {
            Ok(update) => self.dispatch(update).await,
            Err(e) => warn!("Failed to parse update JSON: {e}"),
        }
    }

    /// Dispatch a single typed update to the first matching handler.
    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.clone());
                if let Err(e) = handler(ctx).await {
                    self.handle_error(e);
                }
                break;
            }
        }
    }

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

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

    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(error_handler) = &error_handler {
                            error_handler(e);
                        } else {
                            error!("Scheduled task error: {e}");
                        }
                    }
                }
            });
        }
    }

    // ────────────────────────────────────────────────
    // Long polling
    // ────────────────────────────────────────────────

    /// Start the long-polling loop. This runs until the process is killed.
    ///
    /// On startup it logs the bot's username so you know it's alive.
    pub async fn start_polling(self) {
        let me = match self.bot.get_me().await {
            Ok(u) => u,
            Err(e) => {
                error!("Failed to fetch bot info: {e}");
                return;
            }
        };
        info!(
            "Bot @{} started (long polling)",
            me.username.as_deref().unwrap_or("unknown")
        );

        self.run_start_handlers().await;
        self.spawn_scheduled_tasks();

        let timeout = self.poll_timeout;
        let limit = self.poll_limit;
        let bot = self.bot.clone();
        let mut marker: Option<i64> = None;

        loop {
            match bot
                .get_updates_raw(marker, Some(timeout), Some(limit))
                .await
            {
                Ok(resp) => {
                    if let Some(m) = resp.marker {
                        marker = Some(m);
                    }
                    for update in resp.updates {
                        self.dispatch_raw(update).await;
                    }
                }
                Err(e) => {
                    warn!("Polling error: {e} - retrying in 5 s");
                    tokio::time::sleep(Duration::from_secs(5)).await;
                }
            }
        }
    }
}