From 558b37b1c3b0beba02e15d24db0ed6b3bf6a91f4 Mon Sep 17 00:00:00 2001 From: Andrea Barbagallo Date: Wed, 3 Nov 2021 15:30:10 +0100 Subject: [PATCH] New antiflood function --- telebot/util.py | 22 ++++++++++++++++++++++ tests/test_telebot.py | 7 +++++++ 2 files changed, 29 insertions(+) diff --git a/telebot/util.py b/telebot/util.py index f871f09..b33aaa1 100644 --- a/telebot/util.py +++ b/telebot/util.py @@ -455,3 +455,25 @@ def webhook_google_functions(bot, request): return 'Bot FAIL', 400 else: return 'Bot ON' + +def antiflood(function, *args, **kwargs): + """ + Use this function inside loops in order to avoid getting TooManyRequests error. + Example: + + from telebot.util import antiflood + for chat_id in chat_id_list: + msg = antiflood(bot.send_message, chat_id, text) + + You want get the + """ + from telebot.apihelper import ApiTelegramException + from time import sleep + try: + msg = function(*args, **kwargs) + except ApiTelegramException as ex: + if ex.error_code == 429: + sleep(ex.result_json['parameters']['retry_after']) + msg = function(*args, **kwargs) + finally: + return msg \ No newline at end of file diff --git a/tests/test_telebot.py b/tests/test_telebot.py index 6e8f341..2426b0f 100644 --- a/tests/test_telebot.py +++ b/tests/test_telebot.py @@ -455,6 +455,13 @@ class TestTeleBot: new_msg = tb.edit_message_reply_markup(chat_id=CHAT_ID, message_id=ret_msg.message_id, reply_markup=markup) assert new_msg.message_id + def test_antiflood(self): + text = "Flooding" + tb = telebot.TeleBot(TOKEN) + for _ in range(0,100): + util.antiflood(tb.send_message, CHAT_ID, text) + assert _ + @staticmethod def create_text_message(text): params = {'text': text}