11
22import threading
3- import time
43
54from telebot import apihelper
65from telebot import logger
98
109class 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