Skip to content

Commit 48377ac

Browse files
authored
Merge pull request eternnoir#1947 from alex75311/edit_antiflood_method
redesigned the antiflood method for guaranteed message delivery
2 parents ea3c159 + 14294d1 commit 48377ac

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
@@ -590,7 +590,7 @@ def webhook_google_functions(bot, request):
590590
return 'Bot ON'
591591

592592

593-
def antiflood(function: Callable, *args, **kwargs):
593+
def antiflood(function: Callable, *args, number_retries=5, **kwargs):
594594
"""
595595
Use this function inside loops in order to avoid getting TooManyRequests error.
596596
Example:
@@ -604,6 +604,9 @@ def antiflood(function: Callable, *args, **kwargs):
604604
:param function: The function to call
605605
:type function: :obj:`Callable`
606606
607+
:param number_retries: Number of retries to send
608+
:type function: :obj:int
609+
607610
:param args: The arguments to pass to the function
608611
:type args: :obj:`tuple`
609612
@@ -615,14 +618,16 @@ def antiflood(function: Callable, *args, **kwargs):
615618
from telebot.apihelper import ApiTelegramException
616619
from time import sleep
617620

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

627632

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

0 commit comments

Comments
 (0)