Skip to content

Commit 14294d1

Browse files
author
Alexey Isaev
committed
redesigned the antiflood method for guaranteed message delivery
1 parent 5d9a76b commit 14294d1

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

telebot/util.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -588,7 +588,7 @@ def webhook_google_functions(bot, request):
588588
return 'Bot ON'
589589

590590

591-
def antiflood(function: Callable, *args, **kwargs):
591+
def antiflood(function: Callable, *args, number_retries=5, **kwargs):
592592
"""
593593
Use this function inside loops in order to avoid getting TooManyRequests error.
594594
Example:
@@ -602,6 +602,9 @@ def antiflood(function: Callable, *args, **kwargs):
602602
:param function: The function to call
603603
:type function: :obj:`Callable`
604604
605+
:param number_retries: Number of retries to send
606+
:type function: :obj:int
607+
605608
:param args: The arguments to pass to the function
606609
:type args: :obj:`tuple`
607610
@@ -613,14 +616,16 @@ def antiflood(function: Callable, *args, **kwargs):
613616
from telebot.apihelper import ApiTelegramException
614617
from time import sleep
615618

616-
try:
617-
return function(*args, **kwargs)
618-
except ApiTelegramException as ex:
619-
if ex.error_code == 429:
620-
sleep(ex.result_json['parameters']['retry_after'])
619+
for _ in range(number_retries - 1):
620+
try:
621621
return function(*args, **kwargs)
622-
else:
623-
raise
622+
except ApiTelegramException as ex:
623+
if ex.error_code == 429:
624+
sleep(ex.result_json['parameters']['retry_after'])
625+
else:
626+
raise
627+
else:
628+
return function(*args, **kwargs)
624629

625630

626631
def parse_web_app_data(token: str, raw_init_data: str):

0 commit comments

Comments
 (0)