Merge pull request #294 from python-telegram-bot/yapf

yapf formatter, pre-commit hooks and new travis tests
This commit is contained in:
Leandro Toledo 2016-05-15 19:31:54 -03:00
commit 6bdca1e4f8
133 changed files with 627 additions and 1156 deletions

17
.pre-commit-config.yaml Normal file
View file

@ -0,0 +1,17 @@
- repo: git://github.com/pre-commit/mirrors-yapf
sha: 'v0.7.1'
hooks:
- id: yapf
args: ['-i']
- repo: git://github.com/pre-commit/pre-commit-hooks
sha: 'v0.5.0'
hooks:
- id: flake8
args: ['telegram']
- repo: git://github.com/pre-commit/mirrors-pylint
sha: 'v1.5.5'
hooks:
- id: pylint
args: ['--errors-only', '--disable=no-name-in-module,import-error', 'telegram']

View file

@ -13,7 +13,8 @@ install:
- pip install -r requirements-dev.txt - pip install -r requirements-dev.txt
script: script:
- nosetests -v --with-flaky --no-flaky-report --with-coverage --cover-package=telegram/ - nosetests -v --with-flaky --no-flaky-report --with-coverage --cover-package=telegram/
- 'if [ $TRAVIS_PYTHON_VERSION != 2.6 ] && [ $TRAVIS_PYTHON_VERSION != 3.3 ] && [ $TRAVIS_PYTHON_VERSION != pypy3 ]; then yapf -r telegram; fi'
- flake8 telegram - flake8 telegram
- 'if [[ $TRAVIS_PYTHON_VERSION != 2.6 ]]; then pylint -E telegram --disable=no-name-in-module,import-error; fi' - 'if [ $TRAVIS_PYTHON_VERSION != 2.6 ]; then pylint -E telegram --disable=no-name-in-module,import-error; fi'
after_success: after_success:
coveralls coveralls

View file

@ -22,6 +22,11 @@ Setting things up
``$ pip install -r requirements.txt -r requirements-dev.txt`` ``$ pip install -r requirements.txt -r requirements-dev.txt``
5. Install pre-commit hooks:
``$ pre-commit install``
Finding something to do Finding something to do
----------------------- -----------------------
@ -68,18 +73,20 @@ Here's how to make a one-off code change.
- Add yourself to the AUTHORS.rst_ file in an alphabetical fashion. - Add yourself to the AUTHORS.rst_ file in an alphabetical fashion.
- Before making a commit ensure that all automated tests, pep8 & lint validations still pass: - Before making a commit ensure that all automated tests still pass:
``$ make test`` ``$ make test``
``$ make pep8`` - To actually make the commit (this will trigger tests for yapf, lint and pep8 automatically):
``$ make lint`` ``$ git add your-file-changed.py``
- To actually make the commit and push it to your GitHub fork, run: - yapf may change code formatting, make sure to re-add them to your commit.
``$ git commit -a -m "your-commit-message-here"`` ``$ git commit -a -m "your-commit-message-here"``
- Finally, push it to your GitHub fork, run:
``$ git push origin your-branch-name`` ``$ git push origin your-branch-name``
4. **When your feature is ready to merge, create a pull request.** 4. **When your feature is ready to merge, create a pull request.**

View file

@ -1,10 +1,11 @@
.DEFAULT_GOAL := help .DEFAULT_GOAL := help
.PHONY: clean pep8 lint test install .PHONY: clean pep257 pep8 yapf lint test install
PYLINT := pylint PYLINT := pylint
NOSETESTS := nosetests NOSETESTS := nosetests
PEP257 := pep257 PEP257 := pep257
PEP8 := flake8 PEP8 := flake8
YAPF := yapf
PIP := pip PIP := pip
clean: clean:
@ -19,7 +20,10 @@ pep257:
$(PEP257) telegram $(PEP257) telegram
pep8: pep8:
$(PEP8) telegram $(PEP8) telegram
yapf:
$(YAPF) -r telegram
lint: lint:
$(PYLINT) -E telegram --disable=no-name-in-module,import-error $(PYLINT) -E telegram --disable=no-name-in-module,import-error
@ -28,7 +32,7 @@ test:
$(NOSETESTS) -v $(NOSETESTS) -v
install: install:
$(PIP) install -r requirements.txt $(PIP) install -r requirements.txt -r requirements-dev.txt
help: help:
@echo "Available targets:" @echo "Available targets:"
@ -36,6 +40,7 @@ help:
@echo "- pep257 Check docstring style with pep257" @echo "- pep257 Check docstring style with pep257"
@echo "- pep8 Check style with flake8" @echo "- pep8 Check style with flake8"
@echo "- lint Check style with pylint" @echo "- lint Check style with pylint"
@echo "- yapf Check style with yapf"
@echo "- test Run tests" @echo "- test Run tests"
@echo @echo
@echo "Available variables:" @echo "Available variables:"
@ -43,4 +48,5 @@ help:
@echo "- NOSETESTS default: $(NOSETESTS)" @echo "- NOSETESTS default: $(NOSETESTS)"
@echo "- PEP257 default: $(PEP257)" @echo "- PEP257 default: $(PEP257)"
@echo "- PEP8 default: $(PEP8)" @echo "- PEP8 default: $(PEP8)"
@echo "- YAPF default: $(YAPF)"
@echo "- PIP default: $(PIP)" @echo "- PIP default: $(PIP)"

View file

@ -3,4 +3,7 @@ nose
pep257 pep257
pylint pylint
unittest2 unittest2
flaky flaky
yapf
pre-commit
pre-commit-hooks

View file

