diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 000000000..02302b82d --- /dev/null +++ b/.pre-commit-config.yaml @@ -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'] diff --git a/.travis.yml b/.travis.yml index 0290eea64..5fe9fef59 100644 --- a/.travis.yml +++ b/.travis.yml @@ -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 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index c5e6cfcb3..90876ed26 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -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.** diff --git a/Makefile b/Makefile index 04b32a1ac..85bc6b813 100644 --- a/Makefile +++ b/Makefile @@ -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)" diff --git a/requirements-dev.txt b/requirements-dev.txt index 3cd235bb0..ae6f0047e 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -3,4 +3,7 @@ nose pep257 pylint unittest2 -flaky \ No newline at end of file +flaky +yapf +pre-commit +pre-commit-hooks diff --git a/setup.cfg b/setup.cfg index 2b23f9015..b53e47503 100644 --- a/setup.cfg +++ b/setup.cfg @@ -11,3 +11,7 @@ upload-dir = docs/build/html [flake8] max-line-length = 99 + +[yapf] +based_on_style = google +column_limit = 99 diff --git a/telegram/__init__.py b/telegram/__init__.py index 431140606..ad9e231a4 100644 --- a/telegram/__init__.py +++ b/telegram/__init__.py @@ -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 diff --git a/telegram/audio.py b/telegram/audio.py index ae12687df..3a35e7112 100644 --- a/telegram/audio.py +++ b/telegram/audio.py @@ -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) diff --git a/telegram/base.py b/telegram/base.py index 24033c306..4123d1412 100644 --- a/telegram/base.py +++ b/telegram/base.py @@ -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 diff --git a/telegram/bot.py b/telegram/bot.py index 4f2b2e238..3147f2e37 100644 --- a/telegram/bot.py +++ b/telegram/bot.py @@ -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 diff --git a/telegram/callbackquery.py b/telegram/callbackquery.py index 4920fde40..440ddce8c 100644 --- a/telegram/callbackquery.py +++ b/telegram/callbackquery.py @@ -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 diff --git a/telegram/chat.py b/telegram/chat.py index 24143dcf6..55b3c2c0a 100644 --- a/telegram/chat.py +++ b/telegram/chat.py @@ -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 diff --git a/telegram/chataction.py b/telegram/chataction.py index 52ca3462a..398656db6 100644 --- a/telegram/chataction.py +++ b/telegram/chataction.py @@ -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.""" diff --git a/telegram/choseninlineresult.py b/telegram/choseninlineresult.py index 2b897d327..2de914be7 100644 --- a/telegram/choseninlineresult.py +++ b/telegram/choseninlineresult.py @@ -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 diff --git a/telegram/contact.py b/telegram/contact.py index d9ee7e33f..a755e3eeb 100644 --- a/telegram/contact.py +++ b/telegram/contact.py @@ -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 diff --git a/telegram/document.py b/telegram/document.py index 42949b236..d9ea79d13 100644 --- a/telegram/document.py +++ b/telegram/document.py @@ -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 diff --git a/telegram/emoji.py b/telegram/emoji.py index d6db95e4c..c3dff9aea 100644 --- a/telegram/emoji.py +++ b/telegram/emoji.py @@ -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') diff --git a/telegram/error.py b/telegram/error.py index 6416aa63e..0f9005b40 100644 --- a/telegram/error.py +++ b/telegram/error.py @@ -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') diff --git a/telegram/ext/__init__.py b/telegram/ext/__init__.py index 3c6eb304f..59a8b800d 100644 --- a/telegram/ext/__init__.py +++ b/telegram/ext/__init__.py @@ -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') diff --git a/telegram/ext/callbackqueryhandler.py b/telegram/ext/callbackqueryhandler.py index da749a584..669943c96 100644 --- a/telegram/ext/callbackqueryhandler.py +++ b/telegram/ext/callbackqueryhandler.py @@ -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 diff --git a/telegram/ext/choseninlineresulthandler.py b/telegram/ext/choseninlineresulthandler.py index 000c4ab36..09e8bb3a0 100644 --- a/telegram/ext/choseninlineresulthandler.py +++ b/telegram/ext/choseninlineresulthandler.py @@ -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 diff --git a/telegram/ext/commandhandler.py b/telegram/ext/commandhandler.py index 5e427e124..92ce9c5c7 100644 --- a/telegram/ext/commandhandler.py +++ b/telegram/ext/commandhandler.py @@ -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) diff --git a/telegram/ext/dispatcher.py b/telegram/ext/dispatcher.py index 386972262..a1db87b79 100644 --- a/telegram/ext/dispatcher.py +++ b/telegram/ext/dispatcher.py @@ -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") diff --git a/telegram/ext/handler.py b/telegram/ext/handler.py index fd93b5f42..964bbb98a 100644 --- a/telegram/ext/handler.py +++ b/telegram/ext/handler.py @@ -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") diff --git a/telegram/ext/inlinequeryhandler.py b/telegram/ext/inlinequeryhandler.py index 6f0f6e26a..12cedfe61 100644 --- a/telegram/ext/inlinequeryhandler.py +++ b/telegram/ext/inlinequeryhandler.py @@ -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 diff --git a/telegram/ext/jobqueue.py b/telegram/ext/jobqueue.py index a8c461e10..616468399 100644 --- a/telegram/ext/jobqueue.py +++ b/telegram/ext/jobqueue.py @@ -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: diff --git a/telegram/ext/messagehandler.py b/telegram/ext/messagehandler.py index 0da942b63..8d74d607b 100644 --- a/telegram/ext/messagehandler.py +++ b/telegram/ext/messagehandler.py @@ -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): diff --git a/telegram/ext/regexhandler.py b/telegram/ext/regexhandler.py index 0f82ddf8b..958f8f6d4 100644 --- a/telegram/ext/regexhandler.py +++ b/telegram/ext/regexhandler.py @@ -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: diff --git a/telegram/ext/stringcommandhandler.py b/telegram/ext/stringcommandhandler.py index c9d5f46a5..0689a9fa2 100644 --- a/telegram/ext/stringcommandhandler.py +++ b/telegram/ext/stringcommandhandler.py @@ -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): diff --git a/telegram/ext/stringregexhandler.py b/telegram/ext/stringregexhandler.py index 020ba0953..5ec3896e8 100644 --- a/telegram/ext/stringregexhandler.py +++ b/telegram/ext/stringregexhandler.py @@ -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) diff --git a/telegram/ext/typehandler.py b/telegram/ext/typehandler.py index d72b5bf24..f8ad76ceb 100644 --- a/telegram/ext/typehandler.py +++ b/telegram/ext/typehandler.py @@ -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 diff --git a/telegram/ext/updater.py b/telegram/ext/updater.py index 31d86360e..24e24e1f9 100644 --- a/telegram/ext/updater.py +++ b/telegram/ext/updater.py @@ -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 = [] diff --git a/telegram/file.py b/telegram/file.py index 125898554..74d02a7c4 100644 --- a/telegram/file.py +++ b/telegram/file.py @@ -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): diff --git a/telegram/forcereply.py b/telegram/forcereply.py index 39486a3f4..4388b1cd5 100644 --- a/telegram/forcereply.py +++ b/telegram/forcereply.py @@ -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 diff --git a/telegram/inlinekeyboardbutton.py b/telegram/inlinekeyboardbutton.py index 455748dac..0ef8b2954 100644 --- a/telegram/inlinekeyboardbutton.py +++ b/telegram/inlinekeyboardbutton.py @@ -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 diff --git a/telegram/inlinekeyboardmarkup.py b/telegram/inlinekeyboardmarkup.py index 08e0fa116..fadef209d 100644 --- a/telegram/inlinekeyboardmarkup.py +++ b/telegram/inlinekeyboardmarkup.py @@ -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 diff --git a/telegram/inlinequery.py b/telegram/inlinequery.py index 2a9c883bf..83426c2ef 100644 --- a/telegram/inlinequery.py +++ b/telegram/inlinequery.py @@ -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 diff --git a/telegram/inlinequeryresult.py b/telegram/inlinequeryresult.py index 46daf7739..6ecb7de16 100644 --- a/telegram/inlinequeryresult.py +++ b/telegram/inlinequeryresult.py @@ -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) diff --git a/telegram/inlinequeryresultarticle.py b/telegram/inlinequeryresultarticle.py index 936ff52c0..b94f93059 100644 --- a/telegram/inlinequeryresultarticle.py +++ b/telegram/inlinequeryresultarticle.py @@ -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) diff --git a/telegram/inlinequeryresultaudio.py b/telegram/inlinequeryresultaudio.py index 2b2988ad2..81c777336 100644 --- a/telegram/inlinequeryresultaudio.py +++ b/telegram/inlinequeryresultaudio.py @@ -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) diff --git a/telegram/inlinequeryresultcachedaudio.py b/telegram/inlinequeryresultcachedaudio.py index 669733f84..9f1c9b731 100644 --- a/telegram/inlinequeryresultcachedaudio.py +++ b/telegram/inlinequeryresultcachedaudio.py @@ -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) diff --git a/telegram/inlinequeryresultcacheddocument.py b/telegram/inlinequeryresultcacheddocument.py index d78dc2bd1..fa11f9339 100644 --- a/telegram/inlinequeryresultcacheddocument.py +++ b/telegram/inlinequeryresultcacheddocument.py @@ -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) diff --git a/telegram/inlinequeryresultcachedgif.py b/telegram/inlinequeryresultcachedgif.py index 6ad4268ac..9b0429b78 100644 --- a/telegram/inlinequeryresultcachedgif.py +++ b/telegram/inlinequeryresultcachedgif.py @@ -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) diff --git a/telegram/inlinequeryresultcachedmpeg4gif.py b/telegram/inlinequeryresultcachedmpeg4gif.py index 7c5d675ae..fb3350658 100644 --- a/telegram/inlinequeryresultcachedmpeg4gif.py +++ b/telegram/inlinequeryresultcachedmpeg4gif.py @@ -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) diff --git a/telegram/inlinequeryresultcachedphoto.py b/telegram/inlinequeryresultcachedphoto.py index abb76a941..be04b8ef4 100644 --- a/telegram/inlinequeryresultcachedphoto.py +++ b/telegram/inlinequeryresultcachedphoto.py @@ -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) diff --git a/telegram/inlinequeryresultcachedsticker.py b/telegram/inlinequeryresultcachedsticker.py index 1d01ff57f..c6cc54c69 100644 --- a/telegram/inlinequeryresultcachedsticker.py +++ b/telegram/inlinequeryresultcachedsticker.py @@ -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) diff --git a/telegram/inlinequeryresultcachedvideo.py b/telegram/inlinequeryresultcachedvideo.py index 807ab4060..060fa47b1 100644 --- a/telegram/inlinequeryresultcachedvideo.py +++ b/telegram/inlinequeryresultcachedvideo.py @@ -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) diff --git a/telegram/inlinequeryresultcachedvoice.py b/telegram/inlinequeryresultcachedvoice.py index 61ba9cb4e..11312b129 100644 --- a/telegram/inlinequeryresultcachedvoice.py +++ b/telegram/inlinequeryresultcachedvoice.py @@ -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) diff --git a/telegram/inlinequeryresultcontact.py b/telegram/inlinequeryresultcontact.py index ada569e30..e475654c3 100644 --- a/telegram/inlinequeryresultcontact.py +++ b/telegram/inlinequeryresultcontact.py @@ -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) diff --git a/telegram/inlinequeryresultdocument.py b/telegram/inlinequeryresultdocument.py index 0c0735cf9..36f70ba61 100644 --- a/telegram/inlinequeryresultdocument.py +++ b/telegram/inlinequeryresultdocument.py @@ -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) diff --git a/telegram/inlinequeryresultgif.py b/telegram/inlinequeryresultgif.py index ae3589f6b..253880c3c 100644 --- a/telegram/inlinequeryresultgif.py +++ b/telegram/inlinequeryresultgif.py @@ -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) diff --git a/telegram/inlinequeryresultlocation.py b/telegram/inlinequeryresultlocation.py index a5d77179f..00428285c 100644 --- a/telegram/inlinequeryresultlocation.py +++ b/telegram/inlinequeryresultlocation.py @@ -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) diff --git a/telegram/inlinequeryresultmpeg4gif.py b/telegram/inlinequeryresultmpeg4gif.py index 9f2232eea..8c331f31b 100644 --- a/telegram/inlinequeryresultmpeg4gif.py +++ b/telegram/inlinequeryresultmpeg4gif.py @@ -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) diff --git a/telegram/inlinequeryresultphoto.py b/telegram/inlinequeryresultphoto.py index 76afaf695..7037d3d61 100644 --- a/telegram/inlinequeryresultphoto.py +++ b/telegram/inlinequeryresultphoto.py @@ -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) diff --git a/telegram/inlinequeryresultvenue.py b/telegram/inlinequeryresultvenue.py index bd1189c2d..13af862e1 100644 --- a/telegram/inlinequeryresultvenue.py +++ b/telegram/inlinequeryresultvenue.py @@ -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) diff --git a/telegram/inlinequeryresultvideo.py b/telegram/inlinequeryresultvideo.py index 6f1e49188..f8efb03c4 100644 --- a/telegram/inlinequeryresultvideo.py +++ b/telegram/inlinequeryresultvideo.py @@ -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) diff --git a/telegram/inlinequeryresultvoice.py b/telegram/inlinequeryresultvoice.py index a63156dc0..fb3544bfc 100644 --- a/telegram/inlinequeryresultvoice.py +++ b/telegram/inlinequeryresultvoice.py @@ -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) diff --git a/telegram/inputcontactmessagecontent.py b/telegram/inputcontactmessagecontent.py index c02112a9d..2dd41c4cf 100644 --- a/telegram/inputcontactmessagecontent.py +++ b/telegram/inputcontactmessagecontent.py @@ -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 diff --git a/telegram/inputfile.py b/telegram/inputfile.py index 55fce2b27..8c9276eb5 100644 --- a/telegram/inputfile.py +++ b/telegram/inputfile.py @@ -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 diff --git a/telegram/inputlocationmessagecontent.py b/telegram/inputlocationmessagecontent.py index 0eb987121..b975cd118 100644 --- a/telegram/inputlocationmessagecontent.py +++ b/telegram/inputlocationmessagecontent.py @@ -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 diff --git a/telegram/inputmessagecontent.py b/telegram/inputmessagecontent.py index 538a44563..56072681d 100644 --- a/telegram/inputmessagecontent.py +++ b/telegram/inputmessagecontent.py @@ -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""" diff --git a/telegram/inputtextmessagecontent.py b/telegram/inputtextmessagecontent.py index 7d43430bf..d78eb9bc7 100644 --- a/telegram/inputtextmessagecontent.py +++ b/telegram/inputtextmessagecontent.py @@ -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 diff --git a/telegram/inputvenuemessagecontent.py b/telegram/inputvenuemessagecontent.py index 99ef5ac42..d34d48a50 100644 --- a/telegram/inputvenuemessagecontent.py +++ b/telegram/inputvenuemessagecontent.py @@ -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 diff --git a/telegram/keyboardbutton.py b/telegram/keyboardbutton.py index 59422f8b9..904c0631c 100644 --- a/telegram/keyboardbutton.py +++ b/telegram/keyboardbutton.py @@ -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 diff --git a/telegram/location.py b/telegram/location.py index 8f7152a14..3b84b7ad0 100644 --- a/telegram/location.py +++ b/telegram/location.py @@ -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) diff --git a/telegram/message.py b/telegram/message.py index bcb0694d2..2e2471ee3 100644 --- a/telegram/message.py +++ b/telegram/message.py @@ -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')) diff --git a/telegram/messageentity.py b/telegram/messageentity.py index 179f74feb..4b0e03487 100644 --- a/telegram/messageentity.py +++ b/telegram/messageentity.py @@ -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 diff --git a/telegram/nullhandler.py b/telegram/nullhandler.py index 129c2ac5c..4783fa1c3 100644 --- a/telegram/nullhandler.py +++ b/telegram/nullhandler.py @@ -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 diff --git a/telegram/parsemode.py b/telegram/parsemode.py index eecb6cdf8..840e5cad8 100644 --- a/telegram/parsemode.py +++ b/telegram/parsemode.py @@ -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.""" diff --git a/telegram/photosize.py b/telegram/photosize.py index 694cb5252..a7545e506 100644 --- a/telegram/photosize.py +++ b/telegram/photosize.py @@ -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): diff --git a/telegram/replykeyboardhide.py b/telegram/replykeyboardhide.py index eb76cc778..6c1f37c72 100644 --- a/telegram/replykeyboardhide.py +++ b/telegram/replykeyboardhide.py @@ -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 diff --git a/telegram/replykeyboardmarkup.py b/telegram/replykeyboardmarkup.py index e45f5c38a..9ff66cb6d 100644 --- a/telegram/replykeyboardmarkup.py +++ b/telegram/replykeyboardmarkup.py @@ -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 diff --git a/telegram/replymarkup.py b/telegram/replymarkup.py index 83fa5e3e3..c0a0bc55d 100644 --- a/telegram/replymarkup.py +++ b/telegram/replymarkup.py @@ -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 diff --git a/telegram/sticker.py b/telegram/sticker.py index 1df6cb7db..ad2b6f080 100644 --- a/telegram/sticker.py +++ b/telegram/sticker.py @@ -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) diff --git a/telegram/update.py b/telegram/update.py index 9b60b0be2..17cc16603 100644 --- a/telegram/update.py +++ b/telegram/update.py @@ -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) diff --git a/telegram/user.py b/telegram/user.py index 6ce1cde26..c1b340015 100644 --- a/telegram/user.py +++ b/telegram/user.py @@ -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 diff --git a/telegram/userprofilephotos.py b/telegram/userprofilephotos.py index 20614b1ee..806270c6a 100644 --- a/telegram/userprofilephotos.py +++ b/telegram/userprofilephotos.py @@ -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 diff --git a/telegram/utils/botan.py b/telegram/utils/botan.py index 6aef71f9a..0998fbdea 100644 --- a/telegram/utils/botan.py +++ b/telegram/utils/botan.py @@ -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)) diff --git a/telegram/utils/deprecate.py b/telegram/utils/deprecate.py index 3036f177c..75af2bf9a 100644 --- a/telegram/utils/deprecate.py +++ b/telegram/utils/deprecate.py @@ -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 diff --git a/telegram/utils/request.py b/telegram/utils/request.py index ebbd9281c..b326d6ccf 100644 --- a/telegram/utils/request.py +++ b/telegram/utils/request.py @@ -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: diff --git a/telegram/utils/validate.py b/telegram/utils/validate.py index d8629750a..f340ee5dc 100644 --- a/telegram/utils/validate.py +++ b/telegram/utils/validate.py @@ -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 diff --git a/telegram/utils/webhookhandler.py b/telegram/utils/webhookhandler.py index 2658169e9..92ad280c5 100644 --- a/telegram/utils/webhookhandler.py +++ b/telegram/utils/webhookhandler.py @@ -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) diff --git a/telegram/venue.py b/telegram/venue.py index c1f558fa1..12550ce8e 100644 --- a/telegram/venue.py +++ b/telegram/venue.py @@ -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 diff --git a/telegram/video.py b/telegram/video.py index 110e234cb..d486c19a4 100644 --- a/telegram/video.py +++ b/telegram/video.py @@ -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) diff --git a/telegram/voice.py b/telegram/voice.py index de5950761..8b6c11387 100644 --- a/telegram/voice.py +++ b/telegram/voice.py @@ -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 diff --git a/tests/base.py b/tests/base.py index 7ee934209..6b9824df5 100644 --- a/tests/base.py +++ b/tests/base.py @@ -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) diff --git a/tests/test_audio.py b/tests/test_audio.py index 4e9bb64ad..096c95f2e 100644 --- a/tests/test_audio.py +++ b/tests/test_audio.py @@ -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__': diff --git a/tests/test_bot.py b/tests/test_bot.py index 08fcd4ddc..42aed9cda 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -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) diff --git a/tests/test_chat.py b/tests/test_chat.py index 22d84cf49..3b904dc04 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -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() diff --git a/tests/test_choseninlineresult.py b/tests/test_choseninlineresult.py index 401049aa4..320c84672 100644 --- a/tests/test_choseninlineresult.py +++ b/tests/test_choseninlineresult.py @@ -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): diff --git a/tests/test_contact.py b/tests/test_contact.py index c34cbcbb9..1df539fe6 100644 --- a/tests/test_contact.py +++ b/tests/test_contact.py @@ -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() diff --git a/tests/test_document.py b/tests/test_document.py index 5ace86d72..a8ee206bc 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -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 diff --git a/tests/test_emoji.py b/tests/test_emoji.py index 4df2b5999..2f57aef16 100644 --- a/tests/test_emoji.py +++ b/tests/test_emoji.py @@ -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 diff --git a/tests/test_file.py b/tests/test_file.py index 494a5b9fe..cf1795dfd 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -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 diff --git a/tests/test_filters.py b/tests/test_filters.py index 70e24e60d..58127fc3b 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -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): diff --git a/tests/test_forcereply.py b/tests/test_forcereply.py index 73f51edd4..24d4168fe 100644 --- a/tests/test_forcereply.py +++ b/tests/test_forcereply.py @@ -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) diff --git a/tests/test_inlinekeyboardbutton.py b/tests/test_inlinekeyboardbutton.py index 0ef3d99a3..f28f9682b 100644 --- a/tests/test_inlinekeyboardbutton.py +++ b/tests/test_inlinekeyboardbutton.py @@ -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) diff --git a/tests/test_inlinekeyboardmarkup.py b/tests/test_inlinekeyboardmarkup.py index aa8e13949..069a887ad 100644 --- a/tests/test_inlinekeyboardmarkup.py +++ b/tests/test_inlinekeyboardmarkup.py @@ -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)) diff --git a/tests/test_inlinequery.py b/tests/test_inlinequery.py index 4c59f86cf..98148b596 100644 --- a/tests/test_inlinequery.py +++ b/tests/test_inlinequery.py @@ -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) diff --git a/tests/test_inlinequeryresultarticle.py b/tests/test_inlinequeryresultarticle.py index 032b96567..402f6958c 100644 --- a/tests/test_inlinequeryresultarticle.py +++ b/tests/test_inlinequeryresultarticle.py @@ -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) diff --git a/tests/test_inlinequeryresultaudio.py b/tests/test_inlinequeryresultaudio.py index f2696cf5e..ee850f0a7 100644 --- a/tests/test_inlinequeryresultaudio.py +++ b/tests/test_inlinequeryresultaudio.py @@ -42,8 +42,7 @@ class InlineQueryResultAudioTest(BaseTest, unittest.TestCase): self.title = 'title' self.performer = 'performer' self.audio_duration = 'audio_duration' - 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') ]]) @@ -70,8 +69,7 @@ class InlineQueryResultAudioTest(BaseTest, unittest.TestCase): self.assertEqual(audio.audio_duration, self.audio_duration) self.assertDictEqual(audio.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(audio.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(audio.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_audio_to_json(self): audio = telegram.InlineQueryResultAudio.de_json(self.json_dict) @@ -79,8 +77,7 @@ class InlineQueryResultAudioTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(audio.to_json())) def test_audio_to_dict(self): - audio = telegram.InlineQueryResultAudio.de_json( - self.json_dict).to_dict() + audio = telegram.InlineQueryResultAudio.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(audio)) self.assertDictEqual(self.json_dict, audio) diff --git a/tests/test_inlinequeryresultcachedaudio.py b/tests/test_inlinequeryresultcachedaudio.py index 1ebeba514..072d1ed85 100644 --- a/tests/test_inlinequeryresultcachedaudio.py +++ b/tests/test_inlinequeryresultcachedaudio.py @@ -40,8 +40,7 @@ class InlineQueryResultCachedAudioTest(BaseTest, unittest.TestCase): self.id = 'id' self.type = 'audio' self.audio_file_id = 'audio file id' - 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') ]]) @@ -62,8 +61,7 @@ class InlineQueryResultCachedAudioTest(BaseTest, unittest.TestCase): self.assertEqual(audio.audio_file_id, self.audio_file_id) self.assertDictEqual(audio.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(audio.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(audio.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_audio_to_json(self): audio = telegram.InlineQueryResultCachedAudio.de_json(self.json_dict) @@ -71,8 +69,7 @@ class InlineQueryResultCachedAudioTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(audio.to_json())) def test_audio_to_dict(self): - audio = telegram.InlineQueryResultCachedAudio.de_json( - self.json_dict).to_dict() + audio = telegram.InlineQueryResultCachedAudio.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(audio)) self.assertDictEqual(self.json_dict, audio) diff --git a/tests/test_inlinequeryresultcacheddocument.py b/tests/test_inlinequeryresultcacheddocument.py index 77e1f836c..715589730 100644 --- a/tests/test_inlinequeryresultcacheddocument.py +++ b/tests/test_inlinequeryresultcacheddocument.py @@ -43,8 +43,7 @@ class InlineQueryResultCachedDocumentTest(BaseTest, unittest.TestCase): self.title = 'title' self.caption = 'caption' self.description = 'description' - 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') ]]) @@ -60,8 +59,7 @@ class InlineQueryResultCachedDocumentTest(BaseTest, unittest.TestCase): } def test_document_de_json(self): - document = telegram.InlineQueryResultCachedDocument.de_json( - self.json_dict) + document = telegram.InlineQueryResultCachedDocument.de_json(self.json_dict) self.assertEqual(document.id, self.id) self.assertEqual(document.type, self.type) @@ -71,18 +69,15 @@ class InlineQueryResultCachedDocumentTest(BaseTest, unittest.TestCase): self.assertEqual(document.description, self.description) self.assertDictEqual(document.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(document.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(document.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_document_to_json(self): - document = telegram.InlineQueryResultCachedDocument.de_json( - self.json_dict) + document = telegram.InlineQueryResultCachedDocument.de_json(self.json_dict) self.assertTrue(self.is_json(document.to_json())) def test_document_to_dict(self): - document = telegram.InlineQueryResultCachedDocument.de_json( - self.json_dict).to_dict() + document = telegram.InlineQueryResultCachedDocument.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(document)) self.assertDictEqual(self.json_dict, document) diff --git a/tests/test_inlinequeryresultcachedgif.py b/tests/test_inlinequeryresultcachedgif.py index b15c1eb47..01b7ebc10 100644 --- a/tests/test_inlinequeryresultcachedgif.py +++ b/tests/test_inlinequeryresultcachedgif.py @@ -41,8 +41,7 @@ class InlineQueryResultCachedGifTest(BaseTest, unittest.TestCase): self.gif_file_id = 'gif file id' self.title = 'title' self.caption = 'caption' - 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') ]]) @@ -67,8 +66,7 @@ class InlineQueryResultCachedGifTest(BaseTest, unittest.TestCase): self.assertEqual(gif.caption, self.caption) self.assertDictEqual(gif.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(gif.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(gif.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_gif_to_json(self): gif = telegram.InlineQueryResultCachedGif.de_json(self.json_dict) @@ -76,8 +74,7 @@ class InlineQueryResultCachedGifTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(gif.to_json())) def test_gif_to_dict(self): - gif = telegram.InlineQueryResultCachedGif.de_json( - self.json_dict).to_dict() + gif = telegram.InlineQueryResultCachedGif.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(gif)) self.assertDictEqual(self.json_dict, gif) diff --git a/tests/test_inlinequeryresultcachedmpeg4gif.py b/tests/test_inlinequeryresultcachedmpeg4gif.py index 968a32df6..90abdf232 100644 --- a/tests/test_inlinequeryresultcachedmpeg4gif.py +++ b/tests/test_inlinequeryresultcachedmpeg4gif.py @@ -42,8 +42,7 @@ class InlineQueryResultCachedMpeg4GifTest(BaseTest, unittest.TestCase): self.mpeg4_file_id = 'mpeg4 file id' self.title = 'title' self.caption = 'caption' - 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') ]]) @@ -59,8 +58,7 @@ class InlineQueryResultCachedMpeg4GifTest(BaseTest, unittest.TestCase): } def test_mpeg4_de_json(self): - mpeg4 = telegram.InlineQueryResultCachedMpeg4Gif.de_json( - self.json_dict) + mpeg4 = telegram.InlineQueryResultCachedMpeg4Gif.de_json(self.json_dict) self.assertEqual(mpeg4.type, self.type) self.assertEqual(mpeg4.id, self.id) @@ -69,18 +67,15 @@ class InlineQueryResultCachedMpeg4GifTest(BaseTest, unittest.TestCase): self.assertEqual(mpeg4.caption, self.caption) self.assertDictEqual(mpeg4.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(mpeg4.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(mpeg4.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_mpeg4_to_json(self): - mpeg4 = telegram.InlineQueryResultCachedMpeg4Gif.de_json( - self.json_dict) + mpeg4 = telegram.InlineQueryResultCachedMpeg4Gif.de_json(self.json_dict) self.assertTrue(self.is_json(mpeg4.to_json())) def test_mpeg4_to_dict(self): - mpeg4 = telegram.InlineQueryResultCachedMpeg4Gif.de_json( - self.json_dict).to_dict() + mpeg4 = telegram.InlineQueryResultCachedMpeg4Gif.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(mpeg4)) self.assertDictEqual(self.json_dict, mpeg4) diff --git a/tests/test_inlinequeryresultcachedphoto.py b/tests/test_inlinequeryresultcachedphoto.py index 1542197bf..51e959bf3 100644 --- a/tests/test_inlinequeryresultcachedphoto.py +++ b/tests/test_inlinequeryresultcachedphoto.py @@ -43,8 +43,7 @@ class InlineQueryResultCachedPhotoTest(BaseTest, unittest.TestCase): self.title = 'title' self.description = 'description' self.caption = 'caption' - 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') ]]) @@ -71,8 +70,7 @@ class InlineQueryResultCachedPhotoTest(BaseTest, unittest.TestCase): self.assertEqual(photo.caption, self.caption) self.assertDictEqual(photo.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(photo.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(photo.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_photo_to_json(self): photo = telegram.InlineQueryResultCachedPhoto.de_json(self.json_dict) @@ -80,8 +78,7 @@ class InlineQueryResultCachedPhotoTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(photo.to_json())) def test_photo_to_dict(self): - photo = telegram.InlineQueryResultCachedPhoto.de_json( - self.json_dict).to_dict() + photo = telegram.InlineQueryResultCachedPhoto.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(photo)) self.assertDictEqual(self.json_dict, photo) diff --git a/tests/test_inlinequeryresultcachedsticker.py b/tests/test_inlinequeryresultcachedsticker.py index 04bbcf44f..7e486740d 100644 --- a/tests/test_inlinequeryresultcachedsticker.py +++ b/tests/test_inlinequeryresultcachedsticker.py @@ -40,8 +40,7 @@ class InlineQueryResultCachedStickerTest(BaseTest, unittest.TestCase): self.id = 'id' self.type = 'sticker' self.sticker_file_id = 'sticker file id' - 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') ]]) @@ -55,26 +54,22 @@ class InlineQueryResultCachedStickerTest(BaseTest, unittest.TestCase): } def test_sticker_de_json(self): - sticker = telegram.InlineQueryResultCachedSticker.de_json( - self.json_dict) + sticker = telegram.InlineQueryResultCachedSticker.de_json(self.json_dict) self.assertEqual(sticker.type, self.type) self.assertEqual(sticker.id, self.id) self.assertEqual(sticker.sticker_file_id, self.sticker_file_id) self.assertDictEqual(sticker.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(sticker.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(sticker.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_sticker_to_json(self): - sticker = telegram.InlineQueryResultCachedSticker.de_json( - self.json_dict) + sticker = telegram.InlineQueryResultCachedSticker.de_json(self.json_dict) self.assertTrue(self.is_json(sticker.to_json())) def test_sticker_to_dict(self): - sticker = telegram.InlineQueryResultCachedSticker.de_json( - self.json_dict).to_dict() + sticker = telegram.InlineQueryResultCachedSticker.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(sticker)) self.assertDictEqual(self.json_dict, sticker) diff --git a/tests/test_inlinequeryresultcachedvideo.py b/tests/test_inlinequeryresultcachedvideo.py index 3b0c43628..450dbad76 100644 --- a/tests/test_inlinequeryresultcachedvideo.py +++ b/tests/test_inlinequeryresultcachedvideo.py @@ -43,8 +43,7 @@ class InlineQueryResultCachedVideoTest(BaseTest, unittest.TestCase): self.title = 'title' self.caption = 'caption' self.description = 'description' - 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') ]]) @@ -71,8 +70,7 @@ class InlineQueryResultCachedVideoTest(BaseTest, unittest.TestCase): self.assertEqual(video.caption, self.caption) self.assertDictEqual(video.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(video.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(video.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_video_to_json(self): video = telegram.InlineQueryResultCachedVideo.de_json(self.json_dict) @@ -80,8 +78,7 @@ class InlineQueryResultCachedVideoTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(video.to_json())) def test_video_to_dict(self): - video = telegram.InlineQueryResultCachedVideo.de_json( - self.json_dict).to_dict() + video = telegram.InlineQueryResultCachedVideo.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(video)) self.assertDictEqual(self.json_dict, video) diff --git a/tests/test_inlinequeryresultcachedvoice.py b/tests/test_inlinequeryresultcachedvoice.py index 56615aabb..50fed9b06 100644 --- a/tests/test_inlinequeryresultcachedvoice.py +++ b/tests/test_inlinequeryresultcachedvoice.py @@ -42,8 +42,7 @@ class InlineQueryResultCachedVoiceTest(BaseTest, unittest.TestCase): self.voice_file_id = 'voice file id' self.title = 'title' self.description = 'description' - 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') ]]) @@ -68,8 +67,7 @@ class InlineQueryResultCachedVoiceTest(BaseTest, unittest.TestCase): self.assertEqual(voice.description, self.description) self.assertDictEqual(voice.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(voice.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(voice.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_voice_to_json(self): voice = telegram.InlineQueryResultCachedVoice.de_json(self.json_dict) @@ -77,8 +75,7 @@ class InlineQueryResultCachedVoiceTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(voice.to_json())) def test_voice_to_dict(self): - voice = telegram.InlineQueryResultCachedVoice.de_json( - self.json_dict).to_dict() + voice = telegram.InlineQueryResultCachedVoice.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(voice)) self.assertDictEqual(self.json_dict, voice) diff --git a/tests/test_inlinequeryresultcontact.py b/tests/test_inlinequeryresultcontact.py index d0f15458c..d9b43ed84 100644 --- a/tests/test_inlinequeryresultcontact.py +++ b/tests/test_inlinequeryresultcontact.py @@ -44,8 +44,7 @@ class InlineQueryResultContactTest(BaseTest, unittest.TestCase): self.thumb_url = 'thumb url' self.thumb_width = 10 self.thumb_height = 15 - 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') ]]) @@ -75,8 +74,7 @@ class InlineQueryResultContactTest(BaseTest, unittest.TestCase): self.assertEqual(contact.thumb_height, self.thumb_height) self.assertDictEqual(contact.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(contact.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(contact.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_contact_to_json(self): contact = telegram.InlineQueryResultContact.de_json(self.json_dict) @@ -84,8 +82,7 @@ class InlineQueryResultContactTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(contact.to_json())) def test_contact_to_dict(self): - contact = telegram.InlineQueryResultContact.de_json( - self.json_dict).to_dict() + contact = telegram.InlineQueryResultContact.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(contact)) self.assertDictEqual(self.json_dict, contact) diff --git a/tests/test_inlinequeryresultdocument.py b/tests/test_inlinequeryresultdocument.py index eb0007928..cff1b0a9f 100644 --- a/tests/test_inlinequeryresultdocument.py +++ b/tests/test_inlinequeryresultdocument.py @@ -46,8 +46,7 @@ class InlineQueryResultDocumentTest(BaseTest, unittest.TestCase): self.thumb_url = 'thumb url' self.thumb_width = 10 self.thumb_height = 15 - 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') ]]) @@ -81,8 +80,7 @@ class InlineQueryResultDocumentTest(BaseTest, unittest.TestCase): self.assertEqual(document.thumb_height, self.thumb_height) self.assertDictEqual(document.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(document.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(document.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_document_to_json(self): document = telegram.InlineQueryResultDocument.de_json(self.json_dict) @@ -90,8 +88,7 @@ class InlineQueryResultDocumentTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(document.to_json())) def test_document_to_dict(self): - document = telegram.InlineQueryResultDocument.de_json( - self.json_dict).to_dict() + document = telegram.InlineQueryResultDocument.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(document)) self.assertDictEqual(self.json_dict, document) diff --git a/tests/test_inlinequeryresultgif.py b/tests/test_inlinequeryresultgif.py index 27c5b52e0..05694ff89 100644 --- a/tests/test_inlinequeryresultgif.py +++ b/tests/test_inlinequeryresultgif.py @@ -44,8 +44,7 @@ class InlineQueryResultGifTest(BaseTest, unittest.TestCase): self.thumb_url = 'thumb url' self.title = 'title' self.caption = 'caption' - 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') ]]) @@ -76,8 +75,7 @@ class InlineQueryResultGifTest(BaseTest, unittest.TestCase): self.assertEqual(gif.caption, self.caption) self.assertDictEqual(gif.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(gif.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(gif.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_gif_to_json(self): gif = telegram.InlineQueryResultGif.de_json(self.json_dict) diff --git a/tests/test_inlinequeryresultlocation.py b/tests/test_inlinequeryresultlocation.py index e85cd5cad..55031b02e 100644 --- a/tests/test_inlinequeryresultlocation.py +++ b/tests/test_inlinequeryresultlocation.py @@ -44,8 +44,7 @@ class InlineQueryResultLocationTest(BaseTest, unittest.TestCase): self.thumb_url = 'thumb url' self.thumb_width = 10 self.thumb_height = 15 - 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') ]]) @@ -75,8 +74,7 @@ class InlineQueryResultLocationTest(BaseTest, unittest.TestCase): self.assertEqual(location.thumb_height, self.thumb_height) self.assertDictEqual(location.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(location.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(location.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_location_to_json(self): location = telegram.InlineQueryResultLocation.de_json(self.json_dict) @@ -84,8 +82,7 @@ class InlineQueryResultLocationTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(location.to_json())) def test_location_to_dict(self): - location = telegram.InlineQueryResultLocation.de_json( - self.json_dict).to_dict() + location = telegram.InlineQueryResultLocation.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(location)) self.assertDictEqual(self.json_dict, location) diff --git a/tests/test_inlinequeryresultmpeg4gif.py b/tests/test_inlinequeryresultmpeg4gif.py index b6777f654..572a12782 100644 --- a/tests/test_inlinequeryresultmpeg4gif.py +++ b/tests/test_inlinequeryresultmpeg4gif.py @@ -44,8 +44,7 @@ class InlineQueryResultMpeg4GifTest(BaseTest, unittest.TestCase): self.thumb_url = 'thumb url' self.title = 'title' self.caption = 'caption' - 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') ]]) @@ -76,8 +75,7 @@ class InlineQueryResultMpeg4GifTest(BaseTest, unittest.TestCase): self.assertEqual(mpeg4.caption, self.caption) self.assertDictEqual(mpeg4.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(mpeg4.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(mpeg4.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_mpeg4_to_json(self): mpeg4 = telegram.InlineQueryResultMpeg4Gif.de_json(self.json_dict) @@ -85,8 +83,7 @@ class InlineQueryResultMpeg4GifTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(mpeg4.to_json())) def test_mpeg4_to_dict(self): - mpeg4 = telegram.InlineQueryResultMpeg4Gif.de_json( - self.json_dict).to_dict() + mpeg4 = telegram.InlineQueryResultMpeg4Gif.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(mpeg4)) self.assertDictEqual(self.json_dict, mpeg4) diff --git a/tests/test_inlinequeryresultphoto.py b/tests/test_inlinequeryresultphoto.py index c7d259858..fd1176109 100644 --- a/tests/test_inlinequeryresultphoto.py +++ b/tests/test_inlinequeryresultphoto.py @@ -45,8 +45,7 @@ class InlineQueryResultPhotoTest(BaseTest, unittest.TestCase): self.title = 'title' self.description = 'description' self.caption = 'caption' - 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') ]]) @@ -79,8 +78,7 @@ class InlineQueryResultPhotoTest(BaseTest, unittest.TestCase): self.assertEqual(photo.caption, self.caption) self.assertDictEqual(photo.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(photo.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(photo.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_photo_to_json(self): photo = telegram.InlineQueryResultPhoto.de_json(self.json_dict) @@ -88,8 +86,7 @@ class InlineQueryResultPhotoTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(photo.to_json())) def test_photo_to_dict(self): - photo = telegram.InlineQueryResultPhoto.de_json( - self.json_dict).to_dict() + photo = telegram.InlineQueryResultPhoto.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(photo)) self.assertDictEqual(self.json_dict, photo) diff --git a/tests/test_inlinequeryresultvenue.py b/tests/test_inlinequeryresultvenue.py index a2c177b1c..c0eaefd92 100644 --- a/tests/test_inlinequeryresultvenue.py +++ b/tests/test_inlinequeryresultvenue.py @@ -46,8 +46,7 @@ class InlineQueryResultVenueTest(BaseTest, unittest.TestCase): self.thumb_url = 'thumb url' self.thumb_width = 10 self.thumb_height = 15 - 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') ]]) @@ -81,8 +80,7 @@ class InlineQueryResultVenueTest(BaseTest, unittest.TestCase): self.assertEqual(venue.thumb_height, self.thumb_height) self.assertDictEqual(venue.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(venue.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(venue.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_venue_to_json(self): venue = telegram.InlineQueryResultVenue.de_json(self.json_dict) @@ -90,8 +88,7 @@ class InlineQueryResultVenueTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(venue.to_json())) def test_venue_to_dict(self): - venue = telegram.InlineQueryResultVenue.de_json( - self.json_dict).to_dict() + venue = telegram.InlineQueryResultVenue.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(venue)) self.assertDictEqual(self.json_dict, venue) diff --git a/tests/test_inlinequeryresultvideo.py b/tests/test_inlinequeryresultvideo.py index a72ba52ba..60c4ea0da 100644 --- a/tests/test_inlinequeryresultvideo.py +++ b/tests/test_inlinequeryresultvideo.py @@ -47,8 +47,7 @@ class InlineQueryResultVideoTest(BaseTest, unittest.TestCase): self.title = 'title' self.caption = 'caption' self.description = 'description' - 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') ]]) @@ -85,8 +84,7 @@ class InlineQueryResultVideoTest(BaseTest, unittest.TestCase): self.assertEqual(video.caption, self.caption) self.assertDictEqual(video.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(video.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(video.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_video_to_json(self): video = telegram.InlineQueryResultVideo.de_json(self.json_dict) @@ -94,8 +92,7 @@ class InlineQueryResultVideoTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(video.to_json())) def test_video_to_dict(self): - video = telegram.InlineQueryResultVideo.de_json( - self.json_dict).to_dict() + video = telegram.InlineQueryResultVideo.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(video)) self.assertDictEqual(self.json_dict, video) diff --git a/tests/test_inlinequeryresultvoice.py b/tests/test_inlinequeryresultvoice.py index 6b47ffdcd..b39bd54cb 100644 --- a/tests/test_inlinequeryresultvoice.py +++ b/tests/test_inlinequeryresultvoice.py @@ -41,8 +41,7 @@ class InlineQueryResultVoiceTest(BaseTest, unittest.TestCase): self.voice_url = 'voice url' self.title = 'title' self.voice_duration = 'voice_duration' - 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') ]]) @@ -67,8 +66,7 @@ class InlineQueryResultVoiceTest(BaseTest, unittest.TestCase): self.assertEqual(voice.voice_duration, self.voice_duration) self.assertDictEqual(voice.input_message_content.to_dict(), self.input_message_content.to_dict()) - self.assertDictEqual(voice.reply_markup.to_dict(), - self.reply_markup.to_dict()) + self.assertDictEqual(voice.reply_markup.to_dict(), self.reply_markup.to_dict()) def test_voice_to_json(self): voice = telegram.InlineQueryResultVoice.de_json(self.json_dict) @@ -76,8 +74,7 @@ class InlineQueryResultVoiceTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(voice.to_json())) def test_voice_to_dict(self): - voice = telegram.InlineQueryResultVoice.de_json( - self.json_dict).to_dict() + voice = telegram.InlineQueryResultVoice.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(voice)) self.assertDictEqual(self.json_dict, voice) diff --git a/tests/test_inputcontactmessagecontent.py b/tests/test_inputcontactmessagecontent.py index da90ada01..a3308eea6 100644 --- a/tests/test_inputcontactmessagecontent.py +++ b/tests/test_inputcontactmessagecontent.py @@ -74,8 +74,7 @@ class InputContactMessageContentTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(icmc.to_json())) def test_icmc_to_dict(self): - icmc = telegram.InputContactMessageContent.de_json( - self.json_dict).to_dict() + icmc = telegram.InputContactMessageContent.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(icmc)) self.assertDictEqual(self.json_dict, icmc) diff --git a/tests/test_inputlocationmessagecontent.py b/tests/test_inputlocationmessagecontent.py index 2a8856b9c..11d0e46c9 100644 --- a/tests/test_inputlocationmessagecontent.py +++ b/tests/test_inputlocationmessagecontent.py @@ -39,10 +39,7 @@ class InputLocationMessageContentTest(BaseTest, unittest.TestCase): self.latitude = 1. self.longitude = 2. - self.json_dict = { - 'longitude': self.longitude, - 'latitude': self.latitude, - } + self.json_dict = {'longitude': self.longitude, 'latitude': self.latitude,} def test_ilmc_de_json(self): ilmc = telegram.InputLocationMessageContent.de_json(self.json_dict) @@ -72,8 +69,7 @@ class InputLocationMessageContentTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(ilmc.to_json())) def test_ilmc_to_dict(self): - ilmc = telegram.InputLocationMessageContent.de_json( - self.json_dict).to_dict() + ilmc = telegram.InputLocationMessageContent.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(ilmc)) self.assertDictEqual(self.json_dict, ilmc) diff --git a/tests/test_inputtextmessagecontent.py b/tests/test_inputtextmessagecontent.py index d9311fa0b..589186e3d 100644 --- a/tests/test_inputtextmessagecontent.py +++ b/tests/test_inputtextmessagecontent.py @@ -51,8 +51,7 @@ class InputTextMessageContentTest(BaseTest, unittest.TestCase): self.assertEqual(itmc.parse_mode, self.parse_mode) self.assertEqual(itmc.message_text, self.message_text) - self.assertEqual(itmc.disable_web_page_preview, - self.disable_web_page_preview) + self.assertEqual(itmc.disable_web_page_preview, self.disable_web_page_preview) def test_itmc_de_json_factory(self): itmc = telegram.InputMessageContent.de_json(self.json_dict) @@ -74,8 +73,7 @@ class InputTextMessageContentTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(itmc.to_json())) def test_itmc_to_dict(self): - itmc = telegram.InputTextMessageContent.de_json( - self.json_dict).to_dict() + itmc = telegram.InputTextMessageContent.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(itmc)) self.assertDictEqual(self.json_dict, itmc) diff --git a/tests/test_inputvenuemessagecontent.py b/tests/test_inputvenuemessagecontent.py index d1613cc43..e2f4225cb 100644 --- a/tests/test_inputvenuemessagecontent.py +++ b/tests/test_inputvenuemessagecontent.py @@ -82,8 +82,7 @@ class InputVenueMessageContentTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(ivmc.to_json())) def test_ivmc_to_dict(self): - ivmc = telegram.InputVenueMessageContent.de_json( - self.json_dict).to_dict() + ivmc = telegram.InputVenueMessageContent.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(ivmc)) self.assertDictEqual(self.json_dict, ivmc) diff --git a/tests/test_jobqueue.py b/tests/test_jobqueue.py index 74da24c81..4ac90035d 100644 --- a/tests/test_jobqueue.py +++ b/tests/test_jobqueue.py @@ -40,8 +40,7 @@ root.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.WARN) -formatter = logging.Formatter( - '%(asctime)s - %(name)s - %(levelname)s - %(message)s') +formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) diff --git a/tests/test_keyboardbutton.py b/tests/test_keyboardbutton.py index 2af27ae4c..313dccaea 100644 --- a/tests/test_keyboardbutton.py +++ b/tests/test_keyboardbutton.py @@ -51,8 +51,7 @@ class KeyboardButtonTest(BaseTest, unittest.TestCase): keyboard_button = telegram.KeyboardButton.de_json(self.json_dict) self.assertEqual(keyboard_button.text, self.text) - self.assertEqual(keyboard_button.request_location, - self.request_location) + self.assertEqual(keyboard_button.request_location, self.request_location) self.assertEqual(keyboard_button.request_contact, self.request_contact) def test_keyboard_button_de_json_empty(self): @@ -71,8 +70,7 @@ class KeyboardButtonTest(BaseTest, unittest.TestCase): self.assertTrue(self.is_json(keyboard_button.to_json())) def test_keyboard_button_to_dict(self): - keyboard_button = telegram.KeyboardButton.de_json( - self.json_dict).to_dict() + keyboard_button = telegram.KeyboardButton.de_json(self.json_dict).to_dict() self.assertTrue(self.is_dict(keyboard_button)) self.assertDictEqual(self.json_dict, keyboard_button) diff --git a/tests/test_location.py b/tests/test_location.py index 4c224e4d1..bf48d7297 100644 --- a/tests/test_location.py +++ b/tests/test_location.py @@ -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 Location""" import unittest @@ -34,15 +33,10 @@ class LocationTest(BaseTest, unittest.TestCase): self.latitude = -23.691288 self.longitude = -46.788279 - self.json_dict = { - 'latitude': self.latitude, - 'longitude': self.longitude - } + self.json_dict = {'latitude': self.latitude, 'longitude': self.longitude} def test_send_location_implicit_args(self): - message = self._bot.sendLocation(self._chat_id, - self.latitude, - self.longitude) + message = self._bot.sendLocation(self._chat_id, self.latitude, self.longitude) location = message.location diff --git a/tests/test_photo.py b/tests/test_photo.py index 0b9e6e543..994d0bd3e 100644 --- a/tests/test_photo.py +++ b/tests/test_photo.py @@ -61,9 +61,7 @@ class PhotoTest(BaseTest, unittest.TestCase): @flaky(3, 1) @timeout(10) def test_sendphotoo_all_args(self): - message = self._bot.sendPhoto(self._chat_id, - self.photo_file, - caption=self.caption) + message = self._bot.sendPhoto(self._chat_id, self.photo_file, caption=self.caption) thumb, photo = message.photo @@ -128,8 +126,7 @@ class PhotoTest(BaseTest, unittest.TestCase): @flaky(3, 1) @timeout(10) def test_send_photo_resend(self): - message = self._bot.sendPhoto(chat_id=self._chat_id, - photo=self.photo_file_id) + message = self._bot.sendPhoto(chat_id=self._chat_id, photo=self.photo_file_id) thumb, photo = message.photo @@ -175,9 +172,9 @@ class PhotoTest(BaseTest, unittest.TestCase): del (json_dict['file_id']) json_dict['photo'] = open(os.devnull, 'rb') - self.assertRaises(telegram.TelegramError, - lambda: self._bot.sendPhoto(chat_id=self._chat_id, - **json_dict)) + self.assertRaises( + telegram.TelegramError, + lambda: self._bot.sendPhoto(chat_id=self._chat_id, **json_dict)) @flaky(3, 1) @timeout(10) @@ -187,9 +184,9 @@ class PhotoTest(BaseTest, unittest.TestCase): del (json_dict['file_id']) json_dict['photo'] = '' - self.assertRaises(telegram.TelegramError, - lambda: self._bot.sendPhoto(chat_id=self._chat_id, - **json_dict)) + self.assertRaises( + telegram.TelegramError, + lambda: self._bot.sendPhoto(chat_id=self._chat_id, **json_dict)) @flaky(3, 1) @timeout(10) @@ -200,9 +197,9 @@ class PhotoTest(BaseTest, unittest.TestCase): del (json_dict['width']) del (json_dict['height']) - self.assertRaises(TypeError, - lambda: self._bot.sendPhoto(chat_id=self._chat_id, - **json_dict)) + self.assertRaises( + TypeError, + lambda: self._bot.sendPhoto(chat_id=self._chat_id, **json_dict)) if __name__ == '__main__': diff --git a/tests/test_replykeyboardhide.py b/tests/test_replykeyboardhide.py index b6d35fd07..189a407f1 100644 --- a/tests/test_replykeyboardhide.py +++ b/tests/test_replykeyboardhide.py @@ -35,10 +35,7 @@ class ReplyKeyboardHideTest(BaseTest, unittest.TestCase): self.hide_keyboard = True self.selective = True - self.json_dict = { - 'hide_keyboard': self.hide_keyboard, - 'selective': self.selective, - } + self.json_dict = {'hide_keyboard': self.hide_keyboard, 'selective': self.selective,} def test_send_message_with_reply_keyboard_hide(self): message = self._bot.sendMessage( @@ -47,12 +44,10 @@ class ReplyKeyboardHideTest(BaseTest, unittest.TestCase): reply_markup=telegram.ReplyKeyboardHide.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_reply_keyboard_hide_de_json(self): - reply_keyboard_hide = telegram.ReplyKeyboardHide.de_json( - self.json_dict) + reply_keyboard_hide = telegram.ReplyKeyboardHide.de_json(self.json_dict) self.assertEqual(reply_keyboard_hide.hide_keyboard, self.hide_keyboard) self.assertEqual(reply_keyboard_hide.selective, self.selective) @@ -63,17 +58,14 @@ class ReplyKeyboardHideTest(BaseTest, unittest.TestCase): self.assertFalse(reply_keyboard_hide) def test_reply_keyboard_hide_to_json(self): - reply_keyboard_hide = telegram.ReplyKeyboardHide.de_json( - self.json_dict) + reply_keyboard_hide = telegram.ReplyKeyboardHide.de_json(self.json_dict) self.assertTrue(self.is_json(reply_keyboard_hide.to_json())) def test_reply_keyboard_hide_to_dict(self): - reply_keyboard_hide = telegram.ReplyKeyboardHide.de_json( - self.json_dict) + reply_keyboard_hide = telegram.ReplyKeyboardHide.de_json(self.json_dict) - self.assertEqual(reply_keyboard_hide['hide_keyboard'], - self.hide_keyboard) + self.assertEqual(reply_keyboard_hide['hide_keyboard'], self.hide_keyboard) self.assertEqual(reply_keyboard_hide['selective'], self.selective) diff --git a/tests/test_replykeyboardmarkup.py b/tests/test_replykeyboardmarkup.py index 1209a3dee..9ccf94345 100644 --- a/tests/test_replykeyboardmarkup.py +++ b/tests/test_replykeyboardmarkup.py @@ -32,15 +32,13 @@ class ReplyKeyboardMarkupTest(BaseTest, unittest.TestCase): """This object represents Tests for Telegram ReplyKeyboardMarkup.""" def setUp(self): - self.keyboard = [[telegram.KeyboardButton('button1'), - telegram.KeyboardButton('button2')]] + self.keyboard = [[telegram.KeyboardButton('button1'), telegram.KeyboardButton('button2')]] self.resize_keyboard = True self.one_time_keyboard = True self.selective = True self.json_dict = { - 'keyboard': [[self.keyboard[0][0].to_dict(), - self.keyboard[0][1].to_dict()]], + 'keyboard': [[self.keyboard[0][0].to_dict(), self.keyboard[0][1].to_dict()]], 'resize_keyboard': self.resize_keyboard, 'one_time_keyboard': self.one_time_keyboard, 'selective': self.selective, @@ -53,8 +51,7 @@ class ReplyKeyboardMarkupTest(BaseTest, unittest.TestCase): reply_markup=telegram.ReplyKeyboardMarkup.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_reply_markup_empty_de_json_empty(self): reply_markup_empty = telegram.ReplyKeyboardMarkup.de_json(None) @@ -62,35 +59,26 @@ class ReplyKeyboardMarkupTest(BaseTest, unittest.TestCase): self.assertFalse(reply_markup_empty) def test_reply_keyboard_markup_de_json(self): - reply_keyboard_markup = telegram.ReplyKeyboardMarkup.de_json( - self.json_dict) + reply_keyboard_markup = telegram.ReplyKeyboardMarkup.de_json(self.json_dict) self.assertTrue(isinstance(reply_keyboard_markup.keyboard, list)) - self.assertTrue(isinstance(reply_keyboard_markup.keyboard[0][0], - telegram.KeyboardButton)) - self.assertEqual(reply_keyboard_markup.resize_keyboard, - self.resize_keyboard) - self.assertEqual(reply_keyboard_markup.one_time_keyboard, - self.one_time_keyboard) + self.assertTrue(isinstance(reply_keyboard_markup.keyboard[0][0], telegram.KeyboardButton)) + self.assertEqual(reply_keyboard_markup.resize_keyboard, self.resize_keyboard) + self.assertEqual(reply_keyboard_markup.one_time_keyboard, self.one_time_keyboard) self.assertEqual(reply_keyboard_markup.selective, self.selective) def test_reply_keyboard_markup_to_json(self): - reply_keyboard_markup = telegram.ReplyKeyboardMarkup.de_json( - self.json_dict) + reply_keyboard_markup = telegram.ReplyKeyboardMarkup.de_json(self.json_dict) self.assertTrue(self.is_json(reply_keyboard_markup.to_json())) def test_reply_keyboard_markup_to_dict(self): - reply_keyboard_markup = telegram.ReplyKeyboardMarkup.de_json( - self.json_dict) + reply_keyboard_markup = telegram.ReplyKeyboardMarkup.de_json(self.json_dict) self.assertTrue(isinstance(reply_keyboard_markup.keyboard, list)) - self.assertTrue(isinstance(reply_keyboard_markup.keyboard[0][0], - telegram.KeyboardButton)) - self.assertEqual(reply_keyboard_markup['resize_keyboard'], - self.resize_keyboard) - self.assertEqual(reply_keyboard_markup['one_time_keyboard'], - self.one_time_keyboard) + self.assertTrue(isinstance(reply_keyboard_markup.keyboard[0][0], telegram.KeyboardButton)) + self.assertEqual(reply_keyboard_markup['resize_keyboard'], self.resize_keyboard) + self.assertEqual(reply_keyboard_markup['one_time_keyboard'], self.one_time_keyboard) self.assertEqual(reply_keyboard_markup['selective'], self.selective) diff --git a/tests/test_sticker.py b/tests/test_sticker.py index f1b55c507..f09c53f3d 100644 --- a/tests/test_sticker.py +++ b/tests/test_sticker.py @@ -62,8 +62,7 @@ class StickerTest(BaseTest, unittest.TestCase): @flaky(3, 1) @timeout(10) def test_send_sticker_resend(self): - message = self._bot.sendSticker(chat_id=self._chat_id, - sticker=self.sticker_file_id) + message = self._bot.sendSticker(chat_id=self._chat_id, sticker=self.sticker_file_id) sticker = message.sticker @@ -110,9 +109,9 @@ class StickerTest(BaseTest, unittest.TestCase): del (json_dict['file_id']) json_dict['sticker'] = open(os.devnull, 'rb') - self.assertRaises(telegram.TelegramError, - lambda: self._bot.sendSticker(chat_id=self._chat_id, - **json_dict)) + self.assertRaises( + telegram.TelegramError, + lambda: self._bot.sendSticker(chat_id=self._chat_id, **json_dict)) @flaky(3, 1) @timeout(10) @@ -122,9 +121,9 @@ class StickerTest(BaseTest, unittest.TestCase): del (json_dict['file_id']) json_dict['sticker'] = '' - self.assertRaises(telegram.TelegramError, - lambda: self._bot.sendSticker(chat_id=self._chat_id, - **json_dict)) + self.assertRaises( + telegram.TelegramError, + lambda: self._bot.sendSticker(chat_id=self._chat_id, **json_dict)) @flaky(3, 1) @timeout(10) @@ -133,9 +132,9 @@ class StickerTest(BaseTest, unittest.TestCase): del (json_dict['file_id']) - self.assertRaises(TypeError, - lambda: self._bot.sendSticker(chat_id=self._chat_id, - **json_dict)) + self.assertRaises( + TypeError, + lambda: self._bot.sendSticker(chat_id=self._chat_id, **json_dict)) if __name__ == '__main__': diff --git a/tests/test_updater.py b/tests/test_updater.py index 1f81d551a..ab12d9bda 100644 --- a/tests/test_updater.py +++ b/tests/test_updater.py @@ -60,8 +60,7 @@ root.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.WARN) -formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s ' - '- %(message)s') +formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s ' '- %(message)s') ch.setFormatter(formatter) root.addHandler(ch) @@ -95,8 +94,7 @@ class UpdaterTest(BaseTest, unittest.TestCase): self.message_count += 1 def telegramInlineHandlerTest(self, bot, update): - self.received_message = (update.inline_query, - update.chosen_inline_result) + self.received_message = (update.inline_query, update.chosen_inline_result) self.message_count += 1 def telegramCallbackHandlerTest(self, bot, update): @@ -161,8 +159,7 @@ class UpdaterTest(BaseTest, unittest.TestCase): def test_addTelegramMessageHandlerMultipleMessages(self): self._setup_updater('Multiple', 100) - self.updater.dispatcher.addHandler(MessageHandler( - [], self.telegramHandlerTest)) + self.updater.dispatcher.addHandler(MessageHandler([], self.telegramHandlerTest)) self.updater.start_polling(0.0) sleep(2) self.assertEqual(self.received_message, 'Multiple') @@ -394,9 +391,7 @@ class UpdaterTest(BaseTest, unittest.TestCase): def test_runAsyncWithAdditionalArgs(self): self._setup_updater('Test6', messages=2) d = self.updater.dispatcher - handler = MessageHandler([], - self.asyncAdditionalHandlerTest, - pass_update_queue=True) + handler = MessageHandler([], self.asyncAdditionalHandlerTest, pass_update_queue=True) d.addHandler(handler) self.updater.start_polling(0.01) sleep(1.2) @@ -442,8 +437,7 @@ class UpdaterTest(BaseTest, unittest.TestCase): self.assertEqual(200, response.code) response = self._send_webhook_msg( - ip, port, - None, 'webookhandler.py', + ip, port, None, 'webookhandler.py', get_method=lambda: 'HEAD') self.assertEqual(b'', response.read()) @@ -494,32 +488,28 @@ class UpdaterTest(BaseTest, unittest.TestCase): def test_bootstrap_retries_unauth(self): retries = 3 - self._setup_updater('', - messages=0, - bootstrap_retries=retries, - bootstrap_err=Unauthorized()) + self._setup_updater( + '', messages=0, bootstrap_retries=retries, + bootstrap_err=Unauthorized()) - self.assertRaises(Unauthorized, self.updater._bootstrap, - retries, False, 'path', None) + self.assertRaises(Unauthorized, self.updater._bootstrap, retries, False, 'path', None) self.assertEqual(self.updater.bot.bootstrap_attempts, 1) def test_bootstrap_retries_invalid_token(self): retries = 3 - self._setup_updater('', - messages=0, - bootstrap_retries=retries, - bootstrap_err=InvalidToken()) + self._setup_updater( + '', messages=0, bootstrap_retries=retries, + bootstrap_err=InvalidToken()) - self.assertRaises(InvalidToken, self.updater._bootstrap, - retries, False, 'path', None) + self.assertRaises(InvalidToken, self.updater._bootstrap, retries, False, 'path', None) self.assertEqual(self.updater.bot.bootstrap_attempts, 1) def test_bootstrap_retries_fail(self): retries = 1 self._setup_updater('', messages=0, bootstrap_retries=retries) - self.assertRaisesRegexp(TelegramError, 'test', self.updater._bootstrap, - retries - 1, False, 'path', None) + self.assertRaisesRegexp(TelegramError, 'test', self.updater._bootstrap, retries - 1, False, + 'path', None) self.assertEqual(self.updater.bot.bootstrap_attempts, 1) def test_webhook_invalid_posts(self): @@ -542,9 +532,7 @@ class UpdaterTest(BaseTest, unittest.TestCase): self.assertEqual(ctx.exception.code, 403) with self.assertRaises(HTTPError) as ctx: - self._send_webhook_msg( - ip, port, 'dummy-payload', - content_len=-2) + self._send_webhook_msg(ip, port, 'dummy-payload', content_len=-2) self.assertEqual(ctx.exception.code, 403) # TODO: prevent urllib or the underlying from adding content-length @@ -554,10 +542,7 @@ class UpdaterTest(BaseTest, unittest.TestCase): # self.assertEqual(ctx.exception.code, 411) with self.assertRaises(HTTPError) as ctx: - self._send_webhook_msg(ip, - port, - 'dummy-payload', - content_len='not-a-number') + self._send_webhook_msg(ip, port, 'dummy-payload', content_len='not-a-number') self.assertEqual(ctx.exception.code, 403) finally: @@ -572,7 +557,7 @@ class UpdaterTest(BaseTest, unittest.TestCase): content_len=-1, content_type='application/json', get_method=None): - headers = {'content-type': content_type, } + headers = {'content-type': content_type,} if not payload_str: content_len = None @@ -586,8 +571,7 @@ class UpdaterTest(BaseTest, unittest.TestCase): if content_len is not None: headers['content-length'] = str(content_len) - url = 'http://{ip}:{port}/{path}'.format( - ip=ip, port=port, path=url_path) + url = 'http://{ip}:{port}/{path}'.format(ip=ip, port=port, path=url_path) req = Request(url, data=payload, headers=headers) @@ -622,6 +606,7 @@ class UpdaterTest(BaseTest, unittest.TestCase): class MockBot(object): + def __init__(self, text, messages=1, diff --git a/tests/test_user.py b/tests/test_user.py index 33ae93092..4a0dd5033 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -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 User""" import unittest @@ -59,7 +58,7 @@ class UserTest(BaseTest, unittest.TestCase): def test_user_de_json_without_username(self): json_dict = self.json_dict - del(json_dict['username']) + del (json_dict['username']) user = telegram.User.de_json(self.json_dict) @@ -70,12 +69,11 @@ class UserTest(BaseTest, unittest.TestCase): self.assertEqual(user.name, '%s %s' % (self.first_name, self.last_name)) - def test_user_de_json_without_username_and_lastname(self): json_dict = self.json_dict - del(json_dict['username']) - del(json_dict['last_name']) + del (json_dict['username']) + del (json_dict['last_name']) user = telegram.User.de_json(self.json_dict) @@ -99,5 +97,6 @@ class UserTest(BaseTest, unittest.TestCase): self.assertEqual(user['username'], self.username) self.assertEqual(user['type'], self.type) + if __name__ == '__main__': unittest.main() diff --git a/tests/test_video.py b/tests/test_video.py index 5adf89a72..6ca66f4c1 100644 --- a/tests/test_video.py +++ b/tests/test_video.py @@ -40,11 +40,10 @@ class VideoTest(BaseTest, unittest.TestCase): self.width = 360 self.height = 640 self.duration = 5 - self.thumb = telegram.PhotoSize.de_json( - {'file_id': 'AAQBABOMsecvAAQqqoY1Pee_MqcyAAIC', - 'file_size': 645, - 'height': 90, - 'width': 51}) + self.thumb = telegram.PhotoSize.de_json({'file_id': 'AAQBABOMsecvAAQqqoY1Pee_MqcyAAIC', + 'file_size': 645, + 'height': 90, + 'width': 51}) self.mime_type = 'video/mp4' self.file_size = 326534 @@ -64,9 +63,7 @@ class VideoTest(BaseTest, unittest.TestCase): @flaky(3, 1) @timeout(10) def test_send_video_required_args_only(self): - message = self._bot.sendVideo(self._chat_id, - self.video_file, - timeout=10) + message = self._bot.sendVideo(self._chat_id, self.video_file, timeout=10) video = message.video diff --git a/tests/test_voice.py b/tests/test_voice.py index c1a020c37..4ce76975b 100644 --- a/tests/test_voice.py +++ b/tests/test_voice.py @@ -167,9 +167,9 @@ class VoiceTest(BaseTest, unittest.TestCase): del (json_dict['file_id']) json_dict['voice'] = open(os.devnull, 'rb') - self.assertRaises(telegram.TelegramError, - lambda: self._bot.sendVoice(chat_id=self._chat_id, - **json_dict)) + self.assertRaises( + telegram.TelegramError, + lambda: self._bot.sendVoice(chat_id=self._chat_id, **json_dict)) @flaky(3, 1) @timeout(10) @@ -179,9 +179,9 @@ class VoiceTest(BaseTest, unittest.TestCase): del (json_dict['file_id']) json_dict['voice'] = '' - self.assertRaises(telegram.TelegramError, - lambda: self._bot.sendVoice(chat_id=self._chat_id, - **json_dict)) + self.assertRaises( + telegram.TelegramError, + lambda: self._bot.sendVoice(chat_id=self._chat_id, **json_dict)) @flaky(3, 1) @timeout(10) @@ -191,9 +191,9 @@ class VoiceTest(BaseTest, unittest.TestCase): del (json_dict['file_id']) del (json_dict['duration']) - self.assertRaises(TypeError, - lambda: self._bot.sendVoice(chat_id=self._chat_id, - **json_dict)) + self.assertRaises( + TypeError, + lambda: self._bot.sendVoice(chat_id=self._chat_id, **json_dict)) if __name__ == '__main__':