1
0
mirror of https://github.com/eternnoir/pyTelegramBotAPI.git synced 2023-08-10 21:12:57 +03:00

Merge branch 'inline-mode' into develop

This commit is contained in:
eternnoir 2016-01-05 15:35:45 +08:00
commit 94d34747d1
4 changed files with 386 additions and 46 deletions

View File

@ -0,0 +1,41 @@
# This example show how to write an inline mode telegramt bot use pyTelegramBotAPI.
import telebot
import time
import sys
from telebot import types
API_TOKEN = '<api_token>'
bot = telebot.TeleBot(API_TOKEN)
@bot.inline_handler(lambda query: query.query == 'text')
def query(inline_query):
try:
r = types.InlineQueryResultArticle('1', 'Result', inline_query.query)
bot.answer_inline_query(inline_query.id, [r])
except Exception as e:
print(e)
@bot.inline_handler(lambda query: len(query.query) is 0)
def default_query(inline_query):
try:
r = types.InlineQueryResultArticle('1', 'default', 'default')
bot.answer_inline_query(inline_query.id, [r])
except Exception as e:
print(e)
def main_loop():
bot.polling(True)
while 1:
time.sleep(3)
if __name__ == '__main__':
try:
main_loop()
except KeyboardInterrupt:
print >> sys.stderr, '\nExiting by user request.\n'
sys.exit(0)

View File

@ -66,6 +66,8 @@ class TeleBot:
self.pre_message_subscribers_next_step = {} self.pre_message_subscribers_next_step = {}
self.message_handlers = [] self.message_handlers = []
self.inline_handlers = []
self.chosen_inline_handlers = []
self.threaded = threaded self.threaded = threaded
if self.threaded: if self.threaded:
@ -117,21 +119,38 @@ class TeleBot:
self.skip_pending = False self.skip_pending = False
updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout) updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
new_messages = [] new_messages = []
new_inline_querys = []
new_chosen_inline_results = []
for update in updates: for update in updates:
if update.update_id > self.last_update_id: if update.update_id > self.last_update_id:
self.last_update_id = update.update_id self.last_update_id = update.update_id
if update.message:
new_messages.append(update.message) new_messages.append(update.message)
logger.debug('Received {0} new messages'.format(len(new_messages))) if update.inline_query:
new_inline_querys.append(update.inline_query)
if update.chosen_inline_result:
new_chosen_inline_results.append(update.chosen_inline_result)
logger.debug('Received {0} new updates'.format(len(updates)))
if len(new_messages) > 0: if len(new_messages) > 0:
self.process_new_messages(new_messages) self.process_new_messages(new_messages)
if len(new_inline_querys) > 0:
self.process_new_inline_query(new_inline_querys)
if len(new_chosen_inline_results) > 0:
self.process_new_chosen_inline_query(new_chosen_inline_results)
def process_new_messages(self, new_messages): def process_new_messages(self, new_messages):
self._append_pre_next_step_handler() self._append_pre_next_step_handler()
self.__notify_update(new_messages) self.__notify_update(new_messages)
self._notify_command_handlers(new_messages) self._notify_command_handlers(self.message_handlers, new_messages)
self._notify_message_subscribers(new_messages) self._notify_message_subscribers(new_messages)
self._notify_message_next_handler(new_messages) self._notify_message_next_handler(new_messages)
def process_new_inline_query(self, new_inline_querys):
self._notify_command_handlers(self.inline_handlers, new_inline_querys)
def process_new_chosen_inline_query(self, new_chosen_inline_querys):
self._notify_command_handlers(self.chosen_inline_handlers, new_chosen_inline_querys)
def __notify_update(self, new_messages): def __notify_update(self, new_messages):
for listener in self.update_listener: for listener in self.update_listener:
self.__exec_task(listener, new_messages) self.__exec_task(listener, new_messages)
@ -396,6 +415,9 @@ class TeleBot:
""" """
return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)
def answer_inline_query(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None):
return apihelper.answer_inline_query(self.token, inline_query_id, results, cache_time, is_personal, next_offset)
def register_for_reply(self, message, callback): def register_for_reply(self, message, callback):
""" """
Registers a callback function to be notified when a reply to `message` arrives. Registers a callback function to be notified when a reply to `message` arrives.
@ -504,6 +526,26 @@ class TeleBot:
return decorator return decorator
def inline_handler(self, func):
def decorator(fn):
handler_dict = {'function': fn}
filters = {'lambda': func}
handler_dict['filters'] = filters
self.inline_handlers.append(handler_dict)
return fn
return decorator
def chosen_inline_handler(self, func):
def decorator(fn):
handler_dict = {'function': fn}
filters = {'lambda': func}
handler_dict['filters'] = filters
self.chosen_inline_handlers.append(handler_dict)
return fn
return decorator
@staticmethod @staticmethod
def _test_message_handler(message_handler, message): def _test_message_handler(message_handler, message):
for filter, filter_value in six.iteritems(message_handler['filters']): for filter, filter_value in six.iteritems(message_handler['filters']):
@ -523,9 +565,9 @@ class TeleBot:
return filter_value(message) return filter_value(message)
return False return False
def _notify_command_handlers(self, new_messages): def _notify_command_handlers(self, handlers, new_messages):
for message in new_messages: for message in new_messages:
for message_handler in self.message_handlers: for message_handler in handlers:
if self._test_message_handler(message_handler, message): if self._test_message_handler(message_handler, message):
self.__exec_task(message_handler['function'], message) self.__exec_task(message_handler['function'], message)
break break