@ -11,3 +11,7 @@ upload-dir = docs/build/html
[flake8] [flake8]
max-line-length = 99 max-line-length = 99
[yapf]
based_on_style = google
column_limit = 99

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""A library that provides a Python interface to the Telegram Bot API""" """A library that provides a Python interface to the Telegram Bot API"""
from sys import version_info from sys import version_info
@ -81,70 +80,24 @@ from .inputcontactmessagecontent import InputContactMessageContent
from .update import Update from .update import Update
from .bot import Bot from .bot import Bot
__author__ = 'devs@python-telegram-bot.org' __author__ = 'devs@python-telegram-bot.org'
__version__ = '4.0.3' __version__ = '4.0.3'
__all__ = ['Audio', __all__ = ['Audio', 'Bot', 'Chat', 'ChatAction', 'ChosenInlineResult', 'CallbackQuery', 'Contact',
'Bot', 'Document', 'Emoji', 'File', 'ForceReply', 'InlineKeyboardButton',
'Chat', 'InlineKeyboardMarkup', 'InlineQuery', 'InlineQueryResult', 'InlineQueryResult',
'ChatAction', 'InlineQueryResultArticle', 'InlineQueryResultAudio', 'InlineQueryResultCachedAudio',
'ChosenInlineResult', 'InlineQueryResultCachedDocument', 'InlineQueryResultCachedGif',
'CallbackQuery', 'InlineQueryResultCachedMpeg4Gif', 'InlineQueryResultCachedPhoto',
'Contact', 'InlineQueryResultCachedSticker', 'InlineQueryResultCachedVideo',
'Document', 'InlineQueryResultCachedVoice', 'InlineQueryResultContact', 'InlineQueryResultDocument',
'Emoji', 'InlineQueryResultGif', 'InlineQueryResultLocation', 'InlineQueryResultMpeg4Gif',
'File', 'InlineQueryResultPhoto', 'InlineQueryResultVenue', 'InlineQueryResultVideo',
'ForceReply', 'InlineQueryResultVoice', 'InputContactMessageContent', 'InputFile',
'InlineKeyboardButton', 'InputLocationMessageContent', 'InputMessageContent', 'InputTextMessageContent',
'InlineKeyboardMarkup', 'InputVenueMessageContent', 'KeyboardButton', 'Location', 'Message', 'MessageEntity',
'InlineQuery', 'NullHandler', 'ParseMode', 'PhotoSize', 'ReplyKeyboardHide', 'ReplyKeyboardMarkup',
'InlineQueryResult', 'ReplyMarkup', 'Sticker', 'TelegramError', 'TelegramObject', 'Update', 'User',
'InlineQueryResult', 'UserProfilePhotos', 'Venue', 'Video', 'Voice']
'InlineQueryResultArticle',
'InlineQueryResultAudio',
'InlineQueryResultCachedAudio',
'InlineQueryResultCachedDocument',
'InlineQueryResultCachedGif',
'InlineQueryResultCachedMpeg4Gif',
'InlineQueryResultCachedPhoto',
'InlineQueryResultCachedSticker',
'InlineQueryResultCachedVideo',
'InlineQueryResultCachedVoice',
'InlineQueryResultContact',
'InlineQueryResultDocument',
'InlineQueryResultGif',
'InlineQueryResultLocation',
'InlineQueryResultMpeg4Gif',
'InlineQueryResultPhoto',
'InlineQueryResultVenue',
'InlineQueryResultVideo',
'InlineQueryResultVoice',
'InputContactMessageContent',
'InputFile',
'InputLocationMessageContent',
'InputMessageContent',
'InputTextMessageContent',
'InputVenueMessageContent',
'KeyboardButton',
'Location',
'Message',
'MessageEntity',
'NullHandler',
'ParseMode',
'PhotoSize',
'ReplyKeyboardHide',
'ReplyKeyboardMarkup',
'ReplyMarkup',
'Sticker',
'TelegramError',
'TelegramObject',
'Update',
'User',
'UserProfilePhotos',
'Venue',
'Video',
'Voice']
if version_info < (2, 7): if version_info < (2, 7):
from warnings import warn from warnings import warn

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Audio.""" """This module contains a object that represents a Telegram Audio."""
from telegram import TelegramObject from telegram import TelegramObject
@ -45,10 +44,7 @@ class Audio(TelegramObject):
file_size (Optional[int]): file_size (Optional[int]):
""" """
def __init__(self, def __init__(self, file_id, duration, **kwargs):
file_id,
duration,
**kwargs):
# Required # Required
self.file_id = str(file_id) self.file_id = str(file_id)
self.duration = int(duration) self.duration = int(duration)

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""Base class for Telegram Objects.""" """Base class for Telegram Objects."""
import json import json

View file

@ -17,14 +17,13 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Bot.""" """This module contains a object that represents a Telegram Bot."""
import logging import logging
import functools import functools
from telegram import User, Message, Update, UserProfilePhotos, File, \ from telegram import (User, Message, Update, UserProfilePhotos, File, ReplyMarkup, TelegramObject,
ReplyMarkup, TelegramObject, NullHandler NullHandler)
from telegram.utils import request from telegram.utils import request
from telegram.utils.validate import validate_token from telegram.utils.validate import validate_token
@ -48,21 +47,16 @@ class Bot(TelegramObject):
""" """
def __init__(self, def __init__(self, token, base_url=None, base_file_url=None):
token,
base_url=None,
base_file_url=None):
self.token = validate_token(token) self.token = validate_token(token)
if not base_url: if not base_url:
self.base_url = 'https://api.telegram.org/bot{0}'.format( self.base_url = 'https://api.telegram.org/bot{0}'.format(self.token)
self.token)
else: else:
self.base_url = base_url + self.token self.base_url = base_url + self.token
if not base_file_url: if not base_file_url:
self.base_file_url = 'https://api.telegram.org/file/bot{0}'.format( self.base_file_url = 'https://api.telegram.org/file/bot{0}'.format(self.token)
self.token)
else: else:
self.base_file_url = base_file_url + self.token self.base_file_url = base_file_url + self.token
@ -71,6 +65,7 @@ class Bot(TelegramObject):
self.logger = logging.getLogger(__name__) self.logger = logging.getLogger(__name__)
def info(func): def info(func):
@functools.wraps(func) @functools.wraps(func)
def decorator(self, *args, **kwargs): def decorator(self, *args, **kwargs):
if not self.bot: if not self.bot:
@ -119,17 +114,16 @@ class Bot(TelegramObject):
return decorator return decorator
def message(func): def message(func):
@functools.wraps(func) @functools.wraps(func)
def decorator(self, *args, **kwargs): def decorator(self, *args, **kwargs):
url, data = func(self, *args, **kwargs) url, data = func(self, *args, **kwargs)
if kwargs.get('reply_to_message_id'): if kwargs.get('reply_to_message_id'):
data['reply_to_message_id'] = \ data['reply_to_message_id'] = kwargs.get('reply_to_message_id')
kwargs.get('reply_to_message_id')
if kwargs.get('disable_notification'): if kwargs.get('disable_notification'):
data['disable_notification'] = \ data['disable_notification'] = kwargs.get('disable_notification')
kwargs.get('disable_notification')
if kwargs.get('reply_markup'): if kwargs.get('reply_markup'):
reply_markup = kwargs.get('reply_markup') reply_markup = kwargs.get('reply_markup')
@ -138,8 +132,7 @@ class Bot(TelegramObject):
else: else:
data['reply_markup'] = reply_markup data['reply_markup'] = reply_markup
result = request.post(url, data, result = request.post(url, data, timeout=kwargs.get('timeout'))
timeout=kwargs.get('timeout'))
if result is True: if result is True:
return result return result
@ -172,12 +165,7 @@ class Bot(TelegramObject):
@log @log
@message @message
def sendMessage(self, def sendMessage(self, chat_id, text, parse_mode=None, disable_web_page_preview=None, **kwargs):
chat_id,
text,
parse_mode=None,
disable_web_page_preview=None,
**kwargs):
"""Use this method to send text messages. """Use this method to send text messages.
Args: Args:
@ -217,8 +205,7 @@ class Bot(TelegramObject):
url = '{0}/sendMessage'.format(self.base_url) url = '{0}/sendMessage'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'text': text}
'text': text}
if parse_mode: if parse_mode:
data['parse_mode'] = parse_mode data['parse_mode'] = parse_mode
@ -229,11 +216,7 @@ class Bot(TelegramObject):
@log @log
@message @message
def forwardMessage(self, def forwardMessage(self, chat_id, from_chat_id, message_id, **kwargs):
chat_id,
from_chat_id,
message_id,
**kwargs):
"""Use this method to forward messages of any kind. """Use this method to forward messages of any kind.
Args: Args:
@ -276,11 +259,7 @@ class Bot(TelegramObject):
@log @log
@message @message
def sendPhoto(self, def sendPhoto(self, chat_id, photo, caption=None, **kwargs):
chat_id,
photo,
caption=None,
**kwargs):
"""Use this method to send photos. """Use this method to send photos.
Args: Args:
@ -318,8 +297,7 @@ class Bot(TelegramObject):
url = '{0}/sendPhoto'.format(self.base_url) url = '{0}/sendPhoto'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'photo': photo}
'photo': photo}
if caption: if caption:
data['caption'] = caption data['caption'] = caption
@ -328,13 +306,7 @@ class Bot(TelegramObject):
@log @log
@message @message
def sendAudio(self, def sendAudio(self, chat_id, audio, duration=None, performer=None, title=None, **kwargs):
chat_id,
audio,
duration=None,
performer=None,
title=None,
**kwargs):
"""Use this method to send audio files, if you want Telegram clients to """Use this method to send audio files, if you want Telegram clients to
display them in the music player. Your audio must be in an .mp3 format. display them in the music player. Your audio must be in an .mp3 format.
On success, the sent Message is returned. Bots can currently send audio On success, the sent Message is returned. Bots can currently send audio
@ -384,8 +356,7 @@ class Bot(TelegramObject):
url = '{0}/sendAudio'.format(self.base_url) url = '{0}/sendAudio'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'audio': audio}
'audio': audio}
if duration: if duration:
data['duration'] = duration data['duration'] = duration
@ -398,12 +369,7 @@ class Bot(TelegramObject):
@log @log
@message @message
def sendDocument(self, def sendDocument(self, chat_id, document, filename=None, caption=None, **kwargs):
chat_id,
document,
filename=None,
caption=None,
**kwargs):
"""Use this method to send general files. """Use this method to send general files.
Args: Args:
@ -444,8 +410,7 @@ class Bot(TelegramObject):
url = '{0}/sendDocument'.format(self.base_url) url = '{0}/sendDocument'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'document': document}
'document': document}
if filename: if filename:
data['filename'] = filename data['filename'] = filename
@ -456,10 +421,7 @@ class Bot(TelegramObject):
@log @log
@message @message
def sendSticker(self, def sendSticker(self, chat_id, sticker, **kwargs):
chat_id,
sticker,
**kwargs):
"""Use this method to send .webp stickers. """Use this method to send .webp stickers.
Args: Args:
@ -494,19 +456,13 @@ class Bot(TelegramObject):
url = '{0}/sendSticker'.format(self.base_url) url = '{0}/sendSticker'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'sticker': sticker}
'sticker': sticker}
return url, data return url, data
@log @log
@message @message
def sendVideo(self, def sendVideo(self, chat_id, video, duration=None, caption=None, **kwargs):
chat_id,
video,
duration=None,
caption=None,
**kwargs):
"""Use this method to send video files, Telegram clients support mp4 """Use this method to send video files, Telegram clients support mp4
videos (other formats may be sent as telegram.Document). videos (other formats may be sent as telegram.Document).
@ -547,8 +503,7 @@ class Bot(TelegramObject):
url = '{0}/sendVideo'.format(self.base_url) url = '{0}/sendVideo'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'video': video}
'video': video}
if duration: if duration:
data['duration'] = duration data['duration'] = duration
@ -559,11 +514,7 @@ class Bot(TelegramObject):
@log @log
@message @message
def sendVoice(self, def sendVoice(self, chat_id, voice, duration=None, **kwargs):
chat_id,
voice,
duration=None,
**kwargs):
"""Use this method to send audio files, if you want Telegram clients to """Use this method to send audio files, if you want Telegram clients to
display the file as a playable voice message. For this to work, your display the file as a playable voice message. For this to work, your
audio must be in an .ogg file encoded with OPUS (other formats may be audio must be in an .ogg file encoded with OPUS (other formats may be
@ -605,8 +556,7 @@ class Bot(TelegramObject):
url = '{0}/sendVoice'.format(self.base_url) url = '{0}/sendVoice'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'voice': voice}
'voice': voice}
if duration: if duration:
data['duration'] = duration data['duration'] = duration
@ -615,11 +565,7 @@ class Bot(TelegramObject):
@log @log
@message @message
def sendLocation(self, def sendLocation(self, chat_id, latitude, longitude, **kwargs):
chat_id,
latitude,
longitude,
**kwargs):
"""Use this method to send point on the map. """Use this method to send point on the map.
Args: Args:
@ -654,22 +600,19 @@ class Bot(TelegramObject):
url = '{0}/sendLocation'.format(self.base_url) url = '{0}/sendLocation'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude}
'latitude': latitude,
'longitude': longitude}
return url, data return url, data
@log @log
@message @message
def sendVenue(self, def sendVenue(
chat_id, self, chat_id,
latitude, latitude,
longitude, longitude,
title, title, address,
address, foursquare_id=None,
foursquare_id=None, **kwargs):
**kwargs):
""" """
Use this method to send information about a venue. Use this method to send information about a venue.
@ -725,12 +668,7 @@ class Bot(TelegramObject):
@log @log
@message @message
def sendContact(self, def sendContact(self, chat_id, phone_number, first_name, last_name=None, **kwargs):
chat_id,
phone_number,
first_name,
last_name=None,
**kwargs):
""" """
Use this method to send phone contacts. Use this method to send phone contacts.
@ -769,9 +707,7 @@ class Bot(TelegramObject):
url = '{0}/sendContact'.format(self.base_url) url = '{0}/sendContact'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'phone_number': phone_number, 'first_name': first_name}
'phone_number': phone_number,
'first_name': first_name}
if last_name: if last_name:
data['last_name'] = last_name data['last_name'] = last_name
@ -780,10 +716,7 @@ class Bot(TelegramObject):
@log @log
@message @message
def sendChatAction(self, def sendChatAction(self, chat_id, action, **kwargs):
chat_id,
action,
**kwargs):
"""Use this method when you need to tell the user that something is """Use this method when you need to tell the user that something is
happening on the bot's side. The status is set for 5 seconds or less happening on the bot's side. The status is set for 5 seconds or less
(when a message arrives from your bot, Telegram clients clear its (when a message arrives from your bot, Telegram clients clear its
@ -805,8 +738,7 @@ class Bot(TelegramObject):
url = '{0}/sendChatAction'.format(self.base_url) url = '{0}/sendChatAction'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'action': action}
'action': action}
return url, data return url, data
@ -861,8 +793,7 @@ class Bot(TelegramObject):
results = [res.to_dict() for res in results] results = [res.to_dict() for res in results]
data = {'inline_query_id': inline_query_id, data = {'inline_query_id': inline_query_id, 'results': results}
'results': results}
if cache_time or cache_time == 0: if cache_time or cache_time == 0:
data['cache_time'] = cache_time data['cache_time'] = cache_time
@ -875,17 +806,12 @@ class Bot(TelegramObject):
if switch_pm_parameter: if switch_pm_parameter:
data['switch_pm_parameter'] = switch_pm_parameter data['switch_pm_parameter'] = switch_pm_parameter
result = request.post(url, data, result = request.post(url, data, timeout=kwargs.get('timeout'))
timeout=kwargs.get('timeout'))
return result return result
@log @log
def getUserProfilePhotos(self, def getUserProfilePhotos(self, user_id, offset=None, limit=100, **kwargs):
user_id,
offset=None,
limit=100,
**kwargs):
"""Use this method to get a list of profile pictures for a user. """Use this method to get a list of profile pictures for a user.
Args: Args:
@ -920,15 +846,12 @@ class Bot(TelegramObject):
if limit: if limit:
data['limit'] = limit data['limit'] = limit
result = request.post(url, data, result = request.post(url, data, timeout=kwargs.get('timeout'))
timeout=kwargs.get('timeout'))
return UserProfilePhotos.de_json(result) return UserProfilePhotos.de_json(result)
@log @log
def getFile(self, def getFile(self, file_id, **kwargs):
file_id,
**kwargs):
"""Use this method to get basic info about a file and prepare it for """Use this method to get basic info about a file and prepare it for
downloading. For the moment, bots can download files of up to 20MB in downloading. For the moment, bots can download files of up to 20MB in
size. size.
@ -954,20 +877,15 @@ class Bot(TelegramObject):
data = {'file_id': file_id} data = {'file_id': file_id}
result = request.post(url, data, result = request.post(url, data, timeout=kwargs.get('timeout'))
timeout=kwargs.get('timeout'))
if result.get('file_path'): if result.get('file_path'):
result['file_path'] = '%s/%s' % (self.base_file_url, result['file_path'] = '%s/%s' % (self.base_file_url, result['file_path'])
result['file_path'])
return File.de_json(result) return File.de_json(result)
@log @log
def kickChatMember(self, def kickChatMember(self, chat_id, user_id, **kwargs):
chat_id,
user_id,
**kwargs):
"""Use this method to kick a user from a group or a supergroup. In the """Use this method to kick a user from a group or a supergroup. In the
case of supergroups, the user will not be able to return to the group case of supergroups, the user will not be able to return to the group
on their own using invite links, etc., unless unbanned first. The bot on their own using invite links, etc., unless unbanned first. The bot
@ -994,19 +912,14 @@ class Bot(TelegramObject):
url = '{0}/kickChatMember'.format(self.base_url) url = '{0}/kickChatMember'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'user_id': user_id}
'user_id': user_id}
result = request.post(url, data, result = request.post(url, data, timeout=kwargs.get('timeout'))
timeout=kwargs.get('timeout'))
return result return result
@log @log
def unbanChatMember(self, def unbanChatMember(self, chat_id, user_id, **kwargs):
chat_id,
user_id,
**kwargs):
"""Use this method to unban a previously kicked user in a supergroup. """Use this method to unban a previously kicked user in a supergroup.
The user will not return to the group automatically, but will be able The user will not return to the group automatically, but will be able
to join via link, etc. The bot must be an administrator in the group to join via link, etc. The bot must be an administrator in the group
@ -1033,20 +946,14 @@ class Bot(TelegramObject):
url = '{0}/unbanChatMember'.format(self.base_url) url = '{0}/unbanChatMember'.format(self.base_url)
data = {'chat_id': chat_id, data = {'chat_id': chat_id, 'user_id': user_id}
'user_id': user_id}
result = request.post(url, data, result = request.post(url, data, timeout=kwargs.get('timeout'))
timeout=kwargs.get('timeout'))
return result return result
@log @log
def answerCallbackQuery(self, def answerCallbackQuery(self, callback_query_id, text=None, show_alert=False, **kwargs):
callback_query_id,
text=None,
show_alert=False,
**kwargs):
"""Use this method to send answers to callback queries sent from """Use this method to send answers to callback queries sent from
inline keyboards. The answer will be displayed to the user as a inline keyboards. The answer will be displayed to the user as a
notification at the top of the chat screen or as an alert. notification at the top of the chat screen or as an alert.
@ -1085,8 +992,7 @@ class Bot(TelegramObject):
if show_alert: if show_alert:
data['show_alert'] = show_alert data['show_alert'] = show_alert
result = request.post(url, data, result = request.post(url, data, timeout=kwargs.get('timeout'))
timeout=kwargs.get('timeout'))
return result return result
@ -1158,8 +1064,7 @@ class Bot(TelegramObject):
else: else:
data['reply_markup'] = reply_markup data['reply_markup'] = reply_markup
result = request.post(url, data, result = request.post(url, data, timeout=kwargs.get('timeout'))
timeout=kwargs.get('timeout'))
return Message.de_json(result) return Message.de_json(result)
@ -1218,11 +1123,10 @@ class Bot(TelegramObject):
@log @log
@message @message
def editMessageReplyMarkup(self, def editMessageReplyMarkup(
chat_id=None, self, chat_id=None,
message_id=None, message_id=None, inline_message_id=None,
inline_message_id=None, **kwargs):
**kwargs):
"""Use this method to edit only the reply markup of messages sent by """Use this method to edit only the reply markup of messages sent by
the bot or via the bot (for inline bots). the bot or via the bot (for inline bots).
@ -1266,11 +1170,7 @@ class Bot(TelegramObject):
return url, data return url, data
@log @log
def getUpdates(self, def getUpdates(self, offset=None, limit=100, timeout=0, network_delay=.2):
offset=None,
limit=100,
timeout=0,
network_delay=.2):
"""Use this method to receive incoming updates using long polling. """Use this method to receive incoming updates using long polling.
Args: Args:
@ -1315,18 +1215,14 @@ class Bot(TelegramObject):
result = request.post(url, data, timeout=urlopen_timeout) result = request.post(url, data, timeout=urlopen_timeout)
if result: if result:
self.logger.debug( self.logger.debug('Getting updates: %s', [u['update_id'] for u in result])
'Getting updates: %s', [u['update_id'] for u in result])
else: else:
self.logger.debug('No new updates found.') self.logger.debug('No new updates found.')
return [Update.de_json(x) for x in result] return [Update.de_json(x) for x in result]
@log @log
def setWebhook(self, def setWebhook(self, webhook_url=None, certificate=None, **kwargs):
webhook_url=None,
certificate=None,
**kwargs):
"""Use this method to specify a url and receive incoming updates via an """Use this method to specify a url and receive incoming updates via an
outgoing webhook. Whenever there is an update for the bot, we will send outgoing webhook. Whenever there is an update for the bot, we will send
an HTTPS POST request to the specified url, containing a an HTTPS POST request to the specified url, containing a
@ -1359,8 +1255,7 @@ class Bot(TelegramObject):
if certificate: if certificate:
data['certificate'] = certificate data['certificate'] = certificate
result = request.post(url, data, result = request.post(url, data, timeout=kwargs.get('timeout'))
timeout=kwargs.get('timeout'))
return result return result
@ -1371,9 +1266,7 @@ class Bot(TelegramObject):
return Bot(**data) return Bot(**data)
def to_dict(self): def to_dict(self):
data = {'id': self.id, data = {'id': self.id, 'username': self.username, 'first_name': self.username}
'username': self.username,
'first_name': self.username}
if self.last_name: if self.last_name:
data['last_name'] = self.last_name data['last_name'] = self.last_name
@ -1381,8 +1274,7 @@ class Bot(TelegramObject):
return data return data
def __reduce__(self): def __reduce__(self):
return (self.__class__, (self.token, return (self.__class__, (self.token, self.base_url.replace(self.token, ''),
self.base_url.replace(self.token, ''),
self.base_file_url.replace(self.token, ''))) self.base_file_url.replace(self.token, '')))
# snake_case (PEP8) aliases # snake_case (PEP8) aliases

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram """This module contains a object that represents a Telegram
CallbackQuery""" CallbackQuery"""
@ -26,11 +25,7 @@ from telegram import TelegramObject, Message, User
class CallbackQuery(TelegramObject): class CallbackQuery(TelegramObject):
"""This object represents a Telegram CallbackQuery.""" """This object represents a Telegram CallbackQuery."""
def __init__(self, def __init__(self, id, from_user, data, **kwargs):
id,
from_user,
data,
**kwargs):
# Required # Required
self.id = id self.id = id
self.from_user = from_user self.from_user = from_user

View file

@ -17,7 +17,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Chat.""" """This module contains a object that represents a Telegram Chat."""
from telegram import TelegramObject from telegram import TelegramObject
@ -43,10 +42,7 @@ class Chat(TelegramObject):
type (Optional[str]): type (Optional[str]):
""" """
def __init__(self, def __init__(self, id, type, **kwargs):
id,
type,
**kwargs):
# Required # Required
self.id = int(id) self.id = int(id)
self.type = type self.type = type

