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
script:
- 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
- '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:
coveralls

View file

@ -22,6 +22,11 @@ Setting things up
``$ pip install -r requirements.txt -r requirements-dev.txt``
5. Install pre-commit hooks:
``$ pre-commit install``
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.
- 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 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"``
- Finally, push it to your GitHub fork, run:
``$ git push origin your-branch-name``
4. **When your feature is ready to merge, create a pull request.**

View file

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

View file

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

View file

@ -11,3 +11,7 @@ upload-dir = docs/build/html
[flake8]
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
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""A library that provides a Python interface to the Telegram Bot API"""
from sys import version_info
@ -81,70 +80,24 @@ from .inputcontactmessagecontent import InputContactMessageContent
from .update import Update
from .bot import Bot
__author__ = 'devs@python-telegram-bot.org'
__version__ = '4.0.3'
__all__ = ['Audio',
'Bot',
'Chat',
'ChatAction',
'ChosenInlineResult',
'CallbackQuery',
'Contact',
'Document',
'Emoji',
'File',
'ForceReply',
'InlineKeyboardButton',
'InlineKeyboardMarkup',
'InlineQuery',
'InlineQueryResult',
'InlineQueryResult',
'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']
__all__ = ['Audio', 'Bot', 'Chat', 'ChatAction', 'ChosenInlineResult', 'CallbackQuery', 'Contact',
'Document', 'Emoji', 'File', 'ForceReply', 'InlineKeyboardButton',
'InlineKeyboardMarkup', 'InlineQuery', 'InlineQueryResult', 'InlineQueryResult',
'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):
from warnings import warn

View file

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

View file

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

View file

@ -17,14 +17,13 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Bot."""
import logging
import functools
from telegram import User, Message, Update, UserProfilePhotos, File, \
ReplyMarkup, TelegramObject, NullHandler
from telegram import (User, Message, Update, UserProfilePhotos, File, ReplyMarkup, TelegramObject,
NullHandler)
from telegram.utils import request
from telegram.utils.validate import validate_token
@ -48,21 +47,16 @@ class Bot(TelegramObject):
"""
def __init__(self,
token,
base_url=None,
base_file_url=None):
def __init__(self, token, base_url=None, base_file_url=None):
self.token = validate_token(token)
if not base_url:
self.base_url = 'https://api.telegram.org/bot{0}'.format(
self.token)
self.base_url = 'https://api.telegram.org/bot{0}'.format(self.token)
else:
self.base_url = base_url + self.token
if not base_file_url:
self.base_file_url = 'https://api.telegram.org/file/bot{0}'.format(
self.token)
self.base_file_url = 'https://api.telegram.org/file/bot{0}'.format(self.token)
else:
self.base_file_url = base_file_url + self.token
@ -71,6 +65,7 @@ class Bot(TelegramObject):
self.logger = logging.getLogger(__name__)
def info(func):
@functools.wraps(func)
def decorator(self, *args, **kwargs):
if not self.bot:
@ -119,17 +114,16 @@ class Bot(TelegramObject):
return decorator
def message(func):
@functools.wraps(func)
def decorator(self, *args, **kwargs):
url, data = func(self, *args, **kwargs)
if kwargs.get('reply_to_message_id'):
data['reply_to_message_id'] = \
kwargs.get('reply_to_message_id')
data['reply_to_message_id'] = kwargs.get('reply_to_message_id')
if kwargs.get('disable_notification'):
data['disable_notification'] = \
kwargs.get('disable_notification')
data['disable_notification'] = kwargs.get('disable_notification')
if kwargs.get('reply_markup'):
reply_markup = kwargs.get('reply_markup')
@ -138,8 +132,7 @@ class Bot(TelegramObject):
else:
data['reply_markup'] = reply_markup
result = request.post(url, data,
timeout=kwargs.get('timeout'))
result = request.post(url, data, timeout=kwargs.get('timeout'))
if result is True:
return result
@ -172,12 +165,7 @@ class Bot(TelegramObject):
@log
@message
def sendMessage(self,
chat_id,
text,
parse_mode=None,
disable_web_page_preview=None,
**kwargs):
def sendMessage(self, chat_id, text, parse_mode=None, disable_web_page_preview=None, **kwargs):
"""Use this method to send text messages.
Args:
@ -217,8 +205,7 @@ class Bot(TelegramObject):
url = '{0}/sendMessage'.format(self.base_url)
data = {'chat_id': chat_id,
'text': text}
data = {'chat_id': chat_id, 'text': text}
if parse_mode:
data['parse_mode'] = parse_mode
@ -229,11 +216,7 @@ class Bot(TelegramObject):
@log
@message
def forwardMessage(self,
chat_id,
from_chat_id,
message_id,
**kwargs):
def forwardMessage(self, chat_id, from_chat_id, message_id, **kwargs):
"""Use this method to forward messages of any kind.
Args:
@ -276,11 +259,7 @@ class Bot(TelegramObject):
@log
@message
def sendPhoto(self,
chat_id,
photo,
caption=None,
**kwargs):
def sendPhoto(self, chat_id, photo, caption=None, **kwargs):
"""Use this method to send photos.
Args:
@ -318,8 +297,7 @@ class Bot(TelegramObject):
url = '{0}/sendPhoto'.format(self.base_url)
data = {'chat_id': chat_id,
'photo': photo}
data = {'chat_id': chat_id, 'photo': photo}
if caption:
data['caption'] = caption
@ -328,13 +306,7 @@ class Bot(TelegramObject):
@log
@message
def sendAudio(self,
chat_id,
audio,
duration=None,
performer=None,
title=None,
**kwargs):
def sendAudio(self, chat_id, audio, duration=None, performer=None, title=None, **kwargs):
"""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.
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)
data = {'chat_id': chat_id,
'audio': audio}
data = {'chat_id': chat_id, 'audio': audio}
if duration:
data['duration'] = duration
@ -398,12 +369,7 @@ class Bot(TelegramObject):
@log
@message
def sendDocument(self,
chat_id,
document,
filename=None,
caption=None,
**kwargs):
def sendDocument(self, chat_id, document, filename=None, caption=None, **kwargs):
"""Use this method to send general files.
Args:
@ -444,8 +410,7 @@ class Bot(TelegramObject):
url = '{0}/sendDocument'.format(self.base_url)
data = {'chat_id': chat_id,
'document': document}
data = {'chat_id': chat_id, 'document': document}
if filename:
data['filename'] = filename
@ -456,10 +421,7 @@ class Bot(TelegramObject):
@log
@message
def sendSticker(self,
chat_id,
sticker,
**kwargs):
def sendSticker(self, chat_id, sticker, **kwargs):
"""Use this method to send .webp stickers.
Args:
@ -494,19 +456,13 @@ class Bot(TelegramObject):
url = '{0}/sendSticker'.format(self.base_url)
data = {'chat_id': chat_id,
'sticker': sticker}
data = {'chat_id': chat_id, 'sticker': sticker}
return url, data
@log
@message
def sendVideo(self,
chat_id,
video,
duration=None,
caption=None,
**kwargs):
def sendVideo(self, chat_id, video, duration=None, caption=None, **kwargs):
"""Use this method to send video files, Telegram clients support mp4
videos (other formats may be sent as telegram.Document).
@ -547,8 +503,7 @@ class Bot(TelegramObject):
url = '{0}/sendVideo'.format(self.base_url)
data = {'chat_id': chat_id,
'video': video}
data = {'chat_id': chat_id, 'video': video}
if duration:
data['duration'] = duration
@ -559,11 +514,7 @@ class Bot(TelegramObject):
@log
@message
def sendVoice(self,
chat_id,
voice,
duration=None,
**kwargs):
def sendVoice(self, chat_id, voice, duration=None, **kwargs):
"""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
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)
data = {'chat_id': chat_id,
'voice': voice}
data = {'chat_id': chat_id, 'voice': voice}
if duration:
data['duration'] = duration
@ -615,11 +565,7 @@ class Bot(TelegramObject):
@log
@message
def sendLocation(self,
chat_id,
latitude,
longitude,
**kwargs):
def sendLocation(self, chat_id, latitude, longitude, **kwargs):
"""Use this method to send point on the map.
Args:
@ -654,22 +600,19 @@ class Bot(TelegramObject):
url = '{0}/sendLocation'.format(self.base_url)
data = {'chat_id': chat_id,
'latitude': latitude,
'longitude': longitude}
data = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude}
return url, data
@log
@message
def sendVenue(self,
chat_id,
latitude,
longitude,
title,
address,
foursquare_id=None,
**kwargs):
def sendVenue(
self, chat_id,
latitude,
longitude,
title, address,
foursquare_id=None,
**kwargs):
"""
Use this method to send information about a venue.
@ -725,12 +668,7 @@ class Bot(TelegramObject):
@log
@message
def sendContact(self,
chat_id,
phone_number,
first_name,
last_name=None,
**kwargs):
def sendContact(self, chat_id, phone_number, first_name, last_name=None, **kwargs):
"""
Use this method to send phone contacts.
@ -769,9 +707,7 @@ class Bot(TelegramObject):
url = '{0}/sendContact'.format(self.base_url)
data = {'chat_id': chat_id,
'phone_number': phone_number,
'first_name': first_name}
data = {'chat_id': chat_id, 'phone_number': phone_number, 'first_name': first_name}
if last_name:
data['last_name'] = last_name
@ -780,10 +716,7 @@ class Bot(TelegramObject):
@log
@message
def sendChatAction(self,
chat_id,
action,
**kwargs):
def sendChatAction(self, chat_id, action, **kwargs):
"""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
(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)
data = {'chat_id': chat_id,
'action': action}
data = {'chat_id': chat_id, 'action': action}
return url, data
@ -861,8 +793,7 @@ class Bot(TelegramObject):
results = [res.to_dict() for res in results]
data = {'inline_query_id': inline_query_id,
'results': results}
data = {'inline_query_id': inline_query_id, 'results': results}
if cache_time or cache_time == 0:
data['cache_time'] = cache_time
@ -875,17 +806,12 @@ class Bot(TelegramObject):
if switch_pm_parameter:
data['switch_pm_parameter'] = switch_pm_parameter
result = request.post(url, data,
timeout=kwargs.get('timeout'))
result = request.post(url, data, timeout=kwargs.get('timeout'))
return result
@log
def getUserProfilePhotos(self,
user_id,
offset=None,
limit=100,
**kwargs):
def getUserProfilePhotos(self, user_id, offset=None, limit=100, **kwargs):
"""Use this method to get a list of profile pictures for a user.
Args:
@ -920,15 +846,12 @@ class Bot(TelegramObject):
if limit:
data['limit'] = limit
result = request.post(url, data,
timeout=kwargs.get('timeout'))
result = request.post(url, data, timeout=kwargs.get('timeout'))
return UserProfilePhotos.de_json(result)
@log
def getFile(self,
file_id,
**kwargs):
def getFile(self, file_id, **kwargs):
"""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
size.
@ -954,20 +877,15 @@ class Bot(TelegramObject):
data = {'file_id': file_id}
result = request.post(url, data,
timeout=kwargs.get('timeout'))
result = request.post(url, data, timeout=kwargs.get('timeout'))
if result.get('file_path'):
result['file_path'] = '%s/%s' % (self.base_file_url,
result['file_path'])
result['file_path'] = '%s/%s' % (self.base_file_url, result['file_path'])
return File.de_json(result)
@log
def kickChatMember(self,
chat_id,
user_id,
**kwargs):
def kickChatMember(self, chat_id, user_id, **kwargs):
"""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
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)
data = {'chat_id': chat_id,
'user_id': user_id}
data = {'chat_id': chat_id, 'user_id': user_id}
result = request.post(url, data,
timeout=kwargs.get('timeout'))
result = request.post(url, data, timeout=kwargs.get('timeout'))
return result
@log
def unbanChatMember(self,
chat_id,
user_id,
**kwargs):
def unbanChatMember(self, chat_id, user_id, **kwargs):
"""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
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)
data = {'chat_id': chat_id,
'user_id': user_id}
data = {'chat_id': chat_id, 'user_id': user_id}
result = request.post(url, data,
timeout=kwargs.get('timeout'))
result = request.post(url, data, timeout=kwargs.get('timeout'))
return result
@log
def answerCallbackQuery(self,
callback_query_id,
text=None,
show_alert=False,
**kwargs):
def answerCallbackQuery(self, callback_query_id, text=None, show_alert=False, **kwargs):
"""Use this method to send answers to callback queries sent from
inline keyboards. The answer will be displayed to the user as a
notification at the top of the chat screen or as an alert.
@ -1085,8 +992,7 @@ class Bot(TelegramObject):
if show_alert:
data['show_alert'] = show_alert
result = request.post(url, data,
timeout=kwargs.get('timeout'))
result = request.post(url, data, timeout=kwargs.get('timeout'))
return result
@ -1158,8 +1064,7 @@ class Bot(TelegramObject):
else:
data['reply_markup'] = reply_markup
result = request.post(url, data,
timeout=kwargs.get('timeout'))
result = request.post(url, data, timeout=kwargs.get('timeout'))
return Message.de_json(result)
@ -1218,11 +1123,10 @@ class Bot(TelegramObject):
@log
@message
def editMessageReplyMarkup(self,
chat_id=None,
message_id=None,
inline_message_id=None,
**kwargs):
def editMessageReplyMarkup(
self, chat_id=None,
message_id=None, inline_message_id=None,
**kwargs):
"""Use this method to edit only the reply markup of messages sent by
the bot or via the bot (for inline bots).
@ -1266,11 +1170,7 @@ class Bot(TelegramObject):
return url, data
@log
def getUpdates(self,
offset=None,
limit=100,
timeout=0,
network_delay=.2):
def getUpdates(self, offset=None, limit=100, timeout=0, network_delay=.2):
"""Use this method to receive incoming updates using long polling.
Args:
@ -1315,18 +1215,14 @@ class Bot(TelegramObject):
result = request.post(url, data, timeout=urlopen_timeout)
if result:
self.logger.debug(
'Getting updates: %s', [u['update_id'] for u in result])
self.logger.debug('Getting updates: %s', [u['update_id'] for u in result])
else:
self.logger.debug('No new updates found.')
return [Update.de_json(x) for x in result]
@log
def setWebhook(self,
webhook_url=None,
certificate=None,
**kwargs):
def setWebhook(self, webhook_url=None, certificate=None, **kwargs):
"""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
an HTTPS POST request to the specified url, containing a
@ -1359,8 +1255,7 @@ class Bot(TelegramObject):
if certificate:
data['certificate'] = certificate
result = request.post(url, data,
timeout=kwargs.get('timeout'))
result = request.post(url, data, timeout=kwargs.get('timeout'))
return result
@ -1371,9 +1266,7 @@ class Bot(TelegramObject):
return Bot(**data)
def to_dict(self):
data = {'id': self.id,
'username': self.username,
'first_name': self.username}
data = {'id': self.id, 'username': self.username, 'first_name': self.username}
if self.last_name:
data['last_name'] = self.last_name
@ -1381,8 +1274,7 @@ class Bot(TelegramObject):
return data
def __reduce__(self):
return (self.__class__, (self.token,
self.base_url.replace(self.token, ''),
return (self.__class__, (self.token, self.base_url.replace(self.token, ''),
self.base_file_url.replace(self.token, '')))
# snake_case (PEP8) aliases

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,6 +1,6 @@
#!/usr/bin/env python
# flake8: noqa
# pylint: disable=C0103,C0301,R0903
# pylint: disable=C0103,R0903
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016
@ -18,7 +18,6 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents an Emoji."""
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_UP_WITH_EXCLAMATION_MARK = n(b'\xF0\x9F\x86\x99')
SQUARED_VS = n(b'\xF0\x9F\x86\x9A')
REGIONAL_INDICATOR_SYMBOL_LETTER_D_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_E \
= n(b'\xF0\x9F\x87\xA9\xF0\x9F\x87\xAA')
REGIONAL_INDICATOR_SYMBOL_LETTER_G_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_B \
= n(b'\xF0\x9F\x87\xAC\xF0\x9F\x87\xA7')
REGIONAL_INDICATOR_SYMBOL_LETTER_C_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_N \
= n(b'\xF0\x9F\x87\xA8\xF0\x9F\x87\xB3')
REGIONAL_INDICATOR_SYMBOL_LETTER_J_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_P \
= n(b'\xF0\x9F\x87\xAF\xF0\x9F\x87\xB5')
REGIONAL_INDICATOR_SYMBOL_LETTER_K_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_R \
= n(b'\xF0\x9F\x87\xB0\xF0\x9F\x87\xB7')
REGIONAL_INDICATOR_SYMBOL_LETTER_F_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_R \
= n(b'\xF0\x9F\x87\xAB\xF0\x9F\x87\xB7')
REGIONAL_INDICATOR_SYMBOL_LETTER_E_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_S \
= n(b'\xF0\x9F\x87\xAA\xF0\x9F\x87\xB8')
REGIONAL_INDICATOR_SYMBOL_LETTER_I_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_T \
= n(b'\xF0\x9F\x87\xAE\xF0\x9F\x87\xB9')
REGIONAL_INDICATOR_SYMBOL_LETTER_U_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_S \
= n(b'\xF0\x9F\x87\xBA\xF0\x9F\x87\xB8')
REGIONAL_INDICATOR_SYMBOL_LETTER_R_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_U \
= n(b'\xF0\x9F\x87\xB7\xF0\x9F\x87\xBA')
REGIONAL_INDICATOR_SYMBOL_LETTER_D_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_E = n(
b'\xF0\x9F\x87\xA9\xF0\x9F\x87\xAA')
REGIONAL_INDICATOR_SYMBOL_LETTER_G_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_B = n(
b'\xF0\x9F\x87\xAC\xF0\x9F\x87\xA7')
REGIONAL_INDICATOR_SYMBOL_LETTER_C_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_N = n(
b'\xF0\x9F\x87\xA8\xF0\x9F\x87\xB3')
REGIONAL_INDICATOR_SYMBOL_LETTER_J_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_P = n(
b'\xF0\x9F\x87\xAF\xF0\x9F\x87\xB5')
REGIONAL_INDICATOR_SYMBOL_LETTER_K_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_R = n(
b'\xF0\x9F\x87\xB0\xF0\x9F\x87\xB7')
REGIONAL_INDICATOR_SYMBOL_LETTER_F_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_R = n(
b'\xF0\x9F\x87\xAB\xF0\x9F\x87\xB7')
REGIONAL_INDICATOR_SYMBOL_LETTER_E_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_S = n(
b'\xF0\x9F\x87\xAA\xF0\x9F\x87\xB8')
REGIONAL_INDICATOR_SYMBOL_LETTER_I_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_T = n(
b'\xF0\x9F\x87\xAE\xF0\x9F\x87\xB9')
REGIONAL_INDICATOR_SYMBOL_LETTER_U_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_S = n(
b'\xF0\x9F\x87\xBA\xF0\x9F\x87\xB8')
REGIONAL_INDICATOR_SYMBOL_LETTER_R_PLUS_REGIONAL_INDICATOR_SYMBOL_LETTER_U = n(
b'\xF0\x9F\x87\xB7\xF0\x9F\x87\xBA')
SQUARED_KATAKANA_KOKO = n(b'\xF0\x9F\x88\x81')
SQUARED_KATAKANA_SA = n(b'\xF0\x9F\x88\x82')
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')
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_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')
LOW_BRIGHTNESS_SYMBOL = n(b'\xF0\x9F\x94\x85')
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
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Error."""
@ -62,11 +61,13 @@ class TelegramError(Exception):
class Unauthorized(TelegramError):
def __init__(self):
super(Unauthorized, self).__init__('Unauthorized')
class InvalidToken(TelegramError):
def __init__(self):
super(InvalidToken, self).__init__('Invalid token')
@ -76,5 +77,6 @@ class NetworkError(TelegramError):
class TimedOut(NetworkError):
def __init__(self):
super(TimedOut, self).__init__('Timed out')

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -44,9 +44,8 @@ class Botan(object):
urlopen(request)
return True
except HTTPError as error:
self.logger.warn('Botan track error ' +
str(error.code) +
':' + error.read().decode('utf-8'))
self.logger.warn('Botan track error ' + str(error.code) + ':' + error.read().decode(
'utf-8'))
return False
except URLError as error:
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
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module facilitates the deprecation of functions"""
import warnings
@ -24,7 +23,9 @@ import warnings
def deprecate(func, old, new):
"""Warn users invoking old to switch to the new function."""
def f(*args, **kwargs):
warnings.warn("{0} is being deprecated, please use {1} from now on".format(old, new))
return func(*args, **kwargs)
return f

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -52,8 +52,7 @@ class ChosenInlineResultTest(BaseTest, unittest.TestCase):
result = telegram.ChosenInlineResult.de_json(self.json_dict)
self.assertEqual(result.result_id, self.result_id)
self.assertDictEqual(result.from_user.to_dict(),
self.from_user.to_dict())
self.assertDictEqual(result.from_user.to_dict(), self.from_user.to_dict())
self.assertEqual(result.query, self.query)
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
# Copyright (C) 2015-2016
@ -16,7 +16,6 @@
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents Tests for Telegram Contact"""
import unittest
@ -65,5 +64,6 @@ class ContactTest(BaseTest, unittest.TestCase):
self.assertEqual(contact['last_name'], self.last_name)
self.assertEqual(contact['user_id'], self.user_id)
if __name__ == '__main__':
unittest.main()

View file

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

View file

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

View file

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

View file

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

View file

@ -35,20 +35,15 @@ class ForceReplyTest(BaseTest, unittest.TestCase):
self.force_reply = True
self.selective = True
self.json_dict = {
'force_reply': self.force_reply,
'selective': self.selective,
}
self.json_dict = {'force_reply': self.force_reply, 'selective': self.selective,}
def test_send_message_with_force_reply(self):
message = self._bot.sendMessage(
self._chat_id,
'Моё судно на воздушной подушке полно угрей',
reply_markup=telegram.ForceReply.de_json(self.json_dict))
message = self._bot.sendMessage(self._chat_id,
'Моё судно на воздушной подушке полно угрей',
reply_markup=telegram.ForceReply.de_json(self.json_dict))
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text,
u'Моё судно на воздушной подушке полно угрей')
self.assertEqual(message.text, u'Моё судно на воздушной подушке полно угрей')
def test_force_reply_de_json(self):
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):
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(
self.json_dict)
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(self.json_dict)
self.assertEqual(inline_keyboard_button.text, self.text)
self.assertEqual(inline_keyboard_button.url, self.url)
self.assertEqual(inline_keyboard_button.callback_data,
self.callback_data)
self.assertEqual(inline_keyboard_button.switch_inline_query,
self.switch_inline_query)
self.assertEqual(inline_keyboard_button.callback_data, self.callback_data)
self.assertEqual(inline_keyboard_button.switch_inline_query, self.switch_inline_query)
def test_inline_keyboard_button_de_json_empty(self):
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(None)
@ -70,14 +67,12 @@ class InlineKeyboardButtonTest(BaseTest, unittest.TestCase):
self.assertFalse(inline_keyboard_button)
def test_inline_keyboard_button_to_json(self):
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(
self.json_dict)
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(self.json_dict)
self.assertTrue(self.is_json(inline_keyboard_button.to_json()))
def test_inline_keyboard_button_to_dict(self):
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(
self.json_dict).to_dict()
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(self.json_dict).to_dict()
self.assertTrue(self.is_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."""
def setUp(self):
self.inline_keyboard = [[telegram.InlineKeyboardButton(
text='button1',
callback_data='data1'), telegram.InlineKeyboardButton(
text='button2', callback_data='data2')]]
self.inline_keyboard = [[telegram.InlineKeyboardButton(text='button1',
callback_data='data1'),
telegram.InlineKeyboardButton(text='button2',
callback_data='data2')]]
self.json_dict = {
'inline_keyboard': [[self.inline_keyboard[0][0].to_dict(),
@ -57,26 +57,21 @@ class InlineKeyboardMarkupTest(BaseTest, unittest.TestCase):
self.assertFalse(inline_keyboard_markup)
def test_inline_keyboard_markup_de_json(self):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(
self.json_dict)
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict)
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard,
list))
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard, list))
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard[0][
0], telegram.InlineKeyboardButton))
def test_inline_keyboard_markup_to_json(self):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(
self.json_dict)
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict)
self.assertTrue(self.is_json(inline_keyboard_markup.to_json()))
def test_inline_keyboard_markup_to_dict(self):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(
self.json_dict)
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict)
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard,
list))
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard, list))
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard[0][
0], telegram.InlineKeyboardButton))

View file

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

View file

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

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