From 85341d70648bc7130c1d04a56fc38aef7f3081ba Mon Sep 17 00:00:00 2001 From: Davte Date: Thu, 28 Nov 2019 18:08:58 +0100 Subject: [PATCH] Placeholder system Send a placeholder message or chat_action if the request takes some time. --- davtelepot/__init__.py | 2 +- davtelepot/bot.py | 54 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/davtelepot/__init__.py b/davtelepot/__init__.py index e1e435e..912dd31 100644 --- a/davtelepot/__init__.py +++ b/davtelepot/__init__.py @@ -14,7 +14,7 @@ __author__ = "Davide Testa" __email__ = "davide@davte.it" __credits__ = ["Marco Origlia", "Nick Lee @Nickoala"] __license__ = "GNU General Public License v3.0" -__version__ = "2.3.4" +__version__ = "2.3.5" __maintainer__ = "Davide Testa" __contact__ = "t.me/davte" diff --git a/davtelepot/bot.py b/davtelepot/bot.py index 4012843..203bcd0 100644 --- a/davtelepot/bot.py +++ b/davtelepot/bot.py @@ -214,6 +214,7 @@ class Bot(TelegramBot, ObjectWithDatabase, MultiLanguageObject): self.recent_users = OrderedDict() self._log_file_name = None self._errors_file_name = None + self.placeholder_requests = dict() return @property @@ -2026,6 +2027,59 @@ class Bot(TelegramBot, ObjectWithDatabase, MultiLanguageObject): del self.individual_location_handlers[identifier] return + def set_placeholder(self, chat_id, + text=None, sent_message=None, timeout=1): + """Set a placeholder chat action or text message. + + If it takes the bot more than `timeout` to answer, send a placeholder + message or a `is typing` chat action. + `timeout` may be expressed in seconds (int) or datetime.timedelta + + This method returns a `request_id`. When the calling function has + performed its task, it must set to 1 the value of + `self.placeholder_requests[request_id]`. + If this value is still 0 at `timeout`, the placeholder is sent. + Otherwise, no action is performed. + """ + request_id = len(self.placeholder_requests) + self.placeholder_requests[request_id] = 0 + asyncio.ensure_future( + self.placeholder_effector( + request_id=request_id, + timeout=timeout, + chat_id=chat_id, + sent_message=sent_message, + text=text + ) + ) + return request_id + + async def placeholder_effector(self, request_id, timeout, chat_id, + sent_message=None, text=None): + """Send a placeholder chat action or text message if needed. + + If it takes the bot more than `timeout` to answer, send a placeholder + message or a `is typing` chat action. + `timeout` may be expressed in seconds (int) or datetime.timedelta + """ + if type(timeout) is datetime.timedelta: + timeout = timeout.total_seconds() + print(timeout) + await asyncio.sleep(timeout) + print("sleep ends") + if not self.placeholder_requests[request_id]: + if sent_message and text: + await self.edit_message_text( + update=sent_message, + text=text, + ) + else: + await self.sendChatAction( + chat_id=chat_id, + action='typing' + ) + return + async def webhook_feeder(self, request): """Handle incoming HTTP `request`s.