View file

@ -17,7 +17,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram ChatAction.""" """This module contains a object that represents a Telegram ChatAction."""

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" """
This module contains a object that represents a Telegram ChosenInlineResult This module contains a object that represents a Telegram ChosenInlineResult
""" """
@ -42,12 +41,7 @@ class ChosenInlineResult(TelegramObject):
""" """
def __init__(self, def __init__(self, result_id, from_user, query, location=None, inline_message_id=None):
result_id,
from_user,
query,
location=None,
inline_message_id=None):
# Required # Required
self.result_id = result_id self.result_id = result_id
self.from_user = from_user self.from_user = from_user

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Contact.""" """This module contains a object that represents a Telegram Contact."""
from telegram import TelegramObject from telegram import TelegramObject
@ -41,10 +40,7 @@ class Contact(TelegramObject):
user_id (Optional[int]): user_id (Optional[int]):
""" """
def __init__(self, def __init__(self, phone_number, first_name, **kwargs):
phone_number,
first_name,
**kwargs):
# Required # Required
self.phone_number = str(phone_number) self.phone_number = str(phone_number)
self.first_name = first_name self.first_name = first_name

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Document.""" """This module contains a object that represents a Telegram Document."""
from telegram import PhotoSize, TelegramObject from telegram import PhotoSize, TelegramObject
@ -43,9 +42,7 @@ class Document(TelegramObject):
file_size (Optional[int]): file_size (Optional[int]):
""" """
def __init__(self, def __init__(self, file_id, **kwargs):
file_id,
**kwargs):
# Required # Required
self.file_id = str(file_id) self.file_id = str(file_id)
# Optionals # Optionals

View file

