Skip to content

Commit 43ad415

Browse files
committed
Get and discard all pending updates sent before the first poll of the bot
1 parent a17b301 commit 43ad415

1 file changed

Lines changed: 20 additions & 1 deletion

File tree

‎telebot/__init__.py‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,14 @@ class TeleBot:
4444
getUpdates
4545
"""
4646

47-
def __init__(self, token, threaded=True):
47+
def __init__(self, token, threaded=True, skip_pending=False):
4848
"""
4949
:param token: bot API token
5050
:return: Telebot object.
5151
"""
5252
self.token = token
5353
self.update_listener = []
54+
self.skip_pending = skip_pending
5455

5556
self.__stop_polling = threading.Event()
5657
self.last_update_id = 0
@@ -90,12 +91,30 @@ def get_updates(self, offset=None, limit=None, timeout=20):
9091
ret.append(types.Update.de_json(ju))
9192
return ret
9293

94+
def __skip_updates(self):
95+
"""
96+
Get and discard all pending updates before first poll of the bot
97+
:return: total updates skipped
98+
"""
99+
total = 0
100+
updates = self.get_updates(offset=self.last_update_id, timeout=1)
101+
while updates:
102+
total += len(updates)
103+
for update in updates:
104+
if update.update_id > self.last_update_id:
105+
self.last_update_id = update.update_id
106+
updates = self.get_updates(offset=self.last_update_id+1, timeout=1)
107+
return total
108+
93109
def __retrieve_updates(self, timeout=20):
94110
"""
95111
Retrieves any updates from the Telegram API.
96112
Registered listeners and applicable message handlers will be notified when a new message arrives.
97113
:raises ApiException when a call has failed.
98114
"""
115+
if self.skip_pending:
116+
logger.debug('Skipped {0} pending messages'.format(self.__skip_updates()))
117+
self.skip_pending = False
99118
updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
100119
new_messages = []
101120
for update in updates:

0 commit comments

Comments
 (0)