Skip to content

Commit 94d3474

Browse files
committed
Merge branch 'inline-mode' into develop
2 parents 7514c61 + 8278eef commit 94d3474

4 files changed

Lines changed: 388 additions & 48 deletions

File tree

‎examples/inline_example.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# This example show how to write an inline mode telegramt bot use pyTelegramBotAPI.
2+
import telebot
3+
import time
4+
import sys
5+
from telebot import types
6+
7+
API_TOKEN = '<api_token>'
8+
9+
bot = telebot.TeleBot(API_TOKEN)
10+
11+
12+
@bot.inline_handler(lambda query: query.query == 'text')
13+
def query(inline_query):
14+
try:
15+
r = types.InlineQueryResultArticle('1', 'Result', inline_query.query)
16+
bot.answer_inline_query(inline_query.id, [r])
17+
except Exception as e:
18+
print(e)
19+
20+
21+
@bot.inline_handler(lambda query: len(query.query) is 0)
22+
def default_query(inline_query):
23+
try:
24+
r = types.InlineQueryResultArticle('1', 'default', 'default')
25+
bot.answer_inline_query(inline_query.id, [r])
26+
except Exception as e:
27+
print(e)
28+
29+
30+
def main_loop():
31+
bot.polling(True)
32+
while 1:
33+
time.sleep(3)
34+
35+
36+
if __name__ == '__main__':
37+
try:
38+
main_loop()
39+
except KeyboardInterrupt:
40+
print >> sys.stderr, '\nExiting by user request.\n'
41+
sys.exit(0)

‎telebot/__init__.py‎

Lines changed: 62 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
logger = logging.getLogger('TeleBot')
1313
formatter = logging.Formatter(
14-
'%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"'
14+
'%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"'
1515
)
1616

1717
console_output_handler = logging.StreamHandler(sys.stderr)
@@ -66,6 +66,8 @@ def __init__(self, token, threaded=True, skip_pending=False):
6666
self.pre_message_subscribers_next_step = {}
6767

6868
self.message_handlers = []
69+
self.inline_handlers = []
70+
self.chosen_inline_handlers = []
6971

7072
self.threaded = threaded
7173
if self.threaded:
@@ -103,7 +105,7 @@ def __skip_updates(self):
103105
for update in updates:
104106
if update.update_id > self.last_update_id:
105107
self.last_update_id = update.update_id
106-
updates = self.get_updates(offset=self.last_update_id+1, timeout=1)
108+
updates = self.get_updates(offset=self.last_update_id + 1, timeout=1)
107109
return total
108110

109111
def __retrieve_updates(self, timeout=20):
@@ -117,21 +119,38 @@ def __retrieve_updates(self, timeout=20):
117119
self.skip_pending = False
118120
updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
119121
new_messages = []
122+
new_inline_querys = []
123+
new_chosen_inline_results = []
120124
for update in updates:
121125
if update.update_id > self.last_update_id:
122126
self.last_update_id = update.update_id
123-
new_messages.append(update.message)
124-
logger.debug('Received {0} new messages'.format(len(new_messages)))
127+
if update.message:
128+
new_messages.append(update.message)
129+
if update.inline_query:
130+
new_inline_querys.append(update.inline_query)
131+
if update.chosen_inline_result:
132+
new_chosen_inline_results.append(update.chosen_inline_result)
133+
logger.debug('Received {0} new updates'.format(len(updates)))
125134
if len(new_messages) > 0:
126135
self.process_new_messages(new_messages)
136+
if len(new_inline_querys) > 0:
137+
self.process_new_inline_query(new_inline_querys)
138+
if len(new_chosen_inline_results) > 0:
139+
self.process_new_chosen_inline_query(new_chosen_inline_results)
127140

128141
def process_new_messages(self, new_messages):
129142
self._append_pre_next_step_handler()
130143
self.__notify_update(new_messages)
131-
self._notify_command_handlers(new_messages)
144+
self._notify_command_handlers(self.message_handlers, new_messages)
132145
self._notify_message_subscribers(new_messages)
133146
self._notify_message_next_handler(new_messages)
134147

148+
def process_new_inline_query(self, new_inline_querys):
149+
self._notify_command_handlers(self.inline_handlers, new_inline_querys)
150+
151+
def process_new_chosen_inline_query(self, new_chosen_inline_querys):
152+
self._notify_command_handlers(self.chosen_inline_handlers, new_chosen_inline_querys)
153+
135154
def __notify_update(self, new_messages):
136155
for listener in self.update_listener:
137156
self.__exec_task(listener, new_messages)
@@ -160,9 +179,9 @@ def __threaded_polling(self, none_stop=False, interval=0, timeout=3):
160179