@ -1,6 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
# flake8: noqa # flake8: noqa
# pylint: disable=C0103,C0301,R0903 # pylint: disable=C0103,R0903
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016 # Copyright (C) 2015-2016
@ -18,7 +18,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents an Emoji.""" """This module contains a object that represents an Emoji."""
from future.utils import bytes_to_native_str as n from future.utils import bytes_to_native_str as n
@ -163,26 +162,26 @@ class Emoji(object):
SQUARED_SOS = n(b'\xF0\x9F\x86\x98') SQUARED_SOS = n(b'\xF0\x9F\x86\x98')
SQUARED_UP_WITH_EXCLAMATION_MARK = n(b'\xF0\x9F\x86\x99') SQUARED_UP_WITH_EXCLAMATION_MARK = n(b'\xF0\x9F\x86\x99')
SQUARED_VS = n(b'\xF0\x9F\x86\x9A') SQUARED_VS = n(b'\xF0\x9F\x86\x9A')
REGIONAL_INDICATOR_SYMBOL_LETTER_D_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_E \ REGIONAL_INDICATOR_SYMBOL_LETTER_D_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_E = n(
= n(b'\xF0\x9F\x87\xA9\xF0\x9F\x87\xAA') b'\xF0\x9F\x87\xA9\xF0\x9F\x87\xAA')
REGIONAL_INDICATOR_SYMBOL_LETTER_G_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_B \ REGIONAL_INDICATOR_SYMBOL_LETTER_G_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_B = n(
= n(b'\xF0\x9F\x87\xAC\xF0\x9F\x87\xA7') b'\xF0\x9F\x87\xAC\xF0\x9F\x87\xA7')
REGIONAL_INDICATOR_SYMBOL_LETTER_C_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_N \ REGIONAL_INDICATOR_SYMBOL_LETTER_C_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_N = n(
= n(b'\xF0\x9F\x87\xA8\xF0\x9F\x87\xB3') b'\xF0\x9F\x87\xA8\xF0\x9F\x87\xB3')
REGIONAL_INDICATOR_SYMBOL_LETTER_J_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_P \ REGIONAL_INDICATOR_SYMBOL_LETTER_J_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_P = n(
= n(b'\xF0\x9F\x87\xAF\xF0\x9F\x87\xB5') b'\xF0\x9F\x87\xAF\xF0\x9F\x87\xB5')
REGIONAL_INDICATOR_SYMBOL_LETTER_K_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_R \ REGIONAL_INDICATOR_SYMBOL_LETTER_K_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_R = n(
= n(b'\xF0\x9F\x87\xB0\xF0\x9F\x87\xB7') b'\xF0\x9F\x87\xB0\xF0\x9F\x87\xB7')
REGIONAL_INDICATOR_SYMBOL_LETTER_F_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_R \ REGIONAL_INDICATOR_SYMBOL_LETTER_F_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_R = n(
= n(b'\xF0\x9F\x87\xAB\xF0\x9F\x87\xB7') b'\xF0\x9F\x87\xAB\xF0\x9F\x87\xB7')
REGIONAL_INDICATOR_SYMBOL_LETTER_E_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_S \ REGIONAL_INDICATOR_SYMBOL_LETTER_E_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_S = n(
= n(b'\xF0\x9F\x87\xAA\xF0\x9F\x87\xB8') b'\xF0\x9F\x87\xAA\xF0\x9F\x87\xB8')
REGIONAL_INDICATOR_SYMBOL_LETTER_I_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_T \ REGIONAL_INDICATOR_SYMBOL_LETTER_I_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_T = n(
= n(b'\xF0\x9F\x87\xAE\xF0\x9F\x87\xB9') b'\xF0\x9F\x87\xAE\xF0\x9F\x87\xB9')
REGIONAL_INDICATOR_SYMBOL_LETTER_U_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_S \ REGIONAL_INDICATOR_SYMBOL_LETTER_U_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_S = n(
= n(b'\xF0\x9F\x87\xBA\xF0\x9F\x87\xB8') b'\xF0\x9F\x87\xBA\xF0\x9F\x87\xB8')
REGIONAL_INDICATOR_SYMBOL_LETTER_R_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_U \ REGIONAL_INDICATOR_SYMBOL_LETTER_R_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_U = n(
= n(b'\xF0\x9F\x87\xB7\xF0\x9F\x87\xBA') b'\xF0\x9F\x87\xB7\xF0\x9F\x87\xBA')
SQUARED_KATAKANA_KOKO = n(b'\xF0\x9F\x88\x81') SQUARED_KATAKANA_KOKO = n(b'\xF0\x9F\x88\x81')
SQUARED_KATAKANA_SA = n(b'\xF0\x9F\x88\x82') SQUARED_KATAKANA_SA = n(b'\xF0\x9F\x88\x82')
SQUARED_CJK_UNIFIED_IDEOGRAPH_7121 = n(b'\xF0\x9F\x88\x9A') SQUARED_CJK_UNIFIED_IDEOGRAPH_7121 = n(b'\xF0\x9F\x88\x9A')
@ -858,7 +857,8 @@ class Emoji(object):
NO_MOBILE_PHONES = n(b'\xF0\x9F\x93\xB5') NO_MOBILE_PHONES = n(b'\xF0\x9F\x93\xB5')
TWISTED_RIGHTWARDS_ARROWS = n(b'\xF0\x9F\x94\x80') TWISTED_RIGHTWARDS_ARROWS = n(b'\xF0\x9F\x94\x80')
CLOCKWISE_RIGHTWARDS_AND_LEFTWARDS_OPEN_CIRCLE_ARROWS = n(b'\xF0\x9F\x94\x81') CLOCKWISE_RIGHTWARDS_AND_LEFTWARDS_OPEN_CIRCLE_ARROWS = n(b'\xF0\x9F\x94\x81')
CLOCKWISE_RIGHTWARDS_AND_LEFTWARDS_OPEN_CIRCLE_ARROWS_WITH_CIRCLED_ONE_OVERLAY = n(b'\xF0\x9F\x94\x82') CLOCKWISE_RIGHTWARDS_AND_LEFTWARDS_OPEN_CIRCLE_ARROWS_WITH_CIRCLED_ONE_OVERLAY = n(
b'\xF0\x9F\x94\x82')
ANTICLOCKWISE_DOWNWARDS_AND_UPWARDS_OPEN_CIRCLE_ARROWS = n(b'\xF0\x9F\x94\x84') ANTICLOCKWISE_DOWNWARDS_AND_UPWARDS_OPEN_CIRCLE_ARROWS = n(b'\xF0\x9F\x94\x84')
LOW_BRIGHTNESS_SYMBOL = n(b'\xF0\x9F\x94\x85') LOW_BRIGHTNESS_SYMBOL = n(b'\xF0\x9F\x94\x85')
HIGH_BRIGHTNESS_SYMBOL = n(b'\xF0\x9F\x94\x86') HIGH_BRIGHTNESS_SYMBOL = n(b'\xF0\x9F\x94\x86')

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Error.""" """This module contains a object that represents a Telegram Error."""
@ -62,11 +61,13 @@ class TelegramError(Exception):
class Unauthorized(TelegramError): class Unauthorized(TelegramError):
def __init__(self): def __init__(self):
super(Unauthorized, self).__init__('Unauthorized') super(Unauthorized, self).__init__('Unauthorized')
class InvalidToken(TelegramError): class InvalidToken(TelegramError):
def __init__(self): def __init__(self):
super(InvalidToken, self).__init__('Invalid token') super(InvalidToken, self).__init__('Invalid token')
@ -76,5 +77,6 @@ class NetworkError(TelegramError):
class TimedOut(NetworkError): class TimedOut(NetworkError):
def __init__(self): def __init__(self):
super(TimedOut, self).__init__('Timed out') super(TimedOut, self).__init__('Timed out')

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""Extensions over the Telegram Bot API to facilitate bot making""" """Extensions over the Telegram Bot API to facilitate bot making"""
from .dispatcher import Dispatcher from .dispatcher import Dispatcher
@ -34,6 +33,6 @@ from .stringregexhandler import StringRegexHandler
from .typehandler import TypeHandler from .typehandler import TypeHandler
__all__ = ('Dispatcher', 'JobQueue', 'Updater', 'CallbackQueryHandler', __all__ = ('Dispatcher', 'JobQueue', 'Updater', 'CallbackQueryHandler',
'ChosenInlineResultHandler', 'CommandHandler', 'Handler', 'ChosenInlineResultHandler', 'CommandHandler', 'Handler', 'InlineQueryHandler',
'InlineQueryHandler', 'MessageHandler', 'Filters', 'RegexHandler', 'MessageHandler', 'Filters', 'RegexHandler', 'StringCommandHandler',
'StringCommandHandler', 'StringRegexHandler', 'TypeHandler') 'StringRegexHandler', 'TypeHandler')

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the CallbackQueryHandler class """ """ This module contains the CallbackQueryHandler class """
from .handler import Handler from .handler import Handler

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the ChosenInlineResultHandler class """ """ This module contains the ChosenInlineResultHandler class """
from .handler import Handler from .handler import Handler
@ -39,8 +38,7 @@ class ChosenInlineResultHandler(Handler):
""" """
def __init__(self, callback, pass_update_queue=False): def __init__(self, callback, pass_update_queue=False):
super(ChosenInlineResultHandler, self).__init__(callback, super(ChosenInlineResultHandler, self).__init__(callback, pass_update_queue)
pass_update_queue)
def check_update(self, update): def check_update(self, update):
return isinstance(update, Update) and update.chosen_inline_result return isinstance(update, Update) and update.chosen_inline_result

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the CommandHandler class """ """ This module contains the CommandHandler class """
from .handler import Handler from .handler import Handler
@ -44,19 +43,15 @@ class CommandHandler(Handler):
be used to insert updates. Default is ``False`` be used to insert updates. Default is ``False``
""" """
def __init__(self, command, callback, pass_args=False, def __init__(self, command, callback, pass_args=False, pass_update_queue=False):
pass_update_queue=False):
super(CommandHandler, self).__init__(callback, pass_update_queue) super(CommandHandler, self).__init__(callback, pass_update_queue)
self.command = command self.command = command
self.pass_args = pass_args self.pass_args = pass_args
def check_update(self, update): def check_update(self, update):
return (isinstance(update, Update) and return (isinstance(update, Update) and update.message and update.message.text and
update.message and
update.message.text and
update.message.text.startswith('/') and update.message.text.startswith('/') and
update.message.text[1:].split(' ')[0].split('@')[0] == update.message.text[1:].split(' ')[0].split('@')[0] == self.command)
self.command)
def handle_update(self, update, dispatcher): def handle_update(self, update, dispatcher):
optional_args = self.collect_optional_args(dispatcher) optional_args = self.collect_optional_args(dispatcher)

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the Dispatcher class.""" """This module contains the Dispatcher class."""
import logging import logging
@ -92,6 +91,7 @@ class Dispatcher(object):
update_queue (Queue): The synchronized queue that will contain the update_queue (Queue): The synchronized queue that will contain the
updates. updates.
""" """
def __init__(self, bot, update_queue, workers=4, exception_event=None): def __init__(self, bot, update_queue, workers=4, exception_event=None):
self.bot = bot self.bot = bot
self.update_queue = update_queue self.update_queue = update_queue
@ -140,8 +140,7 @@ class Dispatcher(object):
self.logger.debug('orderly stopping') self.logger.debug('orderly stopping')
break break
elif self.__exception_event.is_set(): elif self.__exception_event.is_set():
self.logger.critical( self.logger.critical('stopping due to exception in another thread')
'stopping due to exception in another thread')
break break
continue continue
@ -182,24 +181,21 @@ class Dispatcher(object):
break break
# Dispatch any errors # Dispatch any errors
except TelegramError as te: except TelegramError as te:
self.logger.warn( self.logger.warn('A TelegramError was raised while processing the '
'A TelegramError was raised while processing the ' 'Update.')
'Update.')
try: try:
self.dispatchError(update, te) self.dispatchError(update, te)
except Exception: except Exception:
self.logger.exception( self.logger.exception('An uncaught error was raised while '
'An uncaught error was raised while ' 'handling the error')
'handling the error')
finally: finally:
break break
# Errors should not stop the thread # Errors should not stop the thread
except Exception: except Exception:
self.logger.exception( self.logger.exception('An uncaught error was raised while '
'An uncaught error was raised while ' 'processing the update')
'processing the update')
break break
def add_handler(self, handler, group=DEFAULT_GROUP): def add_handler(self, handler, group=DEFAULT_GROUP):
@ -228,8 +224,7 @@ class Dispatcher(object):
""" """
if not isinstance(handler, Handler): if not isinstance(handler, Handler):
raise TypeError( raise TypeError('handler is not an instance of {0}'.format(Handler.__name__))
'handler is not an instance of {0}'.format(Handler.__name__))
if not isinstance(group, int): if not isinstance(group, int):
raise TypeError('group is not int') raise TypeError('group is not int')
@ -293,5 +288,5 @@ class Dispatcher(object):
addHandler = deprecate(add_handler, m + "AddHandler", m + "add_handler") addHandler = deprecate(add_handler, m + "AddHandler", m + "add_handler")
removeHandler = deprecate(remove_handler, m + "removeHandler", m + "remove_handler") removeHandler = deprecate(remove_handler, m + "removeHandler", m + "remove_handler")
addErrorHandler = deprecate(add_error_handler, m + "addErrorHandler", m + "add_error_handler") addErrorHandler = deprecate(add_error_handler, m + "addErrorHandler", m + "add_error_handler")
removeErrorHandler = deprecate(remove_error_handler, removeErrorHandler = deprecate(remove_error_handler, m + "removeErrorHandler",
m + "removeErrorHandler", m + "remove_error_handler") m + "remove_error_handler")

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the base class for handlers as used by the """ This module contains the base class for handlers as used by the
Dispatcher """ Dispatcher """
@ -85,5 +84,5 @@ class Handler(object):
m = "telegram.Handler." m = "telegram.Handler."
checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update") checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update")
handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update") handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update")
collectOptionalArgs = deprecate(collect_optional_args, collectOptionalArgs = deprecate(collect_optional_args, m + "collectOptionalArgs",
m + "collectOptionalArgs", m + "collect_optional_args") m + "collect_optional_args")

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the InlineQueryHandler class """ """ This module contains the InlineQueryHandler class """
from .handler import Handler from .handler import Handler

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the class JobQueue.""" """This module contains the class JobQueue."""
import logging import logging
@ -50,12 +49,7 @@ class JobQueue(object):
self.__lock = Lock() self.__lock = Lock()
self.running = False self.running = False
def put(self, def put(self, run, interval, repeat=True, next_t=None, prevent_autostart=False):
run,
interval,
repeat=True,
next_t=None,
prevent_autostart=False):
""" """
Queue a new job. If the JobQueue is not running, it will be started. Queue a new job. If the JobQueue is not running, it will be started.
@ -123,8 +117,7 @@ class JobQueue(object):
if not self.running: if not self.running:
self.running = True self.running = True
self.__lock.release() self.__lock.release()
job_queue_thread = Thread(target=self._start, job_queue_thread = Thread(target=self._start, name="job_queue")
name="job_queue")
job_queue_thread.start() job_queue_thread.start()
self.logger.debug('Job Queue thread started') self.logger.debug('Job Queue thread started')
else: else:

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the MessageHandler class """ """ This module contains the MessageHandler class """
from .handler import Handler from .handler import Handler
@ -76,18 +75,15 @@ class Filters(object):
@staticmethod @staticmethod
def status_update(update): def status_update(update):
return bool( # yapf: disable
update.message.new_chat_member or # https://github.com/google/yapf/issues/252
update.message.left_chat_member or return bool(update.message.new_chat_member or update.message.left_chat_member or
update.message.new_chat_title or update.message.new_chat_title or update.message.new_chat_photo or
update.message.new_chat_photo or update.message.delete_chat_photo or update.message.group_chat_created or
update.message.delete_chat_photo or update.message.supergroup_chat_created or
update.message.group_chat_created or update.message.channel_chat_created or update.message.migrate_to_chat_id or
update.message.supergroup_chat_created or update.message.migrate_from_chat_id or update.message.pinned_message)
update.message.channel_chat_created or # yapf: enable
update.message.migrate_to_chat_id or
update.message.migrate_from_chat_id or
update.message.pinned_message)
class MessageHandler(Handler): class MessageHandler(Handler):

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the RegexHandler class """ """ This module contains the RegexHandler class """
import re import re
@ -51,8 +50,12 @@ class RegexHandler(Handler):
be used to insert updates. Default is ``False`` be used to insert updates. Default is ``False``
""" """
def __init__(self, pattern, callback, pass_groups=False, def __init__(self,
pass_groupdict=False, pass_update_queue=False): pattern,
callback,
pass_groups=False,
pass_groupdict=False,
pass_update_queue=False):
super(RegexHandler, self).__init__(callback, pass_update_queue) super(RegexHandler, self).__init__(callback, pass_update_queue)
if isinstance(pattern, string_types): if isinstance(pattern, string_types):
@ -63,9 +66,7 @@ class RegexHandler(Handler):
self.pass_groupdict = pass_groupdict self.pass_groupdict = pass_groupdict
def check_update(self, update): def check_update(self, update):
if (isinstance(update, Update) and if (isinstance(update, Update) and update.message and update.message.text):
update.message and
update.message.text):
match = re.match(self.pattern, update.message.text) match = re.match(self.pattern, update.message.text)
return bool(match) return bool(match)
else: else:

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the StringCommandHandler class """ """ This module contains the StringCommandHandler class """
from .handler import Handler from .handler import Handler
@ -42,15 +41,13 @@ class StringCommandHandler(Handler):
be used to insert updates. Default is ``False`` be used to insert updates. Default is ``False``
""" """
def __init__(self, command, callback, pass_args=False, def __init__(self, command, callback, pass_args=False, pass_update_queue=False):
pass_update_queue=False):
super(StringCommandHandler, self).__init__(callback, pass_update_queue) super(StringCommandHandler, self).__init__(callback, pass_update_queue)
self.command = command self.command = command
self.pass_args = pass_args self.pass_args = pass_args
def check_update(self, update): def check_update(self, update):
return (isinstance(update, str) and return (isinstance(update, str) and update.startswith('/') and
update.startswith('/') and
update[1:].split(' ')[0] == self.command) update[1:].split(' ')[0] == self.command)
def handle_update(self, update, dispatcher): def handle_update(self, update, dispatcher):

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the StringRegexHandler class """ """ This module contains the StringRegexHandler class """
import re import re
@ -50,8 +49,12 @@ class StringRegexHandler(Handler):
be used to insert updates. Default is ``False`` be used to insert updates. Default is ``False``
""" """
def __init__(self, pattern, callback, pass_groups=False, def __init__(self,
pass_groupdict=False, pass_update_queue=False): pattern,
callback,
pass_groups=False,
pass_groupdict=False,
pass_update_queue=False):
super(StringRegexHandler, self).__init__(callback, pass_update_queue) super(StringRegexHandler, self).__init__(callback, pass_update_queue)
if isinstance(pattern, string_types): if isinstance(pattern, string_types):
@ -62,8 +65,7 @@ class StringRegexHandler(Handler):
self.pass_groupdict = pass_groupdict self.pass_groupdict = pass_groupdict
def check_update(self, update): def check_update(self, update):
return isinstance(update, string_types) and bool( return isinstance(update, string_types) and bool(re.match(self.pattern, update))
re.match(self.pattern, update))
def handle_update(self, update, dispatcher): def handle_update(self, update, dispatcher):
optional_args = self.collect_optional_args(dispatcher) optional_args = self.collect_optional_args(dispatcher)

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the TypeHandler class """ """ This module contains the TypeHandler class """
from .handler import Handler from .handler import Handler

View file

@ -16,8 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the class Updater, which tries to make creating """This module contains the class Updater, which tries to make creating
Telegram bots intuitive.""" Telegram bots intuitive."""
@ -85,8 +83,7 @@ class Updater(object):
self.update_queue = Queue() self.update_queue = Queue()
self.job_queue = JobQueue(self.bot, job_queue_tick_interval) self.job_queue = JobQueue(self.bot, job_queue_tick_interval)
self.__exception_event = Event() self.__exception_event = Event()
self.dispatcher = Dispatcher(self.bot, self.update_queue, workers, self.dispatcher = Dispatcher(self.bot, self.update_queue, workers, self.__exception_event)
self.__exception_event)
self.last_update_id = 0 self.last_update_id = 0
self.logger = logging.getLogger(__name__) self.logger = logging.getLogger(__name__)
self.running = False self.running = False
@ -97,8 +94,7 @@ class Updater(object):
""":type: list[Thread]""" """:type: list[Thread]"""
def _init_thread(self, target, name, *args, **kwargs): def _init_thread(self, target, name, *args, **kwargs):
thr = Thread(target=self._thread_wrapper, name=name, thr = Thread(target=self._thread_wrapper, name=name, args=(target,) + args, kwargs=kwargs)
args=(target,) + args, kwargs=kwargs)
thr.start() thr.start()
self.__threads.append(thr) self.__threads.append(thr)
@ -113,8 +109,12 @@ class Updater(object):
raise raise
self.logger.debug('{0} - ended'.format(thr_name)) self.logger.debug('{0} - ended'.format(thr_name))
def start_polling(self, poll_interval=0.0, timeout=10, network_delay=2, def start_polling(self,
clean=False, bootstrap_retries=0): poll_interval=0.0,
timeout=10,
network_delay=2,
clean=False,
bootstrap_retries=0):
""" """
Starts polling updates from Telegram. Starts polling updates from Telegram.
@ -143,9 +143,8 @@ class Updater(object):
# Create & start threads # Create & start threads
self._init_thread(self.dispatcher.start, "dispatcher") self._init_thread(self.dispatcher.start, "dispatcher")
self._init_thread(self._start_polling, "updater", self._init_thread(self._start_polling, "updater", poll_interval, timeout,
poll_interval, timeout, network_delay, network_delay, bootstrap_retries, clean)
bootstrap_retries, clean)
# Return the update queue so the main thread can insert updates # Return the update queue so the main thread can insert updates
return self.update_queue return self.update_queue
@ -195,15 +194,13 @@ class Updater(object):
# Create & start threads # Create & start threads
self._init_thread(self.dispatcher.start, "dispatcher"), self._init_thread(self.dispatcher.start, "dispatcher"),
self._init_thread(self._start_webhook, "updater", listen, self._init_thread(self._start_webhook, "updater", listen, port, url_path, cert,
port, url_path, cert, key, bootstrap_retries, key, bootstrap_retries, clean, webhook_url)
clean, webhook_url)
# Return the update queue so the main thread can insert updates # Return the update queue so the main thread can insert updates
return self.update_queue return self.update_queue
def _start_polling(self, poll_interval, timeout, network_delay, def _start_polling(self, poll_interval, timeout, network_delay, bootstrap_retries, clean):
bootstrap_retries, clean):
""" """
Thread target of thread 'updater'. Runs in background, pulls Thread target of thread 'updater'. Runs in background, pulls
updates from Telegram and inserts them in the update queue of the updates from Telegram and inserts them in the update queue of the
@ -221,8 +218,7 @@ class Updater(object):
timeout=timeout, timeout=timeout,
network_delay=network_delay) network_delay=network_delay)
except TelegramError as te: except TelegramError as te:
self.logger.error( self.logger.error("Error while getting Updates: {0}".format(te))
"Error while getting Updates: {0}".format(te))
# Put the error into the update queue and let the Dispatcher # Put the error into the update queue and let the Dispatcher
# broadcast it # broadcast it
@ -256,16 +252,15 @@ class Updater(object):
current_interval = 30 current_interval = 30
return current_interval return current_interval
def _start_webhook(self, listen, port, url_path, cert, key, def _start_webhook(self, listen, port, url_path, cert, key, bootstrap_retries, clean,
bootstrap_retries, clean, webhook_url): webhook_url):
self.logger.debug('Updater thread started') self.logger.debug('Updater thread started')
use_ssl = cert is not None and key is not None use_ssl = cert is not None and key is not None
if not url_path.startswith('/'): if not url_path.startswith('/'):
url_path = '/{0}'.format(url_path) url_path = '/{0}'.format(url_path)
# Create and start server # Create and start server
self.httpd = WebhookServer((listen, port), WebhookHandler, self.httpd = WebhookServer((listen, port), WebhookHandler, self.update_queue, url_path)
self.update_queue, url_path)
if use_ssl: if use_ssl:
self._check_ssl_cert(cert, key) self._check_ssl_cert(cert, key)
@ -274,8 +269,10 @@ class Updater(object):
if not webhook_url: if not webhook_url:
webhook_url = self._gen_webhook_url(listen, port, url_path) webhook_url = self._gen_webhook_url(listen, port, url_path)
self._bootstrap(max_retries=bootstrap_retries, clean=clean, self._bootstrap(max_retries=bootstrap_retries,
webhook_url=webhook_url, cert=open(cert, 'rb')) clean=clean,
webhook_url=webhook_url,
cert=open(cert, 'rb'))
elif clean: elif clean:
self.logger.warning("cleaning updates is not supported if " self.logger.warning("cleaning updates is not supported if "
"SSL-termination happens elsewhere; skipping") "SSL-termination happens elsewhere; skipping")
@ -285,10 +282,10 @@ class Updater(object):
def _check_ssl_cert(self, cert, key): def _check_ssl_cert(self, cert, key):
# Check SSL-Certificate with openssl, if possible # Check SSL-Certificate with openssl, if possible
try: try:
exit_code = subprocess.call(["openssl", "x509", "-text", exit_code = subprocess.call(
"-noout", "-in", cert], ["openssl", "x509", "-text", "-noout", "-in", cert],
stdout=open(os.devnull, 'wb'), stdout=open(os.devnull, 'wb'),
stderr=subprocess.STDOUT) stderr=subprocess.STDOUT)
except OSError: except OSError:
exit_code = 0 exit_code = 0
if exit_code is 0: if exit_code is 0:
@ -305,10 +302,7 @@ class Updater(object):
@staticmethod @staticmethod
def _gen_webhook_url(listen, port, url_path): def _gen_webhook_url(listen, port, url_path):
return 'https://{listen}:{port}{path}'.format( return 'https://{listen}:{port}{path}'.format(listen=listen, port=port, path=url_path)
listen=listen,
port=port,
path=url_path)
def _bootstrap(self, max_retries, clean, webhook_url, cert=None): def _bootstrap(self, max_retries, clean, webhook_url, cert=None):
retries = 0 retries = 0
@ -320,8 +314,7 @@ class Updater(object):
self.bot.setWebhook(webhook_url='') self.bot.setWebhook(webhook_url='')
self._clean_updates() self._clean_updates()
self.bot.setWebhook(webhook_url=webhook_url, self.bot.setWebhook(webhook_url=webhook_url, certificate=cert)
certificate=cert)
except (Unauthorized, InvalidToken): except (Unauthorized, InvalidToken):
raise raise
except TelegramError: except TelegramError:
@ -365,10 +358,9 @@ class Updater(object):
def _stop_httpd(self): def _stop_httpd(self):
if self.httpd: if self.httpd:
self.logger.debug( self.logger.debug('Waiting for current webhook connection to be '
'Waiting for current webhook connection to be ' 'closed... Send a Telegram message to the bot to exit '
'closed... Send a Telegram message to the bot to exit ' 'immediately.')
'immediately.')
self.httpd.shutdown() self.httpd.shutdown()
self.httpd = None self.httpd = None
@ -381,16 +373,13 @@ class Updater(object):
threads = list(dispatcher.async_threads) threads = list(dispatcher.async_threads)
total = len(threads) total = len(threads)
for i, thr in enumerate(threads): for i, thr in enumerate(threads):
self.logger.debug( self.logger.debug('Waiting for async thread {0}/{1} to end'.format(i, total))
'Waiting for async thread {0}/{1} to end'.format(i, total))
thr.join() thr.join()
self.logger.debug( self.logger.debug('async thread {0}/{1} has ended'.format(i, total))
'async thread {0}/{1} has ended'.format(i, total))
def _join_threads(self): def _join_threads(self):
for thr in self.__threads: for thr in self.__threads:
self.logger.debug( self.logger.debug('Waiting for {0} thread to end'.format(thr.name))
'Waiting for {0} thread to end'.format(thr.name))
thr.join() thr.join()
self.logger.debug('{0} thread has ended'.format(thr.name)) self.logger.debug('{0} thread has ended'.format(thr.name))
self.__threads = [] self.__threads = []

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram File.""" """This module contains a object that represents a Telegram File."""
from os.path import basename from os.path import basename
@ -42,9 +41,7 @@ class File(TelegramObject):
file_path (Optional[str]): file_path (Optional[str]):
""" """
def __init__(self, def __init__(self, file_id, **kwargs):
file_id,
**kwargs):
# Required # Required
self.file_id = str(file_id) self.file_id = str(file_id)
# Optionals # Optionals
@ -65,8 +62,7 @@ class File(TelegramObject):
return File(**data) return File(**data)
def download(self, def download(self, custom_path=None):
custom_path=None):
""" """
Args: Args:
custom_path (str): custom_path (str):

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram ForceReply.""" """This module contains a object that represents a Telegram ForceReply."""
from telegram import ReplyMarkup from telegram import ReplyMarkup
@ -37,9 +36,7 @@ class ForceReply(ReplyMarkup):
selective (Optional[bool]): selective (Optional[bool]):
""" """
def __init__(self, def __init__(self, force_reply=True, **kwargs):
force_reply=True,
**kwargs):
# Required # Required
self.force_reply = bool(force_reply) self.force_reply = bool(force_reply)
# Optionals # Optionals

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram """This module contains a object that represents a Telegram
InlineKeyboardButton""" InlineKeyboardButton"""
@ -43,9 +42,7 @@ class InlineKeyboardButton(TelegramObject):
""" """
def __init__(self, def __init__(self, text, **kwargs):
text,
**kwargs):
# Required # Required
self.text = text self.text = text
@ -70,7 +67,6 @@ class InlineKeyboardButton(TelegramObject):
inline_keyboards = list() inline_keyboards = list()
for inline_keyboard in data: for inline_keyboard in data:
inline_keyboards.append(InlineKeyboardButton. inline_keyboards.append(InlineKeyboardButton.de_json(inline_keyboard))
de_json(inline_keyboard))
return inline_keyboards return inline_keyboards

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram """This module contains a object that represents a Telegram
InlineKeyboardMarkup""" InlineKeyboardMarkup"""
@ -34,8 +33,7 @@ class InlineKeyboardMarkup(ReplyMarkup):
""" """
def __init__(self, def __init__(self, inline_keyboard):
inline_keyboard):
# Required # Required
self.inline_keyboard = inline_keyboard self.inline_keyboard = inline_keyboard
@ -46,9 +44,8 @@ class InlineKeyboardMarkup(ReplyMarkup):
if not data: if not data:
return None return None
data['inline_keyboard'] = \ data['inline_keyboard'] = [InlineKeyboardButton.de_list(inline_keyboard)
[InlineKeyboardButton.de_list(inline_keyboard) for inline_keyboard for inline_keyboard in data['inline_keyboard']]
in data['inline_keyboard']]
return InlineKeyboardMarkup(**data) return InlineKeyboardMarkup(**data)
@ -57,7 +54,6 @@ class InlineKeyboardMarkup(ReplyMarkup):
data['inline_keyboard'] = [] data['inline_keyboard'] = []
for inline_keyboard in self.inline_keyboard: for inline_keyboard in self.inline_keyboard:
data['inline_keyboard'].append( data['inline_keyboard'].append([x.to_dict() for x in inline_keyboard])
[x.to_dict() for x in inline_keyboard])
return data return data

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram InlineQuery""" """This module contains a object that represents a Telegram InlineQuery"""
from telegram import TelegramObject, User, Location from telegram import TelegramObject, User, Location
@ -45,12 +44,7 @@ class InlineQuery(TelegramObject):
location (optional[:class:`telegram.Location`]): location (optional[:class:`telegram.Location`]):
""" """
def __init__(self, def __init__(self, id, from_user, query, offset, **kwargs):
id,
from_user,
query,
offset,
**kwargs):
# Required # Required
self.id = id self.id = id
self.from_user = from_user self.from_user = from_user

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResult""" InlineQueryResult"""
@ -36,9 +35,7 @@ class InlineQueryResult(TelegramObject):
""" """
def __init__(self, def __init__(self, type, id):
type,
id):
# Required # Required
self.type = str(type) self.type = str(type)
self.id = str(id) self.id = str(id)

View file

@ -16,12 +16,10 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultArticle""" InlineQueryResultArticle"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultArticle(InlineQueryResult): class InlineQueryResultArticle(InlineQueryResult):
@ -97,12 +95,10 @@ class InlineQueryResultArticle(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultArticle, data = super(InlineQueryResultArticle, InlineQueryResultArticle).de_json(data)
InlineQueryResultArticle).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultArticle(**data) return InlineQueryResultArticle(**data)

