Skip to content

Commit eb726ea

Browse files
committed
Implemented yield and a simple event bus
1 parent f553062 commit eb726ea

5 files changed

Lines changed: 154 additions & 94 deletions

File tree

‎telebot/apihelper.py‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,7 @@ def __init__(self, token, request_executor, api_url=API_URL, file_url=FILE_URL):
4242
self.file_url = file_url
4343

4444
@staticmethod
45-
def convert_markup(markup):
46-
return types.to_json(markup)
47-
48-
@staticmethod
49-
def convert_inline_results(results):
45+
def __convert_inline_results(results):
5046
"""
5147
Converts a list of InlineQueryResult objects to a json string.
5248
:param results: list of InlineQueryResult objects
@@ -58,15 +54,15 @@ def convert_inline_results(results):
5854
def make_request(self, method_name, params=None, files=None, method='get', response_type='json'):
5955
request_url = self.api_url.format(self.token, method_name)
6056
try:
61-
response = self.request_executor(request_url,
62-
method=method, params=params, files=files, response_type=response_type)
57+
kwargs = {'method': method, 'params': params, 'files': files, 'response_type': response_type}
58+
response = self.request_executor(request_url, **kwargs)
6359
return response
6460
except Exception as e:
6561
raise ApiException(repr(e), method_name)
6662

6763
def make_json_request(self, method_name, params=None, files=None, method='post', return_type=None):
6864
if params is not None and 'reply_markup' in params:
69-
params['reply_markup'] = self.convert_markup(params['reply_markup'])
65+
params['reply_markup'] = types.to_json(params['reply_markup'])
7066

7167
response = self.make_request(method_name, params, files, method, response_type='json')
7268
if not response['ok']:
@@ -406,7 +402,7 @@ def answer_inline_query(self, inline_query_id, results, **kwargs):
406402
"""
407403
params = util.xmerge({
408404
'inline_query_id': inline_query_id,
409-
'results': self.convert_inline_results(results)
405+
'results': self.__convert_inline_results(results)
410406
}, kwargs)
411407
return self.make_json_request('answerInlineQuery', params=params)
412408

‎telebot/listeners.py‎

Lines changed: 87 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# -*- coding: utf-8 -*-
22
import re
3+
import six
4+
import types
35

46
from telebot import util
57

@@ -8,46 +10,99 @@ def same_chat(chat):
810
return lambda message: message.chat.id == chat.id
911

1012

13+
def has_content_types(content_types):
14+
return lambda m: m.content_type in content_types
15+
16+
17+
def has_commands(commands):
18+
return lambda m: m.content_type == 'text' and util.extract_command(m.text) in commands
19+
20+
21+
def has_regex(regex):
22+
return lambda m: m.content_type == 'text' and re.search(regex, m.text)
23+
24+
25+
class EventBus:
26+
27+
def __init__(self):
28+
self.event_listeners = {}
29+
30+
def prepend_event_listener(self, event, listener):
31+
if event in self.event_listeners:
32+
self.event_listeners[event].insert(0, listener)
33+
else:
34+
self.event_listeners[event] = [listener]
35+
36+
def append_event_listener(self, event, listener):
37+
if event in self.event_listeners:
38+
self.event_listeners[event].append(listener)
39+
else:
40+
self.event_listeners[event] = [listener]
41+
42+
def remove_event_listener(self, listener):
43+
for event, event_listeners in six.iteritems(self.event_listeners):
44+
if listener in event_listeners:
45+
event_listeners.remove(listener)
46+
return True
47+
return False
48+
49+
def dispatch(self, event, *args, **kwargs):
50+
if event not in self.event_listeners:
51+
util.logger.debug("Event {0} dispatched but no listeners".format(event))
52+
return
53+
54+
for listener in self.event_listeners[event]:
55+
if listener(*args, **kwargs):
56+
break
57+
58+
1159
class GeneratorListener:
1260

