Skip to content

Commit 7aaef67

Browse files
committed
Added exception handling mechanism
Added update generator
1 parent 547c186 commit 7aaef67

3 files changed

Lines changed: 52 additions & 41 deletions

File tree

‎telebot/__init__.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
# -*- coding: utf-8 -*-
22
from telebot import types
3+
from telebot import util
4+
from telebot import listeners
5+
from telebot import apihelper
36
from telebot.util import logger
4-
from telebot.telebot_class import *
7+
from telebot.telebot_class import TeleBot
58

69
"""
710
Module : telebot

‎telebot/listeners.py‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ def __call__(self, update):
2929
return
3030

3131
if self.test_message(update.message):
32-
self.handler(update.message)
32+
r = self.handler(update.message)
33+
return r if r is not None else True
34+
return True
3335

3436

3537
class NextStepHandler:
@@ -43,7 +45,9 @@ def __call__(self, update):
4345
return
4446

4547
if update.message.chat.id == self.chat_id:
46-
self.handler(update.message)
48+
r = self.handler(update.message)
49+
return r if r is not None else False
50+
return False
4751

4852

4953
class InlineHandler:
@@ -57,7 +61,9 @@ def __call__(self, update):
5761
return
5862

5963
if self.func(update.inline_query):
60-
self.handler(update.inline_query)
64+
r = self.handler(update.inline_query)
65+
return r if r is not None else True
66+
return True
6167

6268

6369
class ChosenInlineResultHandler:
@@ -71,7 +77,9 @@ def __call__(self, update):
7177
return
7278

7379
if self.func(update.chosen_inline_result):
74-
self.handler(update.chosen_inline_result)
80+
r= self.handler(update.chosen_inline_result)
81+
return r if r is not None else True
82+
return True
7583

7684

7785
class CallbackQueryHandler:
@@ -85,4 +93,6 @@ def __call__(self, update):
8593
return
8694

8795
if self.func(update.callback_query):
88-
self.handler(update.callback_query)
96+
r = self.handler(update.callback_query)
97+
return r if r is not None else True
98+
return True

‎telebot/telebot_class.py‎

Lines changed: 33 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11

22
import threading
3-
import time
43

54
from telebot import apihelper
65
from telebot import logger
@@ -9,7 +8,7 @@
98

109
class TeleBot(apihelper.TelegramApiInterface):
1110

12-
def __init__(self, token, skip_pending=False, request_executor=None):
11+
def __init__(self, token, request_executor=None):
1312
"""
1413
:param token: bot API token
1514
:return: Telebot object.
@@ -21,78 +20,77 @@ def __init__(self, token, skip_pending=False, request_executor=None):
2120

2221
self.token = token
2322
self.update_listeners = []
24-
self.skip_pending = skip_pending
2523

2624
self.__stop_polling = threading.Event()
2725
self.last_update_id = 0
2826

27+
def __yield_updates(self, timeout=20):
28+
updates = self.get_updates(offset=self.last_update_id, timeout=timeout)
29+
while updates:
30+
self.last_update_id = max(updates, key=lambda u: u.update_id)
31+
updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
32+
yield (x for x in updates)
33+
2934
def __skip_updates(self):
3035
"""
3136
Get and discard all pending updates before first poll of the bot
3237
:return: total updates skipped
3338
"""
34-
total = 0
35-
updates = self.get_updates(offset=self.last_update_id)
36-
while updates:
37-
total += len(updates)
38-
for update in updates:
39-
if update.update_id > self.last_update_id:
40-
self.last_update_id = update.update_id
41-
updates = self.get_updates(offset=self.last_update_id + 1)
42-
return total
39+
return len(list(self.__yield_updates(timeout=1)))
4340

4441
def __retrieve_updates(self, timeout=20):
4542
"""
4643
Retrieves any updates from the Telegram API.
4744
Registered listeners and applicable message handlers will be notified when a new message arrives.
4845
:raises ApiException when a call has failed.
4946
"""
50-
updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
51-
self.process_new_updates(updates)
47+
self.process_new_updates(self.__yield_updates(timeout=timeout))
48+
49+
@staticmethod
50+
def __call_listener(listener, update):
51+
r = listener(update)
52+
# Assume the listener wants to stay in the list if it does not return anything
53+
return r if r is not None else True
5254

5355
def process_new_updates(self, updates):
5456
logger.debug('Received {0} new updates'.format(len(updates)))
5557
for update in updates:
56-
for listener in self.update_listeners:
57-
listener(update)
58+
self.update_listeners = filter(lambda l: self.__call_listener(l, update), self.update_listeners)
59+
60+
@staticmethod
61+
def __default_exception_handler(bot, exception):
62+
logger.error(exception)
63+
logger.info("Exception occurred. Stopping.")
64+
bot.stop_polling()
5865

59-
def polling(self, continue_on_exception=False, interval=0, timeout=20):
66+
def polling(self, skip_pending=False, timeout=20, exception_handler=lambda e: True):
6067
"""
6168
This function creates a new Thread that calls an internal __retrieve_updates function.
6269
This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly.
6370
6471
Warning: Do not call this function more than once!
6572
6673
Always get updates.
67-
:param interval:
68-
:param continue_on_exception: Do not stop polling when an ApiException occurs.
74+
:param exception_handler:
75+
:param skip_pending: Retrieve and discard pending updates
6976
:param timeout: Timeout in seconds for long polling.
7077
:return:
7178
"""
7279
logger.info('Started polling.')
7380
self.__stop_polling.clear()
74-
error_interval = .25
7581

76-
if self.skip_pending:
77-
logger.debug('Skipped {0} pending messages'.format(self.__skip_updates()))
82+
if skip_pending:
83+
logger.info('Skipped {0} pending messages'.format(self.__skip_updates()))
7884

79-
while not self.__stop_polling.wait(interval):
85+
while not self.__stop_polling.wait(0):
8086
try:
8187
self.__retrieve_updates(timeout)
82-
error_interval = .25
8388
except apihelper.ApiException as e:
84-
logger.error(e)
85-
if not continue_on_exception:
86-
self.__stop_polling.set()
87-
logger.info("Exception occurred. Stopping.")
88-
else:
89-
logger.info("Waiting for {0} seconds until retry".format(error_interval))
90-
time.sleep(error_interval)
91-
error_interval *= 2
92-
except KeyboardInterrupt:
93-
logger.info("KeyboardInterrupt received.")
89+
exception_handler(self, e)
90+
except KeyboardInterrupt as e:
91+
logger.info("KeyboardInterrupt")
9492
self.__stop_polling.set()
95-
break
93+
raise e
9694

9795
logger.info('Stopped polling.')
9896

0 commit comments

Comments
 (0)