1010import logging
1111
1212logger = logging .getLogger ('TeleBot' )
13- formatter = logging .Formatter ('%(asctime)s (%(filename)s:%(lineno)d) %(levelname)s - %(name)s: "%(message)s"' )
13+ formatter = logging .Formatter (
14+ '%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"'
15+ )
1416
1517console_output_handler = logging .StreamHandler (sys .stderr )
1618console_output_handler .setFormatter (formatter )
@@ -42,20 +44,17 @@ class TeleBot:
4244 getUpdates
4345 """
4446
45- def __init__ (self , token , create_threads = True , num_threads = 4 ):
47+ def __init__ (self , token ):
4648 """
4749 :param token: bot API token
48- :param create_threads: Create thread for message handler
49- :param num_threads: Number of worker in thread pool.
5050 :return: Telebot object.
5151 """
5252 self .token = token
5353 self .update_listener = []
54- self . polling_thread = None
54+
5555 self .__stop_polling = threading .Event ()
5656 self .last_update_id = 0
57- self .num_threads = num_threads
58- self .__create_threads = create_threads
57+ self .exc_info = None
5958
6059 self .message_subscribers_messages = []
6160 self .message_subscribers_callbacks = []
@@ -65,8 +64,7 @@ def __init__(self, token, create_threads=True, num_threads=4):
6564 self .message_subscribers_next_step = {}
6665
6766 self .message_handlers = []
68- if self .__create_threads :
69- self .worker_pool = util .ThreadPool (num_threads )
67+ self .worker_pool = util .ThreadPool ()
7068
7169 def set_webhook (self , url = None , certificate = None ):
7270 return apihelper .set_webhook (self .token , url , certificate )
@@ -88,12 +86,13 @@ def get_updates(self, offset=None, limit=None, timeout=20):
8886 ret .append (types .Update .de_json (ju ))
8987 return ret
9088
91- def get_update (self , timeout = 20 ):
89+ def __retrieve_updates (self , timeout = 20 ):
9290 """
9391 Retrieves any updates from the Telegram API.
9492 Registered listeners and applicable message handlers will be notified when a new message arrives.
9593 :raises ApiException when a call has failed.
9694 """
95+ raise apihelper .ApiException ("Test2" , None , None )
9796 updates = self .get_updates (offset = (self .last_update_id + 1 ), timeout = timeout )
9897 new_messages = []
9998 for update in updates :
@@ -112,57 +111,52 @@ def process_new_messages(self, new_messages):
112111
113112 def __notify_update (self , new_messages ):
114113 for listener in self .update_listener :
115- if self .__create_threads :
116- self .worker_pool .put (listener , new_messages )
117- else :
118- listener (new_messages )
114+ self .worker_pool .put (listener , new_messages )
119115
120- def polling (self , none_stop = False , interval = 0 , block = True , timeout = 20 ):
116+ def polling (self , none_stop = False , interval = 0 , timeout = 20 ):
121117 """
122- This function creates a new Thread that calls an internal __polling function.
118+ This function creates a new Thread that calls an internal __retrieve_updates function.
123119 This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly.
124120
125- Do not call this function more than once!
121+ Warning: Do not call this function more than once!
126122
127123 Always get updates.
128- :param none_stop: Do not stop polling when Exception occur .
124+ :param none_stop: Do not stop polling when an ApiException occurs .
129125 :param timeout: Timeout in seconds for long polling.
130126 :return:
131127 """
132- self .__stop_polling .set ()
133- if self .polling_thread :
134- self .polling_thread .join () # wait thread stop.
135- self .__stop_polling .clear ()
136- self .polling_thread = threading .Thread (target = self .__polling , args = ([none_stop , interval , timeout ]))
137- self .polling_thread .daemon = True
138- self .polling_thread .start ()
139-
140- if block :
141- while self .polling_thread .is_alive :
142- try :
143- time .sleep (.1 )
144- except KeyboardInterrupt :
145- logger .info ("Received KeyboardInterrupt. Stopping." )
146- self .stop_polling ()
147- self .polling_thread .join ()
148- break
149-
150- def __polling (self , none_stop , interval , timeout ):
151128 logger .info ('Started polling.' )
152129
153130 error_interval = .25
131+
132+ polling_thread = util .WorkerThread (name = "PollingThread" )
133+ or_event = util .OrEvent (
134+ polling_thread .done_event ,
135+ polling_thread .exception_event ,
136+ self .worker_pool .exception_event
137+ )
138+
154139 while not self .__stop_polling .wait (interval ):
140+ or_event .clear ()
155141 try :
156- self .get_update (timeout )
142+ polling_thread .put (self .__retrieve_updates , timeout )
143+ or_event .wait ()
144+
145+ polling_thread .raise_exceptions ()
146+ self .worker_pool .raise_exceptions ()
147+
157148 error_interval = .25
158149 except apihelper .ApiException as e :
150+ logger .error (e )
159151 if not none_stop :
160152 self .__stop_polling .set ()
161153 logger .info ("Exception occurred. Stopping." )
162154 else :
155+ polling_thread .clear_exceptions ()
156+ self .worker_pool .clear_exceptions ()
157+ logger .info ("Waiting for {0} seconds until retry" .format (error_interval ))
163158 time .sleep (error_interval )
164159 error_interval *= 2
165- logger .error (e )
166160
167161 logger .info ('Stopped polling.' )
168162
@@ -459,10 +453,7 @@ def _notify_command_handlers(self, new_messages):
459453 for message in new_messages :
460454 for message_handler in self .message_handlers :
461455 if self ._test_message_handler (message_handler , message ):
462- if self .__create_threads :
463- self .worker_pool .put (message_handler ['function' ], message )
464- else :
465- message_handler ['function' ](message )
456+ self .worker_pool .put (message_handler ['function' ], message )
466457 break
467458
468459
0 commit comments