View file

@ -16,12 +16,10 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultAudio""" InlineQueryResultAudio"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultAudio(InlineQueryResult): class InlineQueryResultAudio(InlineQueryResult):
@ -59,6 +57,7 @@ class InlineQueryResultAudio(InlineQueryResult):
input_message_content (Optional[ input_message_content (Optional[
:class:`telegram.input_message_content`]): :class:`telegram.input_message_content`]):
""" """
def __init__(self, def __init__(self,
id, id,
audio_url, audio_url,
@ -86,12 +85,10 @@ class InlineQueryResultAudio(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultAudio, data = super(InlineQueryResultAudio, InlineQueryResultAudio).de_json(data)
InlineQueryResultAudio).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultAudio(**data) return InlineQueryResultAudio(**data)

View file

@ -16,12 +16,10 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultCachedAudio""" InlineQueryResultCachedAudio"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultCachedAudio(InlineQueryResult): class InlineQueryResultCachedAudio(InlineQueryResult):
@ -54,12 +52,8 @@ class InlineQueryResultCachedAudio(InlineQueryResult):
input_message_content (Optional[ input_message_content (Optional[
:class:`telegram.input_message_content`]): :class:`telegram.input_message_content`]):
""" """
def __init__(self,
id, def __init__(self, id, audio_file_id, reply_markup=None, input_message_content=None, **kwargs):
audio_file_id,
reply_markup=None,
input_message_content=None,
**kwargs):
# Required # Required
super(InlineQueryResultCachedAudio, self).__init__('audio', id) super(InlineQueryResultCachedAudio, self).__init__('audio', id)
self.audio_file_id = audio_file_id self.audio_file_id = audio_file_id
@ -72,12 +66,10 @@ class InlineQueryResultCachedAudio(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultCachedAudio, data = super(InlineQueryResultCachedAudio, InlineQueryResultCachedAudio).de_json(data)
InlineQueryResultCachedAudio).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultCachedAudio(**data) return InlineQueryResultCachedAudio(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultCachedDocument""" InlineQueryResultCachedDocument"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultCachedDocument(InlineQueryResult): class InlineQueryResultCachedDocument(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
title, title,
@ -54,9 +53,8 @@ class InlineQueryResultCachedDocument(InlineQueryResult):
data = super(InlineQueryResultCachedDocument, data = super(InlineQueryResultCachedDocument,
InlineQueryResultCachedDocument).de_json(data) InlineQueryResultCachedDocument).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultCachedDocument(**data) return InlineQueryResultCachedDocument(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultCachedGif""" InlineQueryResultCachedGif"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultCachedGif(InlineQueryResult): class InlineQueryResultCachedGif(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
gif_file_id, gif_file_id,
@ -49,12 +48,10 @@ class InlineQueryResultCachedGif(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultCachedGif, data = super(InlineQueryResultCachedGif, InlineQueryResultCachedGif).de_json(data)
InlineQueryResultCachedGif).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultCachedGif(**data) return InlineQueryResultCachedGif(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultMpeg4Gif""" InlineQueryResultMpeg4Gif"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultCachedMpeg4Gif(InlineQueryResult): class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
mpeg4_file_id, mpeg4_file_id,
@ -52,9 +51,8 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
data = super(InlineQueryResultCachedMpeg4Gif, data = super(InlineQueryResultCachedMpeg4Gif,
InlineQueryResultCachedMpeg4Gif).de_json(data) InlineQueryResultCachedMpeg4Gif).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultCachedMpeg4Gif(**data) return InlineQueryResultCachedMpeg4Gif(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultPhoto""" InlineQueryResultPhoto"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultCachedPhoto(InlineQueryResult): class InlineQueryResultCachedPhoto(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
photo_file_id, photo_file_id,
@ -52,12 +51,10 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultCachedPhoto, data = super(InlineQueryResultCachedPhoto, InlineQueryResultCachedPhoto).de_json(data)
InlineQueryResultCachedPhoto).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultCachedPhoto(**data) return InlineQueryResultCachedPhoto(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultCachedSticker""" InlineQueryResultCachedSticker"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultCachedSticker(InlineQueryResult): class InlineQueryResultCachedSticker(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
sticker_file_id, sticker_file_id,
@ -43,12 +42,10 @@ class InlineQueryResultCachedSticker(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultCachedSticker, data = super(InlineQueryResultCachedSticker, InlineQueryResultCachedSticker).de_json(data)
InlineQueryResultCachedSticker).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultCachedSticker(**data) return InlineQueryResultCachedSticker(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultCachedVideo""" InlineQueryResultCachedVideo"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultCachedVideo(InlineQueryResult): class InlineQueryResultCachedVideo(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
video_file_id, video_file_id,
@ -51,12 +50,10 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultCachedVideo, data = super(InlineQueryResultCachedVideo, InlineQueryResultCachedVideo).de_json(data)
InlineQueryResultCachedVideo).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultCachedVideo(**data) return InlineQueryResultCachedVideo(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultCachedVoice""" InlineQueryResultCachedVoice"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultCachedVoice(InlineQueryResult): class InlineQueryResultCachedVoice(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
voice_file_id, voice_file_id,
@ -48,12 +47,10 @@ class InlineQueryResultCachedVoice(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultCachedVoice, data = super(InlineQueryResultCachedVoice, InlineQueryResultCachedVoice).de_json(data)
InlineQueryResultCachedVoice).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultCachedVoice(**data) return InlineQueryResultCachedVoice(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultContact""" InlineQueryResultContact"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultContact(InlineQueryResult): class InlineQueryResultContact(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
phone_number, phone_number,
@ -57,12 +56,10 @@ class InlineQueryResultContact(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultContact, data = super(InlineQueryResultContact, InlineQueryResultContact).de_json(data)
InlineQueryResultContact).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultContact(**data) return InlineQueryResultContact(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultDocument""" InlineQueryResultDocument"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultDocument(InlineQueryResult): class InlineQueryResultDocument(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
document_url, document_url,
@ -62,12 +61,10 @@ class InlineQueryResultDocument(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultDocument, data = super(InlineQueryResultDocument, InlineQueryResultDocument).de_json(data)
InlineQueryResultDocument).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultDocument(**data) return InlineQueryResultDocument(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultGif""" InlineQueryResultGif"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultGif(InlineQueryResult): class InlineQueryResultGif(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
gif_url, gif_url,
@ -58,12 +57,10 @@ class InlineQueryResultGif(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultGif, data = super(InlineQueryResultGif, InlineQueryResultGif).de_json(data)
InlineQueryResultGif).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultGif(**data) return InlineQueryResultGif(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultLocation""" InlineQueryResultLocation"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultLocation(InlineQueryResult): class InlineQueryResultLocation(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
latitude, latitude,
@ -56,12 +55,10 @@ class InlineQueryResultLocation(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultLocation, data = super(InlineQueryResultLocation, InlineQueryResultLocation).de_json(data)
InlineQueryResultLocation).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultLocation(**data) return InlineQueryResultLocation(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultMpeg4Gif""" InlineQueryResultMpeg4Gif"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultMpeg4Gif(InlineQueryResult): class InlineQueryResultMpeg4Gif(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
mpeg4_url, mpeg4_url,
@ -58,12 +57,10 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultMpeg4Gif, data = super(InlineQueryResultMpeg4Gif, InlineQueryResultMpeg4Gif).de_json(data)
InlineQueryResultMpeg4Gif).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultMpeg4Gif(**data) return InlineQueryResultMpeg4Gif(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultPhoto""" InlineQueryResultPhoto"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultPhoto(InlineQueryResult): class InlineQueryResultPhoto(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
photo_url, photo_url,
@ -60,12 +59,10 @@ class InlineQueryResultPhoto(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultPhoto, data = super(InlineQueryResultPhoto, InlineQueryResultPhoto).de_json(data)
InlineQueryResultPhoto).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultPhoto(**data) return InlineQueryResultPhoto(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultVenue""" InlineQueryResultVenue"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultVenue(InlineQueryResult): class InlineQueryResultVenue(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
latitude, latitude,
@ -62,12 +61,10 @@ class InlineQueryResultVenue(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultVenue, data = super(InlineQueryResultVenue, InlineQueryResultVenue).de_json(data)
InlineQueryResultVenue).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultVenue(**data) return InlineQueryResultVenue(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultVideo""" InlineQueryResultVideo"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultVideo(InlineQueryResult): class InlineQueryResultVideo(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
video_url, video_url,
@ -65,12 +64,10 @@ class InlineQueryResultVideo(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultVideo, data = super(InlineQueryResultVideo, InlineQueryResultVideo).de_json(data)
InlineQueryResultVideo).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultVideo(**data) return InlineQueryResultVideo(**data)

View file

@ -16,15 +16,14 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InlineQueryResultVoice""" InlineQueryResultVoice"""
from telegram import InlineQueryResult, InlineKeyboardMarkup, \ from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent
InputMessageContent
class InlineQueryResultVoice(InlineQueryResult): class InlineQueryResultVoice(InlineQueryResult):
def __init__(self, def __init__(self,
id, id,
voice_url, voice_url,
@ -49,12 +48,10 @@ class InlineQueryResultVoice(InlineQueryResult):
@staticmethod @staticmethod
def de_json(data): def de_json(data):
data = super(InlineQueryResultVoice, data = super(InlineQueryResultVoice, InlineQueryResultVoice).de_json(data)
InlineQueryResultVoice).de_json(data)
data['reply_markup'] = InlineKeyboardMarkup.de_json( data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
data.get('reply_markup')) data['input_message_content'] = InputMessageContent.de_json(data.get(
data['input_message_content'] = InputMessageContent.de_json( 'input_message_content'))
data.get('input_message_content'))
return InlineQueryResultVoice(**data) return InlineQueryResultVoice(**data)

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InputContactMessageContent""" InputContactMessageContent"""
@ -26,10 +25,7 @@ from telegram import InputMessageContent
class InputContactMessageContent(InputMessageContent): class InputContactMessageContent(InputMessageContent):
"""Base class for Telegram InputContactMessageContent Objects""" """Base class for Telegram InputContactMessageContent Objects"""
def __init__(self, def __init__(self, phone_number, first_name, last_name=None):
phone_number,
first_name,
last_name=None):
# Required # Required
self.phone_number = phone_number self.phone_number = phone_number
self.first_name = first_name self.first_name = first_name

View file

@ -17,7 +17,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram InputFile.""" """This module contains a object that represents a Telegram InputFile."""
try: try:
@ -37,15 +36,13 @@ from future.moves.urllib.request import urlopen
from telegram import TelegramError from telegram import TelegramError
DEFAULT_MIME_TYPE = 'application/octet-stream' DEFAULT_MIME_TYPE = 'application/octet-stream'
USER_AGENT = 'Python Telegram Bot' \ USER_AGENT = 'Python Telegram Bot (https://github.com/python-telegram-bot/python-telegram-bot)'
' (https://github.com/python-telegram-bot/python-telegram-bot)'
class InputFile(object): class InputFile(object):
"""This object represents a Telegram InputFile.""" """This object represents a Telegram InputFile."""
def __init__(self, def __init__(self, data):
data):
self.data = data self.data = data
self.boundary = choose_boundary() self.boundary = choose_boundary()
@ -87,16 +84,14 @@ class InputFile(object):
# pylint: disable=E1101 # pylint: disable=E1101
self.filename = os.path.basename(self.input_file.name) self.filename = os.path.basename(self.input_file.name)
elif from_url: elif from_url:
self.filename = os.path.basename(self.input_file.url) \ self.filename = os.path.basename(self.input_file.url).split('?')[0].split('&')[0]
.split('?')[0].split('&')[0]
try: try:
self.mimetype = InputFile.is_image(self.input_file_content) self.mimetype = InputFile.is_image(self.input_file_content)
if not self.filename or '.' not in self.filename: if not self.filename or '.' not in self.filename:
self.filename = self.mimetype.replace('/', '.') self.filename = self.mimetype.replace('/', '.')
except TelegramError: except TelegramError:
self.mimetype = mimetypes.guess_type(self.filename)[0] or \ self.mimetype = mimetypes.guess_type(self.filename)[0] or DEFAULT_MIME_TYPE
DEFAULT_MIME_TYPE
@property @property
def headers(self): def headers(self):
@ -104,8 +99,7 @@ class InputFile(object):
Returns: Returns:
str: str:
""" """
return {'User-agent': USER_AGENT, return {'User-agent': USER_AGENT, 'Content-type': self.content_type}
'Content-type': self.content_type}
@property @property
def content_type(self): def content_type(self):
@ -126,21 +120,14 @@ class InputFile(object):
# Add data fields # Add data fields
for name, value in self.data.items(): for name, value in self.data.items():
form.extend([ form.extend([
form_boundary, form_boundary, 'Content-Disposition: form-data; name="%s"' % name, '', str(value)
'Content-Disposition: form-data; name="%s"' % name,
'',
str(value)
]) ])
# Add input_file to upload # Add input_file to upload
form.extend([ form.extend([
form_boundary, form_boundary, 'Content-Disposition: form-data; name="%s"; filename="%s"' % (
'Content-Disposition: form-data; name="%s"; filename="%s"' % (
self.input_name, self.filename self.input_name, self.filename
), ), 'Content-Type: %s' % self.mimetype, '', self.input_file_content
'Content-Type: %s' % self.mimetype,
'',
self.input_file_content
]) ])
form.append('--' + self.boundary + '--') form.append('--' + self.boundary + '--')
@ -193,14 +180,12 @@ class InputFile(object):
bool bool
""" """
if data: if data:
file_types = ['audio', 'document', 'photo', 'sticker', 'video', file_types = ['audio', 'document', 'photo', 'sticker', 'video', 'voice', 'certificate']
'voice', 'certificate']
file_type = [i for i in list(data.keys()) if i in file_types] file_type = [i for i in list(data.keys()) if i in file_types]
if file_type: if file_type:
file_content = data[file_type[0]] file_content = data[file_type[0]]
return hasattr(file_content, 'read') or str( return hasattr(file_content, 'read') or str(file_content).startswith('http')
file_content).startswith('http')
return False return False

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InputLocationMessageContent""" InputLocationMessageContent"""
@ -26,9 +25,7 @@ from telegram import InputMessageContent
class InputLocationMessageContent(InputMessageContent): class InputLocationMessageContent(InputMessageContent):
"""Base class for Telegram InputLocationMessageContent Objects""" """Base class for Telegram InputLocationMessageContent Objects"""
def __init__(self, def __init__(self, latitude, longitude):
latitude,
longitude):
# Required # Required
self.latitude = latitude self.latitude = latitude
self.longitude = longitude self.longitude = longitude

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InputMessageContent""" InputMessageContent"""

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InputTextMessageContent""" InputTextMessageContent"""
@ -26,10 +25,7 @@ from telegram import InputMessageContent
class InputTextMessageContent(InputMessageContent): class InputTextMessageContent(InputMessageContent):
"""Base class for Telegram InputTextMessageContent Objects""" """Base class for Telegram InputTextMessageContent Objects"""
def __init__(self, def __init__(self, message_text, parse_mode=None, disable_web_page_preview=None):
message_text,
parse_mode=None,
disable_web_page_preview=None):
# Required # Required
self.message_text = message_text self.message_text = message_text
# Optionals # Optionals

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram """This module contains the classes that represent Telegram
InputVenueMessageContent""" InputVenueMessageContent"""
@ -26,12 +25,7 @@ from telegram import InputMessageContent
class InputVenueMessageContent(InputMessageContent): class InputVenueMessageContent(InputMessageContent):
"""Base class for Telegram InputVenueMessageContent Objects""" """Base class for Telegram InputVenueMessageContent Objects"""
def __init__(self, def __init__(self, latitude, longitude, title, address, foursquare_id=None):
latitude,
longitude,
title,
address,
foursquare_id=None):
# Required # Required
self.latitude = latitude self.latitude = latitude
self.longitude = longitude self.longitude = longitude

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram KeyboardButton.""" """This module contains a object that represents a Telegram KeyboardButton."""
from telegram import TelegramObject from telegram import TelegramObject
@ -34,10 +33,7 @@ class KeyboardButton(TelegramObject):
request_contact (Optional[bool]): request_contact (Optional[bool]):
""" """
def __init__(self, def __init__(self, text, request_contact=None, request_location=None):
text,
request_contact=None,
request_location=None):
# Required # Required
self.text = text self.text = text
# Optionals # Optionals
@ -60,7 +56,6 @@ class KeyboardButton(TelegramObject):
keyboards = list() keyboards = list()
for keyboard in data: for keyboard in data:
keyboards.append(KeyboardButton. keyboards.append(KeyboardButton.de_json(keyboard))
de_json(keyboard))
return keyboards return keyboards

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Location.""" """This module contains a object that represents a Telegram Location."""
from telegram import TelegramObject from telegram import TelegramObject
@ -34,9 +33,7 @@ class Location(TelegramObject):
latitude (float): latitude (float):
""" """
def __init__(self, def __init__(self, longitude, latitude):
longitude,
latitude):
# Required # Required
self.longitude = float(longitude) self.longitude = float(longitude)
self.latitude = float(latitude) self.latitude = float(latitude)

View file

@ -17,15 +17,13 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Message.""" """This module contains a object that represents a Telegram Message."""
from datetime import datetime from datetime import datetime
from time import mktime from time import mktime
from telegram import (Audio, Contact, Document, Chat, Location, PhotoSize, from telegram import (Audio, Contact, Document, Chat, Location, PhotoSize, Sticker, TelegramObject,
Sticker, TelegramObject, User, Video, Voice, Venue, User, Video, Voice, Venue, MessageEntity)
MessageEntity)
class Message(TelegramObject): class Message(TelegramObject):
@ -104,12 +102,7 @@ class Message(TelegramObject):
channel_chat_created (Optional[bool]): channel_chat_created (Optional[bool]):
""" """
def __init__(self, def __init__(self, message_id, from_user, date, chat, **kwargs):
message_id,
from_user,
date,
chat,
**kwargs):
# Required # Required
self.message_id = int(message_id) self.message_id = int(message_id)
self.from_user = from_user self.from_user = from_user
@ -138,12 +131,10 @@ class Message(TelegramObject):
self.new_chat_photo = kwargs.get('new_chat_photo') self.new_chat_photo = kwargs.get('new_chat_photo')
self.delete_chat_photo = bool(kwargs.get('delete_chat_photo', False)) self.delete_chat_photo = bool(kwargs.get('delete_chat_photo', False))
self.group_chat_created = bool(kwargs.get('group_chat_created', False)) self.group_chat_created = bool(kwargs.get('group_chat_created', False))
self.supergroup_chat_created = bool(kwargs.get( self.supergroup_chat_created = bool(kwargs.get('supergroup_chat_created', False))
'supergroup_chat_created', False))
self.migrate_to_chat_id = int(kwargs.get('migrate_to_chat_id', 0)) self.migrate_to_chat_id = int(kwargs.get('migrate_to_chat_id', 0))
self.migrate_from_chat_id = int(kwargs.get('migrate_from_chat_id', 0)) self.migrate_from_chat_id = int(kwargs.get('migrate_from_chat_id', 0))
self.channel_chat_created = bool(kwargs.get('channel_chat_created', self.channel_chat_created = bool(kwargs.get('channel_chat_created', False))
False))
self.pinned_message = kwargs.get('pinned_message') self.pinned_message = kwargs.get('pinned_message')
@property @property
@ -170,8 +161,7 @@ class Message(TelegramObject):
data['forward_from'] = User.de_json(data.get('forward_from')) data['forward_from'] = User.de_json(data.get('forward_from'))
data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat')) data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat'))
data['forward_date'] = Message._fromtimestamp(data.get('forward_date')) data['forward_date'] = Message._fromtimestamp(data.get('forward_date'))
data['reply_to_message'] = \ data['reply_to_message'] = Message.de_json(data.get('reply_to_message'))
Message.de_json(data.get('reply_to_message'))
data['audio'] = Audio.de_json(data.get('audio')) data['audio'] = Audio.de_json(data.get('audio'))
data['document'] = Document.de_json(data.get('document')) data['document'] = Document.de_json(data.get('document'))
data['photo'] = PhotoSize.de_list(data.get('photo')) data['photo'] = PhotoSize.de_list(data.get('photo'))

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram MessageEntity.""" """This module contains a object that represents a Telegram MessageEntity."""
from telegram import TelegramObject from telegram import TelegramObject
@ -34,11 +33,7 @@ class MessageEntity(TelegramObject):
url (Optional[str]): url (Optional[str]):
""" """
def __init__(self, def __init__(self, type, offset, length, url=None):
type,
offset,
length,
url=None):
# Required # Required
self.type = type self.type = type
self.offset = offset self.offset = offset

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a logging NullHandler.""" """This module contains a object that represents a logging NullHandler."""
import logging import logging

View file

@ -17,7 +17,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram """This module contains a object that represents a Telegram
Message Parse Modes.""" Message Parse Modes."""

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram PhotoSize.""" """This module contains a object that represents a Telegram PhotoSize."""
from telegram import TelegramObject from telegram import TelegramObject
@ -41,11 +40,7 @@ class PhotoSize(TelegramObject):
file_size (Optional[int]): file_size (Optional[int]):
""" """
def __init__(self, def __init__(self, file_id, width, height, **kwargs):
file_id,
width,
height,
**kwargs):
# Required # Required
self.file_id = str(file_id) self.file_id = str(file_id)
self.width = int(width) self.width = int(width)
@ -56,10 +51,8 @@ class PhotoSize(TelegramObject):
def __eq__(self, other): def __eq__(self, other):
if not isinstance(other, self.__class__): if not isinstance(other, self.__class__):
return False return False
return (self.file_id == other.file_id and return (self.file_id == other.file_id and self.width == other.width and
self.width == other.width and self.height == other.height and self.file_size == other.file_size)
self.height == other.height and
self.file_size == other.file_size)
@staticmethod @staticmethod
def de_json(data): def de_json(data):

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram """This module contains a object that represents a Telegram
ReplyKeyboardHide.""" ReplyKeyboardHide."""
@ -38,9 +37,7 @@ class ReplyKeyboardHide(ReplyMarkup):
selective (Optional[bool]): selective (Optional[bool]):
""" """
def __init__(self, def __init__(self, hide_keyboard=True, **kwargs):
hide_keyboard=True,
**kwargs):
# Required # Required
self.hide_keyboard = bool(hide_keyboard) self.hide_keyboard = bool(hide_keyboard)
# Optionals # Optionals

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram """This module contains a object that represents a Telegram
ReplyKeyboardMarkup.""" ReplyKeyboardMarkup."""
@ -42,9 +41,7 @@ class ReplyKeyboardMarkup(ReplyMarkup):
selective (Optional[bool]): selective (Optional[bool]):
""" """
def __init__(self, def __init__(self, keyboard, **kwargs):
keyboard,
**kwargs):
# Required # Required
self.keyboard = keyboard self.keyboard = keyboard
# Optionals # Optionals
@ -64,8 +61,7 @@ class ReplyKeyboardMarkup(ReplyMarkup):
if not data: if not data:
return None return None
data['keyboard'] = [KeyboardButton.de_list(keyboard) for keyboard in data['keyboard'] = [KeyboardButton.de_list(keyboard) for keyboard in data['keyboard']]
data['keyboard']]
return ReplyKeyboardMarkup(**data) return ReplyKeyboardMarkup(**data)
@ -79,6 +75,6 @@ class ReplyKeyboardMarkup(ReplyMarkup):
if hasattr(button, 'to_dict'): if hasattr(button, 'to_dict'):
r.append(button.to_dict()) # telegram.KeyboardButton r.append(button.to_dict()) # telegram.KeyboardButton
else: else:
r.append(button) # str r.append(button) # str
data['keyboard'].append(r) data['keyboard'].append(r)
return data return data

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""Base class for Telegram ReplyMarkup Objects.""" """Base class for Telegram ReplyMarkup Objects."""
from telegram import TelegramObject from telegram import TelegramObject

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Sticker.""" """This module contains a object that represents a Telegram Sticker."""
from telegram import PhotoSize, TelegramObject from telegram import PhotoSize, TelegramObject
@ -45,11 +44,7 @@ class Sticker(TelegramObject):
file_size (Optional[int]): file_size (Optional[int]):
""" """
def __init__(self, def __init__(self, file_id, width, height, **kwargs):
file_id,
width,
height,
**kwargs):
# Required # Required
self.file_id = str(file_id) self.file_id = str(file_id)
self.width = int(width) self.width = int(width)

View file

@ -16,11 +16,9 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Update.""" """This module contains a object that represents a Telegram Update."""
from telegram import (Message, TelegramObject, InlineQuery, from telegram import (Message, TelegramObject, InlineQuery, ChosenInlineResult, CallbackQuery)
ChosenInlineResult, CallbackQuery)
class Update(TelegramObject): class Update(TelegramObject):
@ -44,9 +42,7 @@ class Update(TelegramObject):
callback_query (Optional[:class:`telegram.CallbackQuery`]): callback_query (Optional[:class:`telegram.CallbackQuery`]):
""" """
def __init__(self, def __init__(self, update_id, **kwargs):
update_id,
**kwargs):
# Required # Required
self.update_id = int(update_id) self.update_id = int(update_id)
# Optionals # Optionals
@ -69,9 +65,7 @@ class Update(TelegramObject):
data['message'] = Message.de_json(data.get('message')) data['message'] = Message.de_json(data.get('message'))
data['inline_query'] = InlineQuery.de_json(data.get('inline_query')) data['inline_query'] = InlineQuery.de_json(data.get('inline_query'))
data['chosen_inline_result'] = \ data['chosen_inline_result'] = ChosenInlineResult.de_json(data.get('chosen_inline_result'))
ChosenInlineResult.de_json(data.get('chosen_inline_result')) data['callback_query'] = CallbackQuery.de_json(data.get('callback_query'))
data['callback_query'] = \
CallbackQuery.de_json(data.get('callback_query'))
return Update(**data) return Update(**data)

View file

@ -17,7 +17,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram User.""" """This module contains a object that represents a Telegram User."""
from telegram import TelegramObject from telegram import TelegramObject
@ -44,10 +43,7 @@ class User(TelegramObject):
username (Optional[str]): username (Optional[str]):
""" """
def __init__(self, def __init__(self, id, first_name, **kwargs):
id,
first_name,
**kwargs):
# Required # Required
self.id = int(id) self.id = int(id)
self.first_name = first_name self.first_name = first_name

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram """This module contains a object that represents a Telegram
UserProfilePhotos.""" UserProfilePhotos."""
@ -35,9 +34,7 @@ class UserProfilePhotos(TelegramObject):
photos (List[List[:class:`telegram.PhotoSize`]]): photos (List[List[:class:`telegram.PhotoSize`]]):
""" """
def __init__(self, def __init__(self, total_count, photos):
total_count,
photos):
# Required # Required
self.total_count = int(total_count) self.total_count = int(total_count)
self.photos = photos self.photos = photos

View file

@ -44,9 +44,8 @@ class Botan(object):
urlopen(request) urlopen(request)
return True return True
except HTTPError as error: except HTTPError as error:
self.logger.warn('Botan track error ' + self.logger.warn('Botan track error ' + str(error.code) + ':' + error.read().decode(
str(error.code) + 'utf-8'))
':' + error.read().decode('utf-8'))
return False return False
except URLError as error: except URLError as error:
self.logger.warn('Botan track error ' + str(error.reason)) self.logger.warn('Botan track error ' + str(error.reason))

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module facilitates the deprecation of functions""" """This module facilitates the deprecation of functions"""
import warnings import warnings
@ -24,7 +23,9 @@ import warnings
def deprecate(func, old, new): def deprecate(func, old, new):
"""Warn users invoking old to switch to the new function.""" """Warn users invoking old to switch to the new function."""
def f(*args, **kwargs): def f(*args, **kwargs):
warnings.warn("{0} is being deprecated, please use {1} from now on".format(old, new)) warnings.warn("{0} is being deprecated, please use {1} from now on".format(old, new))
return func(*args, **kwargs) return func(*args, **kwargs)
return f return f

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains methods to make POST and GET requests""" """This module contains methods to make POST and GET requests"""
import functools import functools
@ -57,6 +56,7 @@ def _parse(json_data):
def _try_except_req(func): def _try_except_req(func):
"""Decorator for requests to handle known exceptions""" """Decorator for requests to handle known exceptions"""
@functools.wraps(func) @functools.wraps(func)
def decorator(*args, **kwargs): def decorator(*args, **kwargs):
try: try:
@ -114,9 +114,7 @@ def get(url):
@_try_except_req @_try_except_req
def post(url, def post(url, data, timeout=None):
data,
timeout=None):
"""Request an URL. """Request an URL.
Args: Args:
url: url:
@ -142,22 +140,17 @@ def post(url,
if InputFile.is_inputfile(data): if InputFile.is_inputfile(data):
data = InputFile(data) data = InputFile(data)
request = Request(url, request = Request(url, data=data.to_form(), headers=data.headers)
data=data.to_form(),
headers=data.headers)
else: else:
data = json.dumps(data) data = json.dumps(data)
request = Request(url, request = Request(url, data=data.encode(), headers={'Content-Type': 'application/json'})
data=data.encode(),
headers={'Content-Type': 'application/json'})
result = urlopen(request, **urlopen_kwargs).read() result = urlopen(request, **urlopen_kwargs).read()
return _parse(result) return _parse(result)
@_try_except_req @_try_except_req
def download(url, def download(url, filename):
filename):
"""Download a file by its URL. """Download a file by its URL.
Args: Args:
url: url:

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains functions to validate function arguments""" """This module contains functions to validate function arguments"""
from telegram.error import InvalidToken from telegram.error import InvalidToken

View file

@ -9,7 +9,6 @@ try:
except ImportError: except ImportError:
import http.server as BaseHTTPServer import http.server as BaseHTTPServer
logging.getLogger(__name__).addHandler(NullHandler()) logging.getLogger(__name__).addHandler(NullHandler())
@ -21,10 +20,9 @@ class _InvalidPost(Exception):
class WebhookServer(BaseHTTPServer.HTTPServer, object): class WebhookServer(BaseHTTPServer.HTTPServer, object):
def __init__(self, server_address, RequestHandlerClass, update_queue,
webhook_path): def __init__(self, server_address, RequestHandlerClass, update_queue, webhook_path):
super(WebhookServer, self).__init__(server_address, super(WebhookServer, self).__init__(server_address, RequestHandlerClass)
RequestHandlerClass)
self.logger = logging.getLogger(__name__) self.logger = logging.getLogger(__name__)
self.update_queue = update_queue self.update_queue = update_queue
self.webhook_path = webhook_path self.webhook_path = webhook_path
@ -85,13 +83,11 @@ class WebhookHandler(BaseHTTPServer.BaseHTTPRequestHandler, object):
self.logger.debug('Webhook received data: ' + json_string) self.logger.debug('Webhook received data: ' + json_string)
update = Update.de_json(json.loads(json_string)) update = Update.de_json(json.loads(json_string))
self.logger.debug('Received Update with ID %d on Webhook' % self.logger.debug('Received Update with ID %d on Webhook' % update.update_id)
update.update_id)
self.server.update_queue.put(update) self.server.update_queue.put(update)
def _validate_post(self): def _validate_post(self):
if not (self.path == self.server.webhook_path and if not (self.path == self.server.webhook_path and 'content-type' in self.headers and
'content-type' in self.headers and
self.headers['content-type'] == 'application/json'): self.headers['content-type'] == 'application/json'):
raise _InvalidPost(403) raise _InvalidPost(403)

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Venue.""" """This module contains a object that represents a Telegram Venue."""
from telegram import TelegramObject, Location from telegram import TelegramObject, Location
@ -33,11 +32,7 @@ class Venue(TelegramObject):
foursquare_id (Optional[str]): foursquare_id (Optional[str]):
""" """
def __init__(self, def __init__(self, location, title, address, foursquare_id=None):
location,
title,
address,
foursquare_id=None):
# Required # Required
self.location = location self.location = location
self.title = title self.title = title

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Video.""" """This module contains a object that represents a Telegram Video."""
from telegram import PhotoSize, TelegramObject from telegram import PhotoSize, TelegramObject
@ -47,12 +46,7 @@ class Video(TelegramObject):
file_size (Optional[int]): file_size (Optional[int]):
""" """
def __init__(self, def __init__(self, file_id, width, height, duration, **kwargs):
file_id,
width,
height,
duration,
**kwargs):
# Required # Required
self.file_id = str(file_id) self.file_id = str(file_id)
self.width = int(width) self.width = int(width)

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Voice.""" """This module contains a object that represents a Telegram Voice."""
from telegram import TelegramObject from telegram import TelegramObject
@ -41,9 +40,7 @@ class Voice(TelegramObject):
file_size (Optional[int]): file_size (Optional[int]):
""" """
def __init__(self, def __init__(self, file_id, **kwargs):
file_id,
**kwargs):
# Required # Required
self.file_id = str(file_id) self.file_id = str(file_id)
# Optionals # Optionals

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Base class for tests""" """This module contains a object that represents a Base class for tests"""
import os import os
@ -37,8 +36,8 @@ class BaseTest(object):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(BaseTest, self).__init__(*args, **kwargs) super(BaseTest, self).__init__(*args, **kwargs)
bot = telegram.Bot(os.environ.get( bot = telegram.Bot(os.environ.get('TOKEN',
'TOKEN', '133505823:AAHZFMHno3mzVLErU5b5jJvaeG--qUyLyG0')) '133505823:AAHZFMHno3mzVLErU5b5jJvaeG--qUyLyG0'))
chat_id = os.environ.get('CHAT_ID', '12173560') chat_id = os.environ.get('CHAT_ID', '12173560')
self._bot = bot self._bot = bot
@ -70,7 +69,9 @@ class TestTimedOut(AssertionError):
def timeout(time_limit): def timeout(time_limit):
def decorator(func): def decorator(func):
def timed_out(_signum, frame): def timed_out(_signum, frame):
raise TestTimedOut(time_limit, frame) raise TestTimedOut(time_limit, frame)

View file

@ -197,9 +197,9 @@ class AudioTest(BaseTest, unittest.TestCase):
del (json_dict['file_id']) del (json_dict['file_id'])
json_dict['audio'] = open(os.devnull, 'rb') json_dict['audio'] = open(os.devnull, 'rb')
self.assertRaises(telegram.TelegramError, self.assertRaises(
lambda: self._bot.sendAudio(chat_id=self._chat_id, telegram.TelegramError,
**json_dict)) lambda: self._bot.sendAudio(chat_id=self._chat_id, **json_dict))
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @timeout(10)
@ -209,9 +209,9 @@ class AudioTest(BaseTest, unittest.TestCase):
del (json_dict['file_id']) del (json_dict['file_id'])
json_dict['audio'] = '' json_dict['audio'] = ''
self.assertRaises(telegram.TelegramError, self.assertRaises(
lambda: self._bot.sendAudio(chat_id=self._chat_id, telegram.TelegramError,
**json_dict)) lambda: self._bot.sendAudio(chat_id=self._chat_id, **json_dict))
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @timeout(10)
@ -221,9 +221,9 @@ class AudioTest(BaseTest, unittest.TestCase):
del (json_dict['file_id']) del (json_dict['file_id'])
del (json_dict['duration']) del (json_dict['duration'])
self.assertRaises(TypeError, self.assertRaises(
lambda: self._bot.sendAudio(chat_id=self._chat_id, TypeError,
**json_dict)) lambda: self._bot.sendAudio(chat_id=self._chat_id, **json_dict))
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -17,7 +17,6 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents Tests for Telegram Bot""" """This module contains a object that represents Tests for Telegram Bot"""
import io import io
@ -120,17 +119,20 @@ class BotTest(BaseTest, unittest.TestCase):
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @timeout(10)
def testResendPhoto(self): def testResendPhoto(self):
message = self._bot.sendPhoto(photo='AgADAQADyKcxGx8j9Qdp6d-gpUsw4Gja1i8ABEVJsVqQk8LfJ3wAAgI', message = self._bot.sendPhoto(
chat_id=self._chat_id) photo='AgADAQADyKcxGx8j9Qdp6d-gpUsw4Gja1i8ABEVJsVqQk8LfJ3wAAgI',
chat_id=self._chat_id)
self.assertTrue(self.is_json(message.to_json())) self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.photo[0].file_id, 'AgADAQADyKcxGx8j9Qdp6d-gpUsw4Gja1i8ABEVJsVqQk8LfJ3wAAgI') self.assertEqual(message.photo[0].file_id,
'AgADAQADyKcxGx8j9Qdp6d-gpUsw4Gja1i8ABEVJsVqQk8LfJ3wAAgI')
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @timeout(10)
def testSendJPGURLPhoto(self): def testSendJPGURLPhoto(self):
message = self._bot.sendPhoto(photo='http://dummyimage.com/600x400/000/fff.jpg&text=telegram', message = self._bot.sendPhoto(
chat_id=self._chat_id) photo='http://dummyimage.com/600x400/000/fff.jpg&text=telegram',
chat_id=self._chat_id)
self.assertTrue(self.is_json(message.to_json())) self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.photo[0].file_size, 822) self.assertEqual(message.photo[0].file_size, 822)
@ -138,8 +140,9 @@ class BotTest(BaseTest, unittest.TestCase):
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @timeout(10)
def testSendPNGURLPhoto(self): def testSendPNGURLPhoto(self):
message = self._bot.sendPhoto(photo='http://dummyimage.com/600x400/000/fff.png&text=telegram', message = self._bot.sendPhoto(
chat_id=self._chat_id) photo='http://dummyimage.com/600x400/000/fff.png&text=telegram',
chat_id=self._chat_id)
self.assertTrue(self.is_json(message.to_json())) self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.photo[0].file_size, 684) self.assertEqual(message.photo[0].file_size, 684)
@ -147,8 +150,9 @@ class BotTest(BaseTest, unittest.TestCase):
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @timeout(10)
def testSendGIFURLPhoto(self): def testSendGIFURLPhoto(self):
message = self._bot.sendPhoto(photo='http://dummyimage.com/600x400/000/fff.gif&text=telegram', message = self._bot.sendPhoto(
chat_id=self._chat_id) photo='http://dummyimage.com/600x400/000/fff.gif&text=telegram',
chat_id=self._chat_id)
self.assertTrue(self.is_json(message.to_json())) self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.photo[0].file_size, 684) self.assertEqual(message.photo[0].file_size, 684)
@ -158,8 +162,7 @@ class BotTest(BaseTest, unittest.TestCase):
def testSendBufferedReaderPhoto(self): def testSendBufferedReaderPhoto(self):
photo = open('tests/data/telegram.png', 'rb') photo = open('tests/data/telegram.png', 'rb')
br_photo = io.BufferedReader(io.BytesIO(photo.read())) br_photo = io.BufferedReader(io.BytesIO(photo.read()))
message = self._bot.sendPhoto(photo=br_photo, message = self._bot.sendPhoto(photo=br_photo, chat_id=self._chat_id)
chat_id=self._chat_id)
self.assertTrue(self.is_json(message.to_json())) self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.photo[0].file_size, 1451) self.assertEqual(message.photo[0].file_size, 1451)
@ -167,8 +170,7 @@ class BotTest(BaseTest, unittest.TestCase):
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @timeout(10)
def testSendChatAction(self): def testSendChatAction(self):
self._bot.sendChatAction(action=telegram.ChatAction.TYPING, self._bot.sendChatAction(action=telegram.ChatAction.TYPING, chat_id=self._chat_id)
chat_id=self._chat_id)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @timeout(10)

View file

@ -1,4 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016 # Copyright (C) 2015-2016
@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents Tests for Telegram Chat""" """This module contains a object that represents Tests for Telegram Chat"""
import unittest import unittest
@ -35,11 +34,7 @@ class ChatTest(BaseTest, unittest.TestCase):
self.title = 'ToledosPalaceBot - Group' self.title = 'ToledosPalaceBot - Group'
self.type = 'group' self.type = 'group'
self.json_dict = { self.json_dict = {'id': self.id, 'title': self.title, 'type': self.type}
'id': self.id,
'title': self.title,
'type': self.type
}
def test_group_chat_de_json_empty_json(self): def test_group_chat_de_json_empty_json(self):
group_chat = telegram.Chat.de_json({}) group_chat = telegram.Chat.de_json({})
@ -66,5 +61,6 @@ class ChatTest(BaseTest, unittest.TestCase):
self.assertEqual(group_chat['title'], self.title) self.assertEqual(group_chat['title'], self.title)
self.assertEqual(group_chat['type'], self.type) self.assertEqual(group_chat['type'], self.type)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View file

@ -52,8 +52,7 @@ class ChosenInlineResultTest(BaseTest, unittest.TestCase):
result = telegram.ChosenInlineResult.de_json(self.json_dict) result = telegram.ChosenInlineResult.de_json(self.json_dict)
self.assertEqual(result.result_id, self.result_id) self.assertEqual(result.result_id, self.result_id)
self.assertDictEqual(result.from_user.to_dict(), self.assertDictEqual(result.from_user.to_dict(), self.from_user.to_dict())
self.from_user.to_dict())
self.assertEqual(result.query, self.query) self.assertEqual(result.query, self.query)
def test_choseninlineresult_to_json(self): def test_choseninlineresult_to_json(self):

View file

@ -1,4 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016 # Copyright (C) 2015-2016
@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents Tests for Telegram Contact""" """This module contains a object that represents Tests for Telegram Contact"""
import unittest import unittest
@ -65,5 +64,6 @@ class ContactTest(BaseTest, unittest.TestCase):
self.assertEqual(contact['last_name'], self.last_name) self.assertEqual(contact['last_name'], self.last_name)
self.assertEqual(contact['user_id'], self.user_id) self.assertEqual(contact['user_id'], self.user_id)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View file

@ -100,8 +100,7 @@ class DocumentTest(BaseTest, unittest.TestCase):
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @timeout(10)
def test_send_document_resend(self): def test_send_document_resend(self):
message = self._bot.sendDocument(chat_id=self._chat_id, message = self._bot.sendDocument(chat_id=self._chat_id, document=self.document_file_id)
document=self.document_file_id)
document = message.document document = message.document

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents Tests for Telegram Emoji""" """This module contains a object that represents Tests for Telegram Emoji"""
import unittest import unittest

View file

@ -126,8 +126,7 @@ class FileTest(BaseTest, unittest.TestCase):
del (json_dict['file_path']) del (json_dict['file_path'])
del (json_dict['file_size']) del (json_dict['file_size'])
self.assertRaises(telegram.TelegramError, self.assertRaises(telegram.TelegramError, lambda: self._bot.getFile(**json_dict))
lambda: self._bot.getFile(**json_dict))
def test_error_file_without_required_args(self): def test_error_file_without_required_args(self):
json_dict = self.json_dict json_dict = self.json_dict

View file

@ -35,8 +35,7 @@ class FiltersTest(BaseTest, unittest.TestCase):
"""This object represents Tests for MessageHandler.Filters""" """This object represents Tests for MessageHandler.Filters"""
def setUp(self): def setUp(self):
self.message = Message(0, User(0, "Testuser"), datetime.now(), self.message = Message(0, User(0, "Testuser"), datetime.now(), Chat(0, 'private'))
Chat(0, 'private'))
self.update = Update(0, message=self.message) self.update = Update(0, message=self.message)
def test_filters_text(self): def test_filters_text(self):

View file

@ -35,20 +35,15 @@ class ForceReplyTest(BaseTest, unittest.TestCase):
self.force_reply = True self.force_reply = True
self.selective = True self.selective = True
self.json_dict = { self.json_dict = {'force_reply': self.force_reply, 'selective': self.selective,}
'force_reply': self.force_reply,
'selective': self.selective,
}
def test_send_message_with_force_reply(self): def test_send_message_with_force_reply(self):
message = self._bot.sendMessage( message = self._bot.sendMessage(self._chat_id,
self._chat_id, 'Моё судно на воздушной подушке полно угрей',
'Моё судно на воздушной подушке полно угрей', reply_markup=telegram.ForceReply.de_json(self.json_dict))
reply_markup=telegram.ForceReply.de_json(self.json_dict))
self.assertTrue(self.is_json(message.to_json())) self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, self.assertEqual(message.text, u'Моё судно на воздушной подушке полно угрей')
u'Моё судно на воздушной подушке полно угрей')
def test_force_reply_de_json(self): def test_force_reply_de_json(self):
force_reply = telegram.ForceReply.de_json(self.json_dict) force_reply = telegram.ForceReply.de_json(self.json_dict)

View file

@ -49,15 +49,12 @@ class InlineKeyboardButtonTest(BaseTest, unittest.TestCase):
} }
def test_inline_keyboard_button_de_json(self): def test_inline_keyboard_button_de_json(self):
inline_keyboard_button = telegram.InlineKeyboardButton.de_json( inline_keyboard_button = telegram.InlineKeyboardButton.de_json(self.json_dict)
self.json_dict)
self.assertEqual(inline_keyboard_button.text, self.text) self.assertEqual(inline_keyboard_button.text, self.text)
self.assertEqual(inline_keyboard_button.url, self.url) self.assertEqual(inline_keyboard_button.url, self.url)
self.assertEqual(inline_keyboard_button.callback_data, self.assertEqual(inline_keyboard_button.callback_data, self.callback_data)
self.callback_data) self.assertEqual(inline_keyboard_button.switch_inline_query, self.switch_inline_query)
self.assertEqual(inline_keyboard_button.switch_inline_query,
self.switch_inline_query)
def test_inline_keyboard_button_de_json_empty(self): def test_inline_keyboard_button_de_json_empty(self):
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(None) inline_keyboard_button = telegram.InlineKeyboardButton.de_json(None)
@ -70,14 +67,12 @@ class InlineKeyboardButtonTest(BaseTest, unittest.TestCase):
self.assertFalse(inline_keyboard_button) self.assertFalse(inline_keyboard_button)
def test_inline_keyboard_button_to_json(self): def test_inline_keyboard_button_to_json(self):
inline_keyboard_button = telegram.InlineKeyboardButton.de_json( inline_keyboard_button = telegram.InlineKeyboardButton.de_json(self.json_dict)
self.json_dict)
self.assertTrue(self.is_json(inline_keyboard_button.to_json())) self.assertTrue(self.is_json(inline_keyboard_button.to_json()))
def test_inline_keyboard_button_to_dict(self): def test_inline_keyboard_button_to_dict(self):
inline_keyboard_button = telegram.InlineKeyboardButton.de_json( inline_keyboard_button = telegram.InlineKeyboardButton.de_json(self.json_dict).to_dict()
self.json_dict).to_dict()
self.assertTrue(self.is_dict(inline_keyboard_button)) self.assertTrue(self.is_dict(inline_keyboard_button))
self.assertDictEqual(self.json_dict, inline_keyboard_button) self.assertDictEqual(self.json_dict, inline_keyboard_button)

