1-
2- import threading
3- import six
4- import sys
5- import time
6- import types
7-
1+ # -*- coding: utf-8 -*-
82import telebot .listeners as listeners
93from telebot .util import logger
10- from telebot .apihelper import TelegramApiInterface , DefaultRequestExecutor , ApiException
4+ from telebot .apihelper import TelegramApiInterface , DefaultRequestExecutor
115
126
13- def stopping_exception_handler (bot , exception ):
14- logger .error (exception )
15- logger .info ("Exception occurred. Stopping." )
16- bot .stop_polling ()
7+ def stopping_exception_handler (_ ):
8+ logger .exception ("Exception occurred. Stopping." )
9+ return False
1710
1811
19- def continuing_exception_handler (_ , exception ):
20- logger .error (exception )
21- logger .info ("Exception occurred, waiting 5 seconds." )
22- time .sleep (5 )
12+ def continuing_exception_handler (_ ):
13+ logger .exception ("Exception occurred." )
14+ return True
2315
2416
2517class TeleBot (TelegramApiInterface ):
2618
27- def __init__ (self , token , request_executor = None ):
19+ def __init__ (self , token , exception_handler = stopping_exception_handler , request_executor = None ):
2820 """
2921 :param token: bot API token
3022 :return: Telebot object.
3123 """
3224 request_executor = request_executor if request_executor is not None else DefaultRequestExecutor ()
3325 TelegramApiInterface .__init__ (self , token , request_executor )
3426
27+ self .exception_handler = exception_handler
3528 self .token = token
36- self .update_listeners = []
29+ self .event_bus = listeners . EventBus ()
3730
38- self .__stop_polling = threading . Event ()
31+ self .__stop_polling = False
3932 self .last_update_id = 0
4033
4134 def __yield_updates (self , timeout = 20 ):
4235 updates = self .get_updates (offset = self .last_update_id , timeout = timeout )
4336 while updates :
4437 for u in updates :
4538 yield u
46- self .last_update_id = max (updates , key = lambda u : u .update_id ).update_id
39+ self .last_update_id = max (updates , key = lambda update : update .update_id ).update_id
4740 updates = self .get_updates (offset = (self .last_update_id + 1 ), timeout = timeout )
4841
4942 def skip_updates (self , timeout = 1 ):
@@ -62,48 +55,55 @@ def retrieve_updates(self, timeout=20):
6255 """
6356 self .process_new_updates (self .__yield_updates (timeout = timeout ))
6457
58+ def __process_update (self , update ):
59+ logger .debug ("Processing update {0}" .format (update ))
60+
61+ self .event_bus .dispatch ('on_update' , update )
62+
63+ if update .message is not None :
64+ self .event_bus .dispatch ('on_message' , update .message )
65+ elif update .edited_message is not None :
66+ self .event_bus .dispatch ('on_edited_message' , update .edited_message )
67+ elif update .inline_query is not None :
68+ self .event_bus .dispatch ('on_inline_query' , update .inline_query )
69+ elif update .chosen_inline_result is not None :
70+ self .event_bus .dispatch ('on_chosen_inline_result' , update .chosen_inline_result )
71+ elif update .callback_query is not None :
72+ self .event_bus .dispatch ('on_callback_query' , update .callback_query )
73+
6574 def process_new_updates (self , updates ):
6675 for update in updates :
67- logger .debug ('Received new updates: {0}' .format (update ))
68- for listener in self .update_listeners :
69- listener (update )
70-
71- def polling (self , skip_pending = False , timeout = 20 , exception_handler = stopping_exception_handler ):
76+ try :
77+ self .__process_update (update )
78+ except Exception as e :
79+ # If the exception handler returns False, drop all updates
80+ if not self .exception_handler (e ):
81+ self .stop_polling ()
82+ break
83+
84+ def polling (self , skip_pending = False , timeout = 20 ):
7285 """
73- This function creates a new Thread that calls an internal __retrieve_updates function.
74- This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly.
86+ This function retrieves Updates and dispatches events.
7587
7688 Warning: Do not call this function more than once!
7789
78- Always get updates.
79- :param exception_handler:
80- :param skip_pending: Retrieve and discard pending updates
90+ :param skip_pending: Retrieve and discard pending updates (e.g. do not dispatch events)
8191 :param timeout: Timeout in seconds for long polling.
8292 :return:
8393 """
8494 logger .info ('Started polling.' )
85- self .__stop_polling . clear ()
95+ self .__stop_polling = False
8696
8797 if skip_pending :
88- logger .info ('Skipped {0} pending messages ' .format (len (self .skip_updates ())))
98+ logger .info ('Skipped {0} pending updates ' .format (len (self .skip_updates ())))
8999
90- while not self .__stop_polling .wait (0 ):
91- try :
92- self .retrieve_updates (timeout )
93- except ApiException as e :
94- exception_handler (self , e )
95- except KeyboardInterrupt :
96- logger .info ("KeyboardInterrupt" )
97- self .__stop_polling .set ()
98- six .reraise (* sys .exc_info ())
100+ while not self .__stop_polling :
101+ self .retrieve_updates (timeout )
99102
100103 logger .info ('Stopped polling.' )
101104
102105 def stop_polling (self ):
103- self .__stop_polling .set ()
104-
105- def add_update_listener (self , listener ):
106- self .update_listeners .append (listener )
106+ self .__stop_polling = True
107107
108108 def remove_webhook (self ):
109109 return self .set_webhook () # No params resets webhook
@@ -114,9 +114,6 @@ def reply_to(self, message, text, **kwargs):
114114 """
115115 return self .send_message (message .chat .id , text , reply_to_message_id = message .message_id , ** kwargs )
116116
117- def register_next_step_handler (self , message , handler ):
118- self .add_update_listener (listeners .NextStepHandler (handler , message ))
119-
120117 def message_handler (self , ** kwargs ):
121118 """
122119 Message handler decorator.
@@ -153,7 +150,7 @@ def decorator(handler):
153150 return decorator
154151
155152 def add_message_handler (self , handler , ** kwargs ):
156- self .add_update_listener ( listeners .MessageHandler (handler , ** kwargs ))
153+ self .event_bus . append_event_listener ( 'on_message' , listeners .MessageHandler (self . event_bus , handler , ** kwargs ))
157154
158155 def inline_handler (self , func ):
159156 def decorator (handler ):
@@ -162,7 +159,7 @@ def decorator(handler):
162159 return decorator
163160
164161 def add_inline_handler (self , handler , func ):
165- self .add_update_listener ( listeners .InlineHandler (handler , func ))
162+ self .event_bus . append_event_listener ( 'on_inline_query' , listeners .InlineHandler (handler , func ))
166163
167164 def chosen_inline_handler (self , func ):
168165 def decorator (handler ):
@@ -171,7 +168,7 @@ def decorator(handler):
171168 return decorator
172169
173170 def add_chosen_inline_handler (self , handler , func ):
174- self .add_update_listener ( listeners .ChosenInlineResultHandler (handler , func ))
171+ self .event_bus . append_event_listener ( 'on_chosen_inline_result' , listeners .ChosenInlineResultHandler (handler , func ))
175172
176173 def callback_query_handler (self , func ):
177174 def decorator (handler ):
@@ -180,4 +177,6 @@ def decorator(handler):
180177 return decorator
181178
182179 def add_callback_query_handler (self , handler , func ):
183- self .add_update_listener (listeners .CallbackQueryHandler (handler , func ))
180+ self .event_bus .append_event_listener ('on_callback_query' , listeners .CallbackQueryHandler (handler , func ))
181+
182+
0 commit comments