161180
polling_thread = util.WorkerThread(name="PollingThread")
162181
or_event = util.OrEvent(
163-
polling_thread.done_event,
164-
polling_thread.exception_event,
165-
self.worker_pool.exception_event
182+
polling_thread.done_event,
183+
polling_thread.exception_event,
184+
self.worker_pool.exception_event
166185
)
167186

168187
while not self.__stop_polling.wait(interval):
@@ -271,8 +290,8 @@ def send_message(self, chat_id, text, disable_web_page_preview=None, reply_to_me
271290
:return: API reply.
272291
"""
273292
return types.Message.de_json(
274-
apihelper.send_message(self.token, chat_id, text, disable_web_page_preview, reply_to_message_id,
275-
reply_markup, parse_mode))
293+
apihelper.send_message(self.token, chat_id, text, disable_web_page_preview, reply_to_message_id,
294+
reply_markup, parse_mode))
276295

277296
def forward_message(self, chat_id, from_chat_id, message_id):
278297
"""
@@ -295,7 +314,7 @@ def send_photo(self, chat_id, photo, caption=None, reply_to_message_id=None, rep
295314
:return: API reply.
296315
"""
297316
return types.Message.de_json(
298-
apihelper.send_photo(self.token, chat_id, photo, caption, reply_to_message_id, reply_markup))
317+
apihelper.send_photo(self.token, chat_id, photo, caption, reply_to_message_id, reply_markup))
299318

300319
def send_audio(self, chat_id, audio, duration=None, performer=None, title=None, reply_to_message_id=None,
301320
reply_markup=None):
@@ -311,8 +330,8 @@ def send_audio(self, chat_id, audio, duration=None, performer=None, title=None,
311330
:return: Message
312331
"""
313332
return types.Message.de_json(
314-
apihelper.send_audio(self.token, chat_id, audio, duration, performer, title, reply_to_message_id,
315-
reply_markup))
333+
apihelper.send_audio(self.token, chat_id, audio, duration, performer, title, reply_to_message_id,
334+
reply_markup))
316335

317336
def send_voice(self, chat_id, voice, duration=None, reply_to_message_id=None, reply_markup=None):
318337
"""
@@ -325,7 +344,7 @@ def send_voice(self, chat_id, voice, duration=None, reply_to_message_id=None, re
325344
:return: Message
326345
"""
327346
return types.Message.de_json(
328-
apihelper.send_voice(self.token, chat_id, voice, duration, reply_to_message_id, reply_markup))
347+
apihelper.send_voice(self.token, chat_id, voice, duration, reply_to_message_id, reply_markup))
329348

330349
def send_document(self, chat_id, data, reply_to_message_id=None, reply_markup=None):
331350
"""
@@ -337,7 +356,7 @@ def send_document(self, chat_id, data, reply_to_message_id=None, reply_markup=No
337356
:return: API reply.
338357
"""
339358
return types.Message.de_json(
340-
apihelper.send_data(self.token, chat_id, data, 'document', reply_to_message_id, reply_markup))
359+
apihelper.send_data(self.token, chat_id, data, 'document', reply_to_message_id, reply_markup))
341360

342361
def send_sticker(self, chat_id, data, reply_to_message_id=None, reply_markup=None):
343362
"""
@@ -349,7 +368,7 @@ def send_sticker(self, chat_id, data, reply_to_message_id=None, reply_markup=Non
349368
:return: API reply.
350369
"""
351370
return types.Message.de_json(
352-
apihelper.send_data(self.token, chat_id, data, 'sticker', reply_to_message_id, reply_markup))
371+
apihelper.send_data(self.token, chat_id, data, 'sticker', reply_to_message_id, reply_markup))
353372

354373
def send_video(self, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None):
355374
"""
@@ -363,7 +382,7 @@ def send_video(self, chat_id, data, duration=None, caption=None, reply_to_messag
363382
:return:
364383
"""
365384
return types.Message.de_json(
366-
apihelper.send_video(self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup))
385+
apihelper.send_video(self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup))
367386

368387
def send_location(self, chat_id, latitude, longitude, reply_to_message_id=None, reply_markup=None):
369388
"""
@@ -376,7 +395,7 @@ def send_location(self, chat_id, latitude, longitude, reply_to_message_id=None,
376395
:return: API reply.
377396
"""
378397
return types.Message.de_json(
379-
apihelper.send_location(self.token, chat_id, latitude, longitude, reply_to_message_id, reply_markup))
398+
apihelper.send_location(self.token, chat_id, latitude, longitude, reply_to_message_id, reply_markup))
380399