13-
def __init__(self, func):
14-
self.func = func
61+
def __init__(self, event_bus, chat_id, generator):
62+
self.event_bus = event_bus
63+
self.chat_id = chat_id
64+
self.generator = generator
65+
66+
def __call__(self, message):
67+
if message.chat.id != self.chat_id:
68+
return False
69+
70+
try:
71+
self.generator.send(message)
72+
except StopIteration:
73+
self.event_bus.remove_event_listener(self)
74+
return True
75+
1576

1677
class MessageHandler:
1778

18-
def __init__(self, handler, commands=None, regexp=None, func=None, content_types=None):
79+
def __init__(self, event_bus, handler, commands=None, regexp=None, func=None, content_types=None):
80+
self.event_bus = event_bus
81+
1982
self.handler = handler
2083
self.tests = []
2184
if content_types is not None:
22-
self.tests.append(lambda m: m.content_type in content_types)
85+
self.tests.append(has_content_types(content_types))
2386

2487
if commands is not None:
25-
self.tests.append(lambda m: m.content_type == 'text' and util.extract_command(m.text) in commands)
88+
self.tests.append(has_commands(commands))
2689

2790
if regexp is not None:
28-
self.tests.append(lambda m: m.content_type == 'text' and re.search(regexp, m.text))
91+
self.tests.append(has_regex(regexp))
2992

3093
if func is not None:
3194
self.tests.append(func)
3295

33-
def test_message(self, message):
34-
return all([test(message) for test in self.tests])
35-
36-
def __call__(self, update):
37-
if update.message is not None and self.test_message(update.message):
38-
return self.handler(update.message)
39-
40-
41-
42-
class NextStepHandler:
43-
44-
def __init__(self, handler, message):
45-
self.chat_id = message.chat.id
46-
self.handler = handler
96+
def __call__(self, message):
97+
if not all([test(message) for test in self.tests]):
98+
return False
4799

48-
def __call__(self, update):
49-
if update.message is not None and update.message.chat.id == self.chat_id:
50-
return self.handler(update.message)
100+
returned = self.handler(message)
101+
if isinstance(returned, types.GeneratorType):
102+
returned.next()
103+
generator_listener = GeneratorListener(self.event_bus, message.chat.id, returned)
104+
self.event_bus.prepend_event_listener('on_message', generator_listener)
105+
return True
51106

52107

53108
class InlineHandler:
@@ -56,9 +111,9 @@ def __init__(self, handler, func):
56111
self.handler = handler
57112
self.func = func
58113

59-
def __call__(self, update):
60-
if update.inline_query is not None and self.func(update.inline_query):
61-
return self.handler(update.inline_query)
114+
def __call__(self, inline_query):
115+
if self.func(inline_query):
116+
return self.handler(inline_query)
62117

63118

64119
class ChosenInlineResultHandler:
@@ -67,9 +122,9 @@ def __init__(self, handler, func):
67122
self.handler = handler
68123
self.func = func
69124

70-
def __call__(self, update):
71-
if update.chosen_inline_result is not None and self.func(update.chosen_inline_result):
72-
return self.handler(update.chosen_inline_result)
125+
def __call__(self, chosen_inline_result):
126+
if self.func(chosen_inline_result):
127+
return self.handler(chosen_inline_result)
73128

74129

75130
class CallbackQueryHandler:
@@ -78,6 +133,6 @@ def __init__(self, handler, func):
78133
self.handler = handler
79134
self.func = func
80135

81-
def __call__(self, update):
82-
if update.callback_query is not None and self.func(update.callback_query):
83-
self.handler(update.callback_query)
136+
def __call__(self, callback_query):
137+
if self.func(callback_query):
138+
self.handler(callback_query)

‎telebot/telebot_class.py‎

Lines changed: 51 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,42 @@
1-
2-
import threading
3-
import six
4-
import sys
5-
import time
6-
import types
7-
1+
# -*- coding: utf-8 -*-
82
import telebot.listeners as listeners
93
from 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

2517
class 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

Comments
 (0)