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
use crate::{
    contexts::fields::Message,
    errors,
    internal::Sealed,
    types::{
        chat,
        parameters::{ChatId, ImplicitChatId},
    },
    Bot,
};
use futures::future::BoxFuture;
use std::{convert::Infallible, time::Duration};
use tokio::time::sleep;

const INTERVAL: Duration = Duration::from_secs(5);

async fn send_chat_action_in_loop(
    bot: Bot,
    chat_id: ChatId,
    action: chat::Action,
) -> Result<Infallible, errors::MethodCall> {
    loop {
        let delay = sleep(INTERVAL);
        bot.send_chat_action(chat_id.clone(), action).call().await?;
        delay.await;
    }
}

/// An utility trait for [`Bot`] with a method to send a chat action in a loop.
///
/// [`Bot`]: crate::Bot
#[allow(clippy::module_name_repetitions)]
pub trait ChatActionLoopBotExt: Sealed {
    /// Sends a chat action in an infinite loop, returning only if failed
    /// to send the action.
    ///
    /// This utility is supposed to be [`select!`]ed with another future.
    /// As soon as the other future completes, this future is dropped
    /// and the chat action is no longer sent.
    ///
    /// [`select!`]: tokio::select
    fn send_chat_action_in_loop(
        &self,
        chat_id: impl ImplicitChatId,
        action: chat::Action,
    ) -> BoxFuture<'_, Result<Infallible, errors::MethodCall>>;
}

impl ChatActionLoopBotExt for Bot {
    fn send_chat_action_in_loop(
        &self,
        chat_id: impl ImplicitChatId,
        action: chat::Action,
    ) -> BoxFuture<'_, Result<Infallible, errors::MethodCall>> {
        let chat_id: ChatId = chat_id.into();
        Box::pin(send_chat_action_in_loop(self.clone(), chat_id, action))
    }
}

/// An utility trait for contexts with a method to send a chat action in a loop.
pub trait ChatActionLoop: Message {
    /// Sends a chat action in an infinite loop, returning only if failed
    /// to send the action.
    ///
    /// This utility is supposed to be [`select!`]ed with another future.
    /// As soon as the other future completes, this future is dropped
    /// and the chat action is no longer sent.
    ///
    /// [`select!`]: tokio::select
    fn send_chat_action_in_loop(
        &self,
        action: chat::Action,
    ) -> BoxFuture<Result<Infallible, errors::MethodCall>> {
        Box::pin(self.bot().send_chat_action_in_loop(self.chat().id, action))
    }
}

impl<T: Message> ChatActionLoop for T {}