381400
def send_chat_action(self, chat_id, action):
382401
"""
@@ -396,6 +415,9 @@ def reply_to(self, message, text, **kwargs):
396415
"""
397416
return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)
398417

418+
def answer_inline_query(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None):
419+
return apihelper.answer_inline_query(self.token, inline_query_id, results, cache_time, is_personal, next_offset)
420+
399421
def register_for_reply(self, message, callback):
400422
"""
401423
Registers a callback function to be notified when a reply to `message` arrives.
@@ -504,6 +526,26 @@ def decorator(fn):
504526

505527
return decorator
506528

529+
def inline_handler(self, func):
530+
def decorator(fn):
531+
handler_dict = {'function': fn}
532+
filters = {'lambda': func}
533+
handler_dict['filters'] = filters
534+
self.inline_handlers.append(handler_dict)
535+
return fn
536+
537+
return decorator
538+
539+
def chosen_inline_handler(self, func):
540+
def decorator(fn):
541+
handler_dict = {'function': fn}
542+
filters = {'lambda': func}
543+
handler_dict['filters'] = filters
544+
self.chosen_inline_handlers.append(handler_dict)
545+
return fn
546+
547+
return decorator
548+
507549
@staticmethod
508550
def _test_message_handler(message_handler, message):
509551
for filter, filter_value in six.iteritems(message_handler['filters']):
@@ -523,9 +565,9 @@ def _test_filter(filter, filter_value, message):
523565
return filter_value(message)
524566
return False
525567

526-
def _notify_command_handlers(self, new_messages):
568+
def _notify_command_handlers(self, handlers, new_messages):
527569
for message in new_messages:
528-
for message_handler in self.message_handlers:
570+
for message_handler in handlers:
529571
if self._test_message_handler(message_handler, message):
530572
self.__exec_task(message_handler['function'], message)
531573
break

‎telebot/apihelper.py‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,19 +42,19 @@ def _check_result(method_name, result):
4242
:return: The result parsed to a JSON dictionary.
4343
"""
4444
if result.status_code != 200:
45-
msg = 'The server returned HTTP {0} {1}. Response body:\n[{2}]'\
45+
msg = 'The server returned HTTP {0} {1}. Response body:\n[{2}]' \
4646
.format(result.status_code, result.reason, result.text.encode('utf8'))
4747
raise ApiException(msg, method_name, result)
4848

4949
try:
5050
result_json = result.json()
5151
except:
52-
msg = 'The server returned an invalid JSON response. Response body:\n[{0}]'\
52+
msg = 'The server returned an invalid JSON response. Response body:\n[{0}]' \
5353
.format(result.text.encode('utf8'))
5454
raise ApiException(msg, method_name, result)
5555

5656
if not result_json['ok']:
57-
msg = 'Error code: {0} Description: {1}'\
57+
msg = 'Error code: {0} Description: {1}' \
5858
.format(result_json['error_code'], result_json['description'])
5959
raise ApiException(msg, method_name, result)
6060
return result_json
@@ -74,7 +74,7 @@ def download_file(token, file_path):
7474
url = FILE_URL.format(token, file_path)
7575
result = requests.get(url)
7676
if result.status_code != 200:
77-
msg = 'The server returned HTTP {0} {1}. Response body:\n[{2}]'\
77+
msg = 'The server returned HTTP {0} {1}. Response body:\n[{2}]' \
7878
.format(result.status_code, result.reason, result.text)
7979
raise ApiException(msg, 'Download file', result)
8080
return result.content
@@ -258,11 +258,34 @@ def get_method_by_type(data_type):
258258
return r'sendSticker'
259259

260260

261+
def answer_inline_query(token, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None):
262+
method_url = 'answerInlineQuery'
263+
payload = {'inline_query_id': inline_query_id, 'results': _convert_inline_results(results)}
264+
if cache_time:
265+
payload['cache_time'] = cache_time
266+
if is_personal:
267+
payload['is_personal'] = is_personal
268+
if next_offset:
269+
payload['next_offset'] = next_offset
270+
return _make_request(token, method_url, params=payload)
271+
272+
273+
def _convert_inline_results(results):
274+
ret = ''
275+
for r in results:
276+
if isinstance(r, types.JsonSerializable):
277+
ret = ret + r.to_json() + ','
278+
if len(ret) > 0:
279+
ret = ret[:-1]
280+
return '[' + ret + ']'
281+
282+
261283
def _convert_markup(markup):
262284
if isinstance(markup, types.JsonSerializable):
263285
return markup.to_json()
264286
return markup
265287

288+
266289
class ApiException(Exception):
267290
"""
268291
This class represents an Exception thrown when a call to the Telegram API fails.

0 commit comments

Comments
 (0)