View File

@ -258,11 +258,34 @@ def get_method_by_type(data_type):
return r'sendSticker' return r'sendSticker'
def answer_inline_query(token, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None):
method_url = 'answerInlineQuery'
payload = {'inline_query_id': inline_query_id, 'results': _convert_inline_results(results)}
if cache_time:
payload['cache_time'] = cache_time
if is_personal:
payload['is_personal'] = is_personal
if next_offset:
payload['next_offset'] = next_offset
return _make_request(token, method_url, params=payload)
def _convert_inline_results(results):
ret = ''
for r in results:
if isinstance(r, types.JsonSerializable):
ret = ret + r.to_json() + ','
if len(ret) > 0:
ret = ret[:-1]
return '[' + ret + ']'
def _convert_markup(markup): def _convert_markup(markup):
if isinstance(markup, types.JsonSerializable): if isinstance(markup, types.JsonSerializable):
return markup.to_json() return markup.to_json()
return markup return markup
class ApiException(Exception): class ApiException(Exception):
""" """
This class represents an Exception thrown when a call to the Telegram API fails. This class represents an Exception thrown when a call to the Telegram API fails.

View File

@ -1,24 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""
Available types
User # TODO InlineQueryResultArticle, InlineQueryResultPhoto, InlineQueryResultGif, InlineQueryResultMpeg4Gif, InlineQueryResultVideo
GroupChat
Message
PhotoSize
Audio
Document
Sticker
Video
Contact
Location
Update
InputFile
UserProfilePhotos
ReplyKeyboardMarkup
ReplyKeyboardHide
ForceReply
"""
import json import json
import six import six
@ -87,12 +69,22 @@ class Update(JsonDeserializable):
def de_json(cls, json_type): def de_json(cls, json_type):
obj = cls.check_json(json_type) obj = cls.check_json(json_type)
update_id = obj['update_id'] update_id = obj['update_id']
message = None
inline_query = None
chosen_inline_result = None
if 'message' in obj:
message = Message.de_json(obj['message']) message = Message.de_json(obj['message'])
return cls(update_id, message) if 'inline_query' in obj:
inline_query = InlineQuery.de_json(obj['inline_query'])
if 'chosen_inline_result' in obj:
chosen_inline_result = ChosenInlineResult.de_json(obj['chosen_inline_result'])
return cls(update_id, message, inline_query, chosen_inline_result)
def __init__(self, update_id, message): def __init__(self, update_id, message, inline_query, chosen_inline_result):
self.update_id = update_id self.update_id = update_id
self.message = message self.message = message
self.inline_query = inline_query
self.chosen_inline_result = chosen_inline_result
class User(JsonDeserializable): class User(JsonDeserializable):
@ -515,3 +507,245 @@ class ReplyKeyboardMarkup(JsonSerializable):
json_dict['selective'] = True json_dict['selective'] = True
return json.dumps(json_dict) return json.dumps(json_dict)
class InlineQuery(JsonDeserializable):
@classmethod
def de_json(cls, json_type):
obj = cls.check_json(json_type)
id = obj['id']
from_user = User.de_json(obj['from'])
query = obj['query']
offset = obj['offset']
return cls(id, from_user, query, offset)
def __init__(self, id, from_user, query, offset):
"""
This object represents an incoming inline query.
When the user sends an empty query, your bot could
return some default or trending results.
:param id: string Unique identifier for this query
:param from_user: User Sender
:param query: String Text of the query
:param offset: String Offset of the results to be returned, can be controlled by the bot
:return: InlineQuery Object
"""
self.id = id
self.from_user = from_user
self.query = query
self.offset = offset
class ChosenInlineResult(JsonDeserializable):
@classmethod
def de_json(cls, json_type):
obj = cls.check_json(json_type)
result_id = obj['result_id']
from_user = User.de_json(obj['from'])
query = obj['query']
return cls(result_id, from_user, query)
def __init__(self, result_id, from_user, query):
"""
This object represents a result of an inline query
that was chosen by the user and sent to their chat partner.
:param result_id: string The unique identifier for the result that was chosen.
:param from_user: User The user that chose the result.
:param query: String The query that was used to obtain the result.
:return: ChosenInlineResult Object.
"""
self.result_id = result_id
self.from_user = from_user
self.query = query
class InlineQueryResultArticle(JsonSerializable):
def __init__(self, id, title, message_text, parse_mode=None, disable_web_page_preview=None, url=None,
hide_url=None, description=None, thumb_url=None, thumb_width=None, thumb_height=None):
self.type = 'article'
self.id = id
self.title = title
self.message_text = message_text
self.parse_mode = parse_mode
self.disable_web_page_preview = disable_web_page_preview
self.url = url
self.hide_url = hide_url
self.description = description
self.thumb_url = thumb_url
self.thumb_width = thumb_width
self.thumb_height = thumb_height
def to_json(self):
json_dict = {'type': self.type, 'id': self.id, 'title': self.title, 'message_text': self.message_text}
if self.parse_mode:
json_dict['parse_mode'] = self.parse_mode
if self.disable_web_page_preview:
json_dict['disable_web_page_preview'] = self.disable_web_page_preview
if self.url:
json_dict['url'] = self.url
if self.hide_url:
json_dict['hide_url'] = self.hide_url
if self.description:
json_dict['description'] = self.description
if self.thumb_url:
json_dict['thumb_url'] = self.thumb_url
if self.thumb_width:
json_dict['thumb_width'] = self.thumb_width
if self.thumb_height:
json_dict['thumb_height'] = self.thumb_height
return json.dumps(json_dict)
class InlineQueryResultPhoto(JsonSerializable):
def __init__(self, id, photo_url, mime_type=None, photo_width=None, photo_height=None, thumb_url=None, title=None,
description=None, caption=None, message_text=None, parse_mode=None, disable_web_page_preview=None):
self.type = 'photo'
self.id = id
self.photo_url = photo_url
self.mime_type = mime_type
self.photo_width = photo_width
self.photo_height = photo_height
self.thumb_url = thumb_url
self.title = title
self.description = description
self.caption = caption
self.message_text = message_text
self.parse_mode = parse_mode
self.disable_web_page_preview = disable_web_page_preview
def to_json(self):
json_dict = {'type': self.type, 'id': self.id, 'photo_url': self.photo_url}
if self.mime_type:
json_dict['mime_type'] = self.mime_type
if self.photo_width:
json_dict['photo_width'] = self.photo_width
if self.photo_height:
json_dict['photo_height'] = self.photo_height
if self.thumb_url:
json_dict['thumb_url'] = self.thumb_url
if self.title:
json_dict['title'] = self.title
if self.description:
json_dict['description'] = self.description
if self.caption:
json_dict['caption'] = self.caption
if self.message_text:
json_dict['message_text'] = self.message_text
if self.parse_mode:
json_dict['parse_mode'] = self.parse_mode
if self.disable_web_page_preview:
json_dict['disable_web_page_preview'] = self.disable_web_page_preview
return json.dumps(json_dict)
class InlineQueryResultGif(JsonSerializable):
def __init__(self, id, gif_url, gif_width=None, gif_height=None, thumb_url=None, title=None, caption=None,
message_text=None, parse_mode=None, disable_web_page_preview=None):
self.type = 'gif'
self.id = id
self.gif_url = gif_url
self.gif_width = gif_width
self.gif_height = gif_height
self.thumb_url = thumb_url
self.title = title
self.caption = caption
self.message_text = message_text
self.parse_mode = parse_mode
self.disable_web_page_preview = disable_web_page_preview
def to_json(self):
json_dict = {'type': self.type, 'id': self.id, 'gif_url': self.gif_url}
if self.gif_height:
json_dict['gif_height'] = self.gif_height
if self.gif_width:
json_dict['gif_width'] = self.gif_width
if self.thumb_url:
json_dict['thumb_url'] = self.thumb_url
if self.title:
json_dict['title'] = self.title
if self.caption:
json_dict['caption'] = self.caption
if self.message_text:
json_dict['message_text'] = self.message_text
if self.parse_mode:
json_dict['parse_mode'] = self.parse_mode
if self.disable_web_page_preview:
json_dict['disable_web_page_preview'] = self.disable_web_page_preview
return json.dumps(json_dict)
class InlineQueryResultMpeg4Gif(JsonSerializable):
def __init__(self, id, mpeg4_url, mpeg4_width=None, mpeg4_height=None, thumb_url=None, title=None, caption=None,
message_text=None, parse_mode=None, disable_web_page_preview=None):
self.type = 'mpeg4_gif'
self.id = id
self.mpeg4_url = mpeg4_url
self.mpeg4_width = mpeg4_width
self.mpeg4_height = mpeg4_height
self.thumb_url = thumb_url
self.title = title
self.caption = caption
self.message_text = message_text
self.parse_mode = parse_mode
self.disable_web_page_preview = disable_web_page_preview
def to_json(self):
json_dict = {'type': self.type, 'id': self.id, 'mpeg4_url': self.mpeg4_url}
if self.mpeg4_width:
json_dict['mpeg4_width'] = self.mpeg4_width
if self.mpeg4_height:
json_dict['mpeg4_height'] = self.mpeg4_height
if self.thumb_url:
json_dict['thumb_url'] = self.thumb_url
if self.title:
json_dict['title'] = self.title
if self.caption:
json_dict['caption'] = self.caption
if self.message_text:
json_dict['message_text'] = self.message_text
if self.parse_mode:
json_dict['parse_mode'] = self.parse_mode
if self.disable_web_page_preview:
json_dict['disable_web_page_preview'] = self.disable_web_page_preview
return json.dumps(json_dict)
class InlineQueryResultVideo(JsonSerializable):
def __init__(self, id, video_url, mime_type, message_text=None, parse_mode=None, disable_web_page_preview=None,
video_width=None, video_height=None, video_duration=None, thumb_url=None, title=None,
description=None):
self.type = 'video'
self.id = id
self.video_url = video_url
self.mime_type = mime_type
self.message_text = message_text
self.parse_mode = parse_mode
self.disable_web_page_preview = disable_web_page_preview
self.video_width = video_width
self.video_height = video_height
self.video_duration = video_duration
self.thumb_url = thumb_url
self.title = title
self.description = description
def to_json(self):
json_dict = {'type': self.type, 'id': self.id, 'video_url': self.video_url, 'mime_type': self.mime_type}
if self.message_text:
json_dict['message_text'] = self.message_text
if self.parse_mode:
json_dict['parse_mode'] = self.parse_mode
if self.disable_web_page_preview:
json_dict['disable_web_page_preview'] = self.disable_web_page_preview
if self.video_width:
json_dict['video_width'] = self.video_width
if self.video_height:
json_dict['video_height'] = self.video_height
if self.video_duration:
json_dict['video_duration'] = self.video_duration
if self.thumb_url:
json_dict['thumb_url'] = self.thumb_url
if self.title:
json_dict['title'] = self.title
if self.description:
json_dict['description'] = self.description
return json.dumps(json_dict)