View file

@ -32,10 +32,10 @@ class InlineKeyboardMarkupTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram KeyboardButton.""" """This object represents Tests for Telegram KeyboardButton."""
def setUp(self): def setUp(self):
self.inline_keyboard = [[telegram.InlineKeyboardButton( self.inline_keyboard = [[telegram.InlineKeyboardButton(text='button1',
text='button1', callback_data='data1'),
callback_data='data1'), telegram.InlineKeyboardButton( telegram.InlineKeyboardButton(text='button2',
text='button2', callback_data='data2')]] callback_data='data2')]]
self.json_dict = { self.json_dict = {
'inline_keyboard': [[self.inline_keyboard[0][0].to_dict(), 'inline_keyboard': [[self.inline_keyboard[0][0].to_dict(),
@ -57,26 +57,21 @@ class InlineKeyboardMarkupTest(BaseTest, unittest.TestCase):
self.assertFalse(inline_keyboard_markup) self.assertFalse(inline_keyboard_markup)
def test_inline_keyboard_markup_de_json(self): def test_inline_keyboard_markup_de_json(self):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json( inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict)
self.json_dict)
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard, self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard, list))
list))
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard[0][ self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard[0][
0], telegram.InlineKeyboardButton)) 0], telegram.InlineKeyboardButton))
def test_inline_keyboard_markup_to_json(self): def test_inline_keyboard_markup_to_json(self):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json( inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict)
self.json_dict)
self.assertTrue(self.is_json(inline_keyboard_markup.to_json())) self.assertTrue(self.is_json(inline_keyboard_markup.to_json()))
def test_inline_keyboard_markup_to_dict(self): def test_inline_keyboard_markup_to_dict(self):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json( inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict)
self.json_dict)
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard, self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard, list))
list))
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard[0][ self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard[0][
0], telegram.InlineKeyboardButton)) 0], telegram.InlineKeyboardButton))

View file

@ -57,10 +57,8 @@ class InlineQueryTest(BaseTest, unittest.TestCase):
inlinequery = telegram.InlineQuery.de_json(self.json_dict) inlinequery = telegram.InlineQuery.de_json(self.json_dict)
self.assertEqual(inlinequery.id, self.id) self.assertEqual(inlinequery.id, self.id)
self.assertDictEqual(inlinequery.from_user.to_dict(), self.assertDictEqual(inlinequery.from_user.to_dict(), self.from_user.to_dict())
self.from_user.to_dict()) self.assertDictEqual(inlinequery.location.to_dict(), self.location.to_dict())
self.assertDictEqual(inlinequery.location.to_dict(),
self.location.to_dict())
self.assertEqual(inlinequery.query, self.query) self.assertEqual(inlinequery.query, self.query)
self.assertEqual(inlinequery.offset, self.offset) self.assertEqual(inlinequery.offset, self.offset)

View file

@ -39,8 +39,7 @@ class InlineQueryResultArticleTest(BaseTest, unittest.TestCase):
self.id = 'id' self.id = 'id'
self.type = 'article' self.type = 'article'
self.title = 'title' self.title = 'title'
self.input_message_content = telegram.InputTextMessageContent( self.input_message_content = telegram.InputTextMessageContent('input_message_content')
'input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup([[ self.reply_markup = telegram.InlineKeyboardMarkup([[
telegram.InlineKeyboardButton('reply_markup') telegram.InlineKeyboardButton('reply_markup')
]]) ]])
@ -73,8 +72,7 @@ class InlineQueryResultArticleTest(BaseTest, unittest.TestCase):
self.assertEqual(article.title, self.title) self.assertEqual(article.title, self.title)
self.assertDictEqual(article.input_message_content.to_dict(), self.assertDictEqual(article.input_message_content.to_dict(),
self.input_message_content.to_dict()) self.input_message_content.to_dict())
self.assertDictEqual(article.reply_markup.to_dict(), self.assertDictEqual(article.reply_markup.to_dict(), self.reply_markup.to_dict())
self.reply_markup.to_dict())
self.assertEqual(article.url, self.url) self.assertEqual(article.url, self.url)
self.assertEqual(article.hide_url, self.hide_url) self.assertEqual(article.hide_url, self.hide_url)
self.assertEqual(article.description, self.description) self.assertEqual(article.description, self.description)
@ -88,8 +86,7 @@ class InlineQueryResultArticleTest(BaseTest, unittest.TestCase):
self.assertTrue(self.is_json(article.to_json())) self.assertTrue(self.is_json(article.to_json()))
def test_article_to_dict(self): def test_article_to_dict(self):
article = telegram.InlineQueryResultArticle.de_json( article = telegram.InlineQueryResultArticle.de_json(self.json_dict).to_dict()
self.json_dict).to_dict()
self.assertTrue(self.is_dict(article)) self.assertTrue(self.is_dict(article))
self.assertDictEqual(self.json_dict, article) self.assertDictEqual(self.json_dict, article)

Some files were not shown because too many files have changed in this diff Show more