diff --git a/contrib/debian/control b/contrib/debian/control index ebaf262ca..fd32cc739 100644 --- a/contrib/debian/control +++ b/contrib/debian/control @@ -15,7 +15,7 @@ Depends: ${python3:Depends}, ${misc:Depends} Description: We have made you a wrapper you can't refuse! The Python Telegram bot (Python 3) This library provides a pure Python interface for the Telegram Bot API. - It's compatible with Python versions 2.7, 3.3+ and PyPy. + It's compatible with Python versions 3.5+ and PyPy. . In addition to the pure API implementation, this library features a number of high-level diff --git a/contrib/debian/rules b/contrib/debian/rules index 82fcd9896..fbc5d1ad7 100755 --- a/contrib/debian/rules +++ b/contrib/debian/rules @@ -6,7 +6,7 @@ export PYBUILD_NAME=telegram %: - DEB_BUILD_OPTIONS=nocheck dh $@ --with python2,python3 --buildsystem=pybuild + DEB_BUILD_OPTIONS=nocheck dh $@ --with python3 --buildsystem=pybuild # If you need to rebuild the Sphinx documentation diff --git a/examples/deeplinking.py b/examples/deeplinking.py index b4d92d26e..609600974 100644 --- a/examples/deeplinking.py +++ b/examples/deeplinking.py @@ -61,7 +61,7 @@ def deep_linked_level_2(update, context): bot = context.bot url = helpers.create_deep_linked_url(bot.get_me().username, USING_ENTITIES) text = "You can also mask the deep-linked URLs as links: " \ - "[▶️ CLICK HERE]({0}).".format(url) + "[▶️ CLICK HERE]({}).".format(url) update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) @@ -69,7 +69,7 @@ def deep_linked_level_3(update, context): """Reached through the USING_ENTITIES payload""" payload = context.args update.message.reply_text("Congratulations! This is as deep as it gets 👏🏻\n\n" - "The payload was: {0}".format(payload)) + "The payload was: {}".format(payload)) def main(): diff --git a/examples/nestedconversationbot.py b/examples/nestedconversationbot.py index 14d59ad38..926f0b652 100644 --- a/examples/nestedconversationbot.py +++ b/examples/nestedconversationbot.py @@ -100,14 +100,14 @@ def show_data(update, context): text = '' if level == SELF: for person in user_data[level]: - text += '\nName: {0}, Age: {1}'.format(person.get(NAME, '-'), person.get(AGE, '-')) + text += '\nName: {}, Age: {}'.format(person.get(NAME, '-'), person.get(AGE, '-')) else: male, female = _name_switcher(level) for person in user_data[level]: gender = female if person[GENDER] == FEMALE else male - text += '\n{0}: Name: {1}, Age: {2}'.format(gender, person.get(NAME, '-'), - person.get(AGE, '-')) + text += '\n{}: Name: {}, Age: {}'.format(gender, person.get(NAME, '-'), + person.get(AGE, '-')) return text ud = context.user_data @@ -307,8 +307,8 @@ def main(): states={ SELECTING_LEVEL: [CallbackQueryHandler(select_gender, - pattern='^{0}$|^{1}$'.format(str(PARENTS), - str(CHILDREN)))], + pattern='^{}$|^{}$'.format(str(PARENTS), + str(CHILDREN)))], SELECTING_GENDER: [description_conv] }, diff --git a/requirements.txt b/requirements.txt index 6f926578e..ac9fb7cc1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,3 @@ -future>=0.16.0 certifi tornado>=5.1 cryptography diff --git a/telegram/__main__.py b/telegram/__main__.py index 44e92baec..d314679ae 100644 --- a/telegram/__main__.py +++ b/telegram/__main__.py @@ -20,7 +20,6 @@ import sys import subprocess import certifi -import future from . import __version__ as telegram_ver @@ -37,11 +36,10 @@ def _git_revision(): def print_ver_info(): git_revision = _git_revision() - print('python-telegram-bot {0}'.format(telegram_ver) + (' ({0})'.format(git_revision) - if git_revision else '')) - print('certifi {0}'.format(certifi.__version__)) - print('future {0}'.format(future.__version__)) - print('Python {0}'.format(sys.version.replace('\n', ' '))) + print('python-telegram-bot {}'.format(telegram_ver) + (' ({})'.format(git_revision) + if git_revision else '')) + print('certifi {}'.format(certifi.__version__)) + print('Python {}'.format(sys.version.replace('\n', ' '))) def main(): diff --git a/telegram/base.py b/telegram/base.py index 65c43678e..444d30efc 100644 --- a/telegram/base.py +++ b/telegram/base.py @@ -24,7 +24,7 @@ except ImportError: import json -class TelegramObject(object): +class TelegramObject: """Base class for most telegram objects.""" _id_attrs = () @@ -74,9 +74,9 @@ class TelegramObject(object): def __eq__(self, other): if isinstance(other, self.__class__): return self._id_attrs == other._id_attrs - return super(TelegramObject, self).__eq__(other) # pylint: disable=no-member + return super().__eq__(other) # pylint: disable=no-member def __hash__(self): if self._id_attrs: return hash((self.__class__, self._id_attrs)) # pylint: disable=no-member - return super(TelegramObject, self).__hash__() + return super().__hash__() diff --git a/telegram/bot.py b/telegram/bot.py index af9195068..f4570f8e8 100644 --- a/telegram/bot.py +++ b/telegram/bot.py @@ -34,7 +34,6 @@ from datetime import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization -from future.utils import string_types from telegram import (User, Message, Update, Chat, ChatMember, UserProfilePhotos, File, ReplyMarkup, TelegramObject, WebhookInfo, GameHighScore, StickerSet, @@ -94,7 +93,7 @@ class Bot(TelegramObject): defaults = kwargs.get('defaults') # Make an instance of the class - instance = super(Bot, cls).__new__(cls) + instance = super().__new__(cls) if not defaults: return instance @@ -266,7 +265,7 @@ class Bot(TelegramObject): def name(self): """:obj:`str`: Bot's @username.""" - return '@{0}'.format(self.username) + return '@{}'.format(self.username) @log def get_me(self, timeout=None, **kwargs): @@ -285,7 +284,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/getMe'.format(self.base_url) + url = '{}/getMe'.format(self.base_url) result = self._request.get(url, timeout=timeout) @@ -335,7 +334,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendMessage'.format(self.base_url) + url = '{}/sendMessage'.format(self.base_url) data = {'chat_id': chat_id, 'text': text} @@ -380,7 +379,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/deleteMessage'.format(self.base_url) + url = '{}/deleteMessage'.format(self.base_url) data = {'chat_id': chat_id, 'message_id': message_id} @@ -418,7 +417,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/forwardMessage'.format(self.base_url) + url = '{}/forwardMessage'.format(self.base_url) data = {} @@ -479,7 +478,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendPhoto'.format(self.base_url) + url = '{}/sendPhoto'.format(self.base_url) if isinstance(photo, PhotoSize): photo = photo.file_id @@ -563,7 +562,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendAudio'.format(self.base_url) + url = '{}/sendAudio'.format(self.base_url) if isinstance(audio, Audio): audio = audio.file_id @@ -651,7 +650,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendDocument'.format(self.base_url) + url = '{}/sendDocument'.format(self.base_url) if isinstance(document, Document): document = document.file_id @@ -714,7 +713,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendSticker'.format(self.base_url) + url = '{}/sendSticker'.format(self.base_url) if isinstance(sticker, Sticker): sticker = sticker.file_id @@ -794,7 +793,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendVideo'.format(self.base_url) + url = '{}/sendVideo'.format(self.base_url) if isinstance(video, Video): video = video.file_id @@ -877,7 +876,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendVideoNote'.format(self.base_url) + url = '{}/sendVideoNote'.format(self.base_url) if isinstance(video_note, VideoNote): video_note = video_note.file_id @@ -957,7 +956,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendAnimation'.format(self.base_url) + url = '{}/sendAnimation'.format(self.base_url) if isinstance(animation, Animation): animation = animation.file_id @@ -1038,7 +1037,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendVoice'.format(self.base_url) + url = '{}/sendVoice'.format(self.base_url) if isinstance(voice, Voice): voice = voice.file_id @@ -1087,7 +1086,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendMediaGroup'.format(self.base_url) + url = '{}/sendMediaGroup'.format(self.base_url) data = {'chat_id': chat_id, 'media': media} @@ -1155,7 +1154,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendLocation'.format(self.base_url) + url = '{}/sendLocation'.format(self.base_url) if not ((latitude is not None and longitude is not None) or location): raise ValueError("Either location or latitude and longitude must be passed as" @@ -1218,7 +1217,7 @@ class Bot(TelegramObject): edited Message is returned, otherwise ``True`` is returned. """ - url = '{0}/editMessageLiveLocation'.format(self.base_url) + url = '{}/editMessageLiveLocation'.format(self.base_url) if not (all([latitude, longitude]) or location): raise ValueError("Either location or latitude and longitude must be passed as" @@ -1272,7 +1271,7 @@ class Bot(TelegramObject): edited Message is returned, otherwise ``True`` is returned. """ - url = '{0}/stopMessageLiveLocation'.format(self.base_url) + url = '{}/stopMessageLiveLocation'.format(self.base_url) data = {} @@ -1338,7 +1337,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendVenue'.format(self.base_url) + url = '{}/sendVenue'.format(self.base_url) if not (venue or all([latitude, longitude, address, title])): raise ValueError("Either venue or latitude, longitude, address and title must be" @@ -1416,7 +1415,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendContact'.format(self.base_url) + url = '{}/sendContact'.format(self.base_url) if (not contact) and (not all([phone_number, first_name])): raise ValueError("Either contact or phone_number and first_name must be passed as" @@ -1474,7 +1473,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendGame'.format(self.base_url) + url = '{}/sendGame'.format(self.base_url) data = {'chat_id': chat_id, 'game_short_name': game_short_name} @@ -1508,7 +1507,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendChatAction'.format(self.base_url) + url = '{}/sendChatAction'.format(self.base_url) data = {'chat_id': chat_id, 'action': action} data.update(kwargs) @@ -1572,7 +1571,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/answerInlineQuery'.format(self.base_url) + url = '{}/answerInlineQuery'.format(self.base_url) for res in results: if res._has_parse_mode and res.parse_mode == DEFAULT_NONE: @@ -1638,7 +1637,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/getUserProfilePhotos'.format(self.base_url) + url = '{}/getUserProfilePhotos'.format(self.base_url) data = {'user_id': user_id} @@ -1686,7 +1685,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/getFile'.format(self.base_url) + url = '{}/getFile'.format(self.base_url) try: file_id = file_id.file_id @@ -1699,7 +1698,7 @@ class Bot(TelegramObject): result = self._request.post(url, data, timeout=timeout) if result.get('file_path'): - result['file_path'] = '%s/%s' % (self.base_file_url, result['file_path']) + result['file_path'] = '{}/{}'.format(self.base_file_url, result['file_path']) return File.de_json(result, self) @@ -1730,7 +1729,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/kickChatMember'.format(self.base_url) + url = '{}/kickChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id} data.update(kwargs) @@ -1767,7 +1766,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/unbanChatMember'.format(self.base_url) + url = '{}/unbanChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id} data.update(kwargs) @@ -1819,7 +1818,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url_ = '{0}/answerCallbackQuery'.format(self.base_url) + url_ = '{}/answerCallbackQuery'.format(self.base_url) data = {'callback_query_id': callback_query_id} @@ -1881,7 +1880,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/editMessageText'.format(self.base_url) + url = '{}/editMessageText'.format(self.base_url) data = {'text': text} @@ -1945,7 +1944,7 @@ class Bot(TelegramObject): 'edit_message_caption: Both chat_id and message_id are required when ' 'inline_message_id is not specified') - url = '{0}/editMessageCaption'.format(self.base_url) + url = '{}/editMessageCaption'.format(self.base_url) data = {} @@ -2007,7 +2006,7 @@ class Bot(TelegramObject): 'edit_message_media: Both chat_id and message_id are required when ' 'inline_message_id is not specified') - url = '{0}/editMessageMedia'.format(self.base_url) + url = '{}/editMessageMedia'.format(self.base_url) data = {'media': media} @@ -2060,7 +2059,7 @@ class Bot(TelegramObject): 'edit_message_reply_markup: Both chat_id and message_id are required when ' 'inline_message_id is not specified') - url = '{0}/editMessageReplyMarkup'.format(self.base_url) + url = '{}/editMessageReplyMarkup'.format(self.base_url) data = {} @@ -2119,7 +2118,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/getUpdates'.format(self.base_url) + url = '{}/getUpdates'.format(self.base_url) data = {'timeout': timeout} @@ -2213,7 +2212,7 @@ class Bot(TelegramObject): .. _`guide to Webhooks`: https://core.telegram.org/bots/webhooks """ - url_ = '{0}/setWebhook'.format(self.base_url) + url_ = '{}/setWebhook'.format(self.base_url) # Backwards-compatibility: 'url' used to be named 'webhook_url' if 'webhook_url' in kwargs: # pragma: no cover @@ -2263,7 +2262,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/deleteWebhook'.format(self.base_url) + url = '{}/deleteWebhook'.format(self.base_url) data = kwargs @@ -2290,7 +2289,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/leaveChat'.format(self.base_url) + url = '{}/leaveChat'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) @@ -2320,7 +2319,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/getChat'.format(self.base_url) + url = '{}/getChat'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) @@ -2355,7 +2354,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/getChatAdministrators'.format(self.base_url) + url = '{}/getChatAdministrators'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) @@ -2383,7 +2382,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/getChatMembersCount'.format(self.base_url) + url = '{}/getChatMembersCount'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) @@ -2412,7 +2411,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/getChatMember'.format(self.base_url) + url = '{}/getChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id} data.update(kwargs) @@ -2443,7 +2442,7 @@ class Bot(TelegramObject): :obj:`bool`: On success, ``True`` is returned. """ - url = '{0}/setChatStickerSet'.format(self.base_url) + url = '{}/setChatStickerSet'.format(self.base_url) data = {'chat_id': chat_id, 'sticker_set_name': sticker_set_name} @@ -2470,7 +2469,7 @@ class Bot(TelegramObject): :obj:`bool`: On success, ``True`` is returned. """ - url = '{0}/deleteChatStickerSet'.format(self.base_url) + url = '{}/deleteChatStickerSet'.format(self.base_url) data = {'chat_id': chat_id} @@ -2493,7 +2492,7 @@ class Bot(TelegramObject): :class:`telegram.WebhookInfo` """ - url = '{0}/getWebhookInfo'.format(self.base_url) + url = '{}/getWebhookInfo'.format(self.base_url) data = kwargs @@ -2542,7 +2541,7 @@ class Bot(TelegramObject): current score in the chat and force is False. """ - url = '{0}/setGameScore'.format(self.base_url) + url = '{}/setGameScore'.format(self.base_url) data = {'user_id': user_id, 'score': score} @@ -2591,7 +2590,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/getGameHighScores'.format(self.base_url) + url = '{}/getGameHighScores'.format(self.base_url) data = {'user_id': user_id} @@ -2692,7 +2691,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendInvoice'.format(self.base_url) + url = '{}/sendInvoice'.format(self.base_url) data = { 'chat_id': chat_id, @@ -2705,7 +2704,7 @@ class Bot(TelegramObject): 'prices': [p.to_dict() for p in prices] } if provider_data is not None: - if isinstance(provider_data, string_types): + if isinstance(provider_data, str): data['provider_data'] = provider_data else: data['provider_data'] = json.dumps(provider_data) @@ -2784,7 +2783,7 @@ class Bot(TelegramObject): 'answerShippingQuery: If ok is False, error_message ' 'should not be empty and there should not be shipping_options') - url_ = '{0}/answerShippingQuery'.format(self.base_url) + url_ = '{}/answerShippingQuery'.format(self.base_url) data = {'shipping_query_id': shipping_query_id, 'ok': ok} @@ -2839,7 +2838,7 @@ class Bot(TelegramObject): 'not be error_message; if ok is False, error_message ' 'should not be empty') - url_ = '{0}/answerPreCheckoutQuery'.format(self.base_url) + url_ = '{}/answerPreCheckoutQuery'.format(self.base_url) data = {'pre_checkout_query_id': pre_checkout_query_id, 'ok': ok} @@ -2884,7 +2883,7 @@ class Bot(TelegramObject): Raises: :class:`telegram.TelegramError` """ - url = '{0}/restrictChatMember'.format(self.base_url) + url = '{}/restrictChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id, 'permissions': permissions.to_dict()} @@ -2943,7 +2942,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/promoteChatMember'.format(self.base_url) + url = '{}/promoteChatMember'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id} @@ -2992,7 +2991,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/setChatPermissions'.format(self.base_url) + url = '{}/setChatPermissions'.format(self.base_url) data = {'chat_id': chat_id, 'permissions': permissions.to_dict()} data.update(kwargs) @@ -3030,7 +3029,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/setChatAdministratorCustomTitle'.format(self.base_url) + url = '{}/setChatAdministratorCustomTitle'.format(self.base_url) data = {'chat_id': chat_id, 'user_id': user_id, 'custom_title': custom_title} data.update(kwargs) @@ -3061,7 +3060,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/exportChatInviteLink'.format(self.base_url) + url = '{}/exportChatInviteLink'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) @@ -3093,7 +3092,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/setChatPhoto'.format(self.base_url) + url = '{}/setChatPhoto'.format(self.base_url) if InputFile.is_file(photo): photo = InputFile(photo) @@ -3127,7 +3126,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/deleteChatPhoto'.format(self.base_url) + url = '{}/deleteChatPhoto'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) @@ -3159,7 +3158,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/setChatTitle'.format(self.base_url) + url = '{}/setChatTitle'.format(self.base_url) data = {'chat_id': chat_id, 'title': title} data.update(kwargs) @@ -3191,7 +3190,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/setChatDescription'.format(self.base_url) + url = '{}/setChatDescription'.format(self.base_url) data = {'chat_id': chat_id, 'description': description} data.update(kwargs) @@ -3228,7 +3227,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/pinChatMessage'.format(self.base_url) + url = '{}/pinChatMessage'.format(self.base_url) data = {'chat_id': chat_id, 'message_id': message_id} @@ -3263,7 +3262,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/unpinChatMessage'.format(self.base_url) + url = '{}/unpinChatMessage'.format(self.base_url) data = {'chat_id': chat_id} data.update(kwargs) @@ -3290,7 +3289,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/getStickerSet'.format(self.base_url) + url = '{}/getStickerSet'.format(self.base_url) data = {'name': name} data.update(kwargs) @@ -3327,7 +3326,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/uploadStickerFile'.format(self.base_url) + url = '{}/uploadStickerFile'.format(self.base_url) if InputFile.is_file(png_sticker): png_sticker = InputFile(png_sticker) @@ -3392,7 +3391,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/createNewStickerSet'.format(self.base_url) + url = '{}/createNewStickerSet'.format(self.base_url) if InputFile.is_file(png_sticker): png_sticker = InputFile(png_sticker) @@ -3464,7 +3463,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/addStickerToSet'.format(self.base_url) + url = '{}/addStickerToSet'.format(self.base_url) if InputFile.is_file(png_sticker): png_sticker = InputFile(png_sticker) @@ -3507,7 +3506,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/setStickerPositionInSet'.format(self.base_url) + url = '{}/setStickerPositionInSet'.format(self.base_url) data = {'sticker': sticker, 'position': position} data.update(kwargs) @@ -3534,7 +3533,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/deleteStickerFromSet'.format(self.base_url) + url = '{}/deleteStickerFromSet'.format(self.base_url) data = {'sticker': sticker} data.update(kwargs) @@ -3613,7 +3612,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url_ = '{0}/setPassportDataErrors'.format(self.base_url) + url_ = '{}/setPassportDataErrors'.format(self.base_url) data = {'user_id': user_id, 'errors': [error.to_dict() for error in errors]} data.update(kwargs) @@ -3690,7 +3689,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendPoll'.format(self.base_url) + url = '{}/sendPoll'.format(self.base_url) data = { 'chat_id': chat_id, @@ -3758,7 +3757,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/stopPoll'.format(self.base_url) + url = '{}/stopPoll'.format(self.base_url) data = { 'chat_id': chat_id, @@ -3813,7 +3812,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/sendDice'.format(self.base_url) + url = '{}/sendDice'.format(self.base_url) data = { 'chat_id': chat_id, @@ -3844,7 +3843,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/getMyCommands'.format(self.base_url) + url = '{}/getMyCommands'.format(self.base_url) result = self._request.get(url, timeout=timeout) @@ -3873,7 +3872,7 @@ class Bot(TelegramObject): :class:`telegram.TelegramError` """ - url = '{0}/setMyCommands'.format(self.base_url) + url = '{}/setMyCommands'.format(self.base_url) cmds = [c if isinstance(c, BotCommand) else BotCommand(c[0], c[1]) for c in commands] diff --git a/telegram/callbackquery.py b/telegram/callbackquery.py index 2e3483155..5a3cf6360 100644 --- a/telegram/callbackquery.py +++ b/telegram/callbackquery.py @@ -99,7 +99,7 @@ class CallbackQuery(TelegramObject): if not data: return None - data = super(CallbackQuery, cls).de_json(data, bot) + data = super().de_json(data, bot) data['from_user'] = User.de_json(data.get('from'), bot) message = data.get('message') diff --git a/telegram/chataction.py b/telegram/chataction.py index 39be0ce7a..66fd3ff31 100644 --- a/telegram/chataction.py +++ b/telegram/chataction.py @@ -20,7 +20,7 @@ """This module contains an object that represents a Telegram ChatAction.""" -class ChatAction(object): +class ChatAction: """Helper class to provide constants for different chatactions.""" FIND_LOCATION = 'find_location' diff --git a/telegram/chatmember.py b/telegram/chatmember.py index 5dea1169e..18f8f7fbd 100644 --- a/telegram/chatmember.py +++ b/telegram/chatmember.py @@ -150,7 +150,7 @@ class ChatMember(TelegramObject): if not data: return None - data = super(ChatMember, cls).de_json(data, bot) + data = super().de_json(data, bot) data['user'] = User.de_json(data.get('user'), bot) data['until_date'] = from_timestamp(data.get('until_date', None)) @@ -158,7 +158,7 @@ class ChatMember(TelegramObject): return cls(**data) def to_dict(self): - data = super(ChatMember, self).to_dict() + data = super().to_dict() data['until_date'] = to_timestamp(self.until_date) diff --git a/telegram/choseninlineresult.py b/telegram/choseninlineresult.py index 27a8ee0d2..a2074c238 100644 --- a/telegram/choseninlineresult.py +++ b/telegram/choseninlineresult.py @@ -72,7 +72,7 @@ class ChosenInlineResult(TelegramObject): if not data: return None - data = super(ChosenInlineResult, cls).de_json(data, bot) + data = super().de_json(data, bot) # Required data['from_user'] = User.de_json(data.pop('from'), bot) # Optionals diff --git a/telegram/error.py b/telegram/error.py index a10aa9000..789042a36 100644 --- a/telegram/error.py +++ b/telegram/error.py @@ -38,7 +38,7 @@ def _lstrip_str(in_s, lstr): class TelegramError(Exception): def __init__(self, message): - super(TelegramError, self).__init__() + super().__init__() msg = _lstrip_str(message, 'Error: ') msg = _lstrip_str(msg, '[Error]: ') @@ -58,7 +58,7 @@ class Unauthorized(TelegramError): class InvalidToken(TelegramError): def __init__(self): - super(InvalidToken, self).__init__('Invalid token') + super().__init__('Invalid token') class NetworkError(TelegramError): @@ -71,7 +71,7 @@ class BadRequest(NetworkError): class TimedOut(NetworkError): def __init__(self): - super(TimedOut, self).__init__('Timed out') + super().__init__('Timed out') class ChatMigrated(TelegramError): @@ -82,8 +82,7 @@ class ChatMigrated(TelegramError): """ def __init__(self, new_chat_id): - super(ChatMigrated, - self).__init__('Group migrated to supergroup. New chat id: {}'.format(new_chat_id)) + super().__init__('Group migrated to supergroup. New chat id: {}'.format(new_chat_id)) self.new_chat_id = new_chat_id @@ -95,8 +94,7 @@ class RetryAfter(TelegramError): """ def __init__(self, retry_after): - super(RetryAfter, - self).__init__('Flood control exceeded. Retry in {} seconds'.format(retry_after)) + super().__init__('Flood control exceeded. Retry in {} seconds'.format(retry_after)) self.retry_after = float(retry_after) @@ -110,4 +108,4 @@ class Conflict(TelegramError): """ def __init__(self, msg): - super(Conflict, self).__init__(msg) + super().__init__(msg) diff --git a/telegram/ext/callbackcontext.py b/telegram/ext/callbackcontext.py index 7fb72c9a1..5dc8aac30 100644 --- a/telegram/ext/callbackcontext.py +++ b/telegram/ext/callbackcontext.py @@ -21,7 +21,7 @@ from telegram import Update -class CallbackContext(object): +class CallbackContext: """ This is a context object passed to the callback called by :class:`telegram.ext.Handler` or by the :class:`telegram.ext.Dispatcher` in an error handler added by diff --git a/telegram/ext/callbackqueryhandler.py b/telegram/ext/callbackqueryhandler.py index 69f926bc0..90417f0ce 100644 --- a/telegram/ext/callbackqueryhandler.py +++ b/telegram/ext/callbackqueryhandler.py @@ -20,8 +20,6 @@ import re -from future.utils import string_types - from telegram import Update from .handler import Handler @@ -105,14 +103,14 @@ class CallbackQueryHandler(Handler): pass_groupdict=False, pass_user_data=False, pass_chat_data=False): - super(CallbackQueryHandler, self).__init__( + super().__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue, pass_user_data=pass_user_data, pass_chat_data=pass_chat_data) - if isinstance(pattern, string_types): + if isinstance(pattern, str): pattern = re.compile(pattern) self.pattern = pattern @@ -139,9 +137,7 @@ class CallbackQueryHandler(Handler): return True def collect_optional_args(self, dispatcher, update=None, check_result=None): - optional_args = super(CallbackQueryHandler, self).collect_optional_args(dispatcher, - update, - check_result) + optional_args = super().collect_optional_args(dispatcher, update, check_result) if self.pattern: if self.pass_groups: optional_args['groups'] = check_result.groups() diff --git a/telegram/ext/commandhandler.py b/telegram/ext/commandhandler.py index 1387c18d6..bb483ce02 100644 --- a/telegram/ext/commandhandler.py +++ b/telegram/ext/commandhandler.py @@ -20,8 +20,6 @@ import re import warnings -from future.utils import string_types - from telegram.ext import Filters from telegram.utils.deprecate import TelegramDeprecationWarning @@ -125,14 +123,14 @@ class CommandHandler(Handler): pass_job_queue=False, pass_user_data=False, pass_chat_data=False): - super(CommandHandler, self).__init__( + super().__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue, pass_user_data=pass_user_data, pass_chat_data=pass_chat_data) - if isinstance(command, string_types): + if isinstance(command, str): self.command = [command.lower()] else: self.command = [x.lower() for x in command] @@ -184,7 +182,7 @@ class CommandHandler(Handler): return False def collect_optional_args(self, dispatcher, update=None, check_result=None): - optional_args = super(CommandHandler, self).collect_optional_args(dispatcher, update) + optional_args = super().collect_optional_args(dispatcher, update) if self.pass_args: optional_args['args'] = check_result[0] return optional_args @@ -306,7 +304,7 @@ class PrefixHandler(CommandHandler): self._command = list() self._commands = list() - super(PrefixHandler, self).__init__( + super().__init__( 'nocommand', callback, filters=filters, allow_edited=None, pass_args=pass_args, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue, @@ -323,7 +321,7 @@ class PrefixHandler(CommandHandler): @prefix.setter def prefix(self, prefix): - if isinstance(prefix, string_types): + if isinstance(prefix, str): self._prefix = [prefix.lower()] else: self._prefix = prefix @@ -335,7 +333,7 @@ class PrefixHandler(CommandHandler): @command.setter def command(self, command): - if isinstance(command, string_types): + if isinstance(command, str): self._command = [command.lower()] else: self._command = command diff --git a/telegram/ext/conversationhandler.py b/telegram/ext/conversationhandler.py index d61146462..0119e52f0 100644 --- a/telegram/ext/conversationhandler.py +++ b/telegram/ext/conversationhandler.py @@ -28,7 +28,7 @@ from telegram.ext import (Handler, CallbackQueryHandler, InlineQueryHandler, from telegram.utils.promise import Promise -class _ConversationTimeoutContext(object): +class _ConversationTimeoutContext: def __init__(self, conversation_key, update, dispatcher, callback_context): self.conversation_key = conversation_key self.update = update @@ -404,7 +404,7 @@ class ConversationHandler(Handler): return key, handler, check return None - self.logger.debug('selecting conversation %s with state %s' % (str(key), str(state))) + self.logger.debug('selecting conversation {} with state {}'.format(str(key), str(state))) handler = None diff --git a/telegram/ext/dictpersistence.py b/telegram/ext/dictpersistence.py index 42a2eca18..3d18aa148 100644 --- a/telegram/ext/dictpersistence.py +++ b/telegram/ext/dictpersistence.py @@ -66,9 +66,9 @@ class DictPersistence(BasePersistence): chat_data_json='', bot_data_json='', conversations_json=''): - super(DictPersistence, self).__init__(store_user_data=store_user_data, - store_chat_data=store_chat_data, - store_bot_data=store_bot_data) + super().__init__(store_user_data=store_user_data, + store_chat_data=store_chat_data, + store_bot_data=store_bot_data) self._user_data = None self._chat_data = None self._bot_data = None diff --git a/telegram/ext/dispatcher.py b/telegram/ext/dispatcher.py index 4b0678c9b..5dd61ed28 100644 --- a/telegram/ext/dispatcher.py +++ b/telegram/ext/dispatcher.py @@ -29,8 +29,6 @@ from collections import defaultdict from queue import Queue, Empty -from future.builtins import range - from telegram import TelegramError, Update from telegram.ext.handler import Handler from telegram.ext.callbackcontext import CallbackContext @@ -66,7 +64,7 @@ class DispatcherHandlerStop(Exception): pass -class Dispatcher(object): +class Dispatcher: """This class dispatches all kinds of updates to its registered handlers. Attributes: @@ -304,10 +302,10 @@ class Dispatcher(object): self.__async_queue.put(None) for i, thr in enumerate(threads): - self.logger.debug('Waiting for async thread {0}/{1} to end'.format(i + 1, total)) + self.logger.debug('Waiting for async thread {}/{} to end'.format(i + 1, total)) thr.join() self.__async_threads.remove(thr) - self.logger.debug('async thread {0}/{1} has ended'.format(i + 1, total)) + self.logger.debug('async thread {}/{} has ended'.format(i + 1, total)) @property def has_running_threads(self): @@ -391,7 +389,7 @@ class Dispatcher(object): from .conversationhandler import ConversationHandler 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 {}'.format(Handler.__name__)) if not isinstance(group, int): raise TypeError('group is not int') if isinstance(handler, ConversationHandler) and handler.persistent: diff --git a/telegram/ext/filters.py b/telegram/ext/filters.py index f10b66f87..ef67d3f9f 100644 --- a/telegram/ext/filters.py +++ b/telegram/ext/filters.py @@ -21,7 +21,6 @@ import re from abc import ABC, abstractmethod -from future.utils import string_types from threading import Lock from telegram import Chat, Update, MessageEntity @@ -248,7 +247,7 @@ class _DiceEmoji(BaseFilter): return True -class Filters(object): +class Filters: """Predefined filters for use as the `filter` argument of :class:`telegram.ext.MessageHandler`. Examples: @@ -426,7 +425,7 @@ class Filters(object): data_filter = True def __init__(self, pattern): - if isinstance(pattern, string_types): + if isinstance(pattern, str): pattern = re.compile(pattern) self.pattern = pattern self.name = 'Filters.regex({})'.format(self.pattern) @@ -1306,7 +1305,7 @@ officedocument.wordprocessingml.document")``- """ def __init__(self, lang): - if isinstance(lang, string_types): + if isinstance(lang, str): self.lang = [lang] else: self.lang = lang diff --git a/telegram/ext/inlinequeryhandler.py b/telegram/ext/inlinequeryhandler.py index adef02cc7..518ac9a7a 100644 --- a/telegram/ext/inlinequeryhandler.py +++ b/telegram/ext/inlinequeryhandler.py @@ -19,9 +19,8 @@ """ This module contains the InlineQueryHandler class """ import re -from future.utils import string_types - from telegram import Update + from .handler import Handler @@ -104,14 +103,14 @@ class InlineQueryHandler(Handler): pass_groupdict=False, pass_user_data=False, pass_chat_data=False): - super(InlineQueryHandler, self).__init__( + super().__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue, pass_user_data=pass_user_data, pass_chat_data=pass_chat_data) - if isinstance(pattern, string_types): + if isinstance(pattern, str): pattern = re.compile(pattern) self.pattern = pattern @@ -140,8 +139,7 @@ class InlineQueryHandler(Handler): return True def collect_optional_args(self, dispatcher, update=None, check_result=None): - optional_args = super(InlineQueryHandler, self).collect_optional_args(dispatcher, - update, check_result) + optional_args = super().collect_optional_args(dispatcher, update, check_result) if self.pattern: if self.pass_groups: optional_args['groups'] = check_result.groups() diff --git a/telegram/ext/jobqueue.py b/telegram/ext/jobqueue.py index 3a65a38db..75ffb877d 100644 --- a/telegram/ext/jobqueue.py +++ b/telegram/ext/jobqueue.py @@ -33,12 +33,12 @@ from telegram.utils.deprecate import TelegramDeprecationWarning from telegram.utils.helpers import to_float_timestamp -class Days(object): +class Days: MON, TUE, WED, THU, FRI, SAT, SUN = range(7) EVERY_DAY = tuple(range(7)) -class JobQueue(object): +class JobQueue: """This class allows you to periodically perform tasks with the bot. Attributes: @@ -54,7 +54,7 @@ class JobQueue(object): warnings.warn("Passing bot to jobqueue is deprecated. Please use set_dispatcher " "instead!", TelegramDeprecationWarning, stacklevel=2) - class MockDispatcher(object): + class MockDispatcher: def __init__(self): self.bot = bot self.use_context = False @@ -492,7 +492,7 @@ class JobQueue(object): return tuple(job[1] for job in self._queue.queue if job and job[1].name == name) -class Job(object): +class Job: """This class encapsulates a Job. Attributes: diff --git a/telegram/ext/messagehandler.py b/telegram/ext/messagehandler.py index b9bc0487a..b01259f7e 100644 --- a/telegram/ext/messagehandler.py +++ b/telegram/ext/messagehandler.py @@ -117,7 +117,7 @@ class MessageHandler(Handler): channel_post_updates=None, edited_updates=None): - super(MessageHandler, self).__init__( + super().__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue, diff --git a/telegram/ext/messagequeue.py b/telegram/ext/messagequeue.py index 29b3200ee..3c4bef749 100644 --- a/telegram/ext/messagequeue.py +++ b/telegram/ext/messagequeue.py @@ -23,24 +23,9 @@ from telegram.utils import promise import functools -import sys import time import threading -if sys.version_info.major > 2: - import queue as q -else: - import Queue as q - -# We need to count < 1s intervals, so the most accurate timer is needed -# Starting from Python 3.3 we have time.perf_counter which is the clock -# with the highest resolution available to the system, so let's use it there. -# In Python 2.7, there's no perf_counter yet, so fallback on what we have: -# on Windows, the best available is time.clock while time.time is on -# another platforms (M. Lutz, "Learning Python," 4ed, p.630-634) -if sys.version_info.major == 3 and sys.version_info.minor >= 3: - curtime = time.perf_counter # pylint: disable=E1101 -else: - curtime = time.clock if sys.platform[:3] == 'win' else time.time +import queue as q class DelayQueueError(RuntimeError): @@ -95,11 +80,11 @@ class DelayQueue(threading.Thread): self.__exit_req = False # flag to gently exit thread self.__class__._instcnt += 1 if name is None: - name = '%s-%s' % (self.__class__.__name__, self.__class__._instcnt) - super(DelayQueue, self).__init__(name=name) + name = '{}-{}'.format(self.__class__.__name__, self.__class__._instcnt) + super().__init__(name=name) self.daemon = False if autostart: # immediately start processing - super(DelayQueue, self).start() + super().start() def run(self): """ @@ -114,7 +99,7 @@ class DelayQueue(threading.Thread): if self.__exit_req: return # shutdown thread # delay routine - now = curtime() + now = time.perf_counter() t_delta = now - self.time_limit # calculate early to improve perf. if times and t_delta > times[-1]: # if last call was before the limit time-window @@ -146,7 +131,7 @@ class DelayQueue(threading.Thread): self.__exit_req = True # gently request self._queue.put(None) # put something to unfreeze if frozen - super(DelayQueue, self).join(timeout=timeout) + super().join(timeout=timeout) @staticmethod def _default_exception_handler(exc): @@ -180,7 +165,7 @@ class DelayQueue(threading.Thread): # msg --> group delay if group msg, else no delay --> normal msg delay --> out # This way OS threading scheduler cares of timings accuracy. # (see time.time, time.clock, time.perf_counter, time.sleep @ docs.python.org) -class MessageQueue(object): +class MessageQueue: """ Implements callback processing with proper delays to avoid hitting Telegram's message limits. Contains two ``DelayQueue``, for group and for all messages, interconnected in delay chain. diff --git a/telegram/ext/picklepersistence.py b/telegram/ext/picklepersistence.py index 55e5e55f2..64f4f6fc6 100644 --- a/telegram/ext/picklepersistence.py +++ b/telegram/ext/picklepersistence.py @@ -66,9 +66,9 @@ class PicklePersistence(BasePersistence): store_bot_data=True, single_file=True, on_flush=False): - super(PicklePersistence, self).__init__(store_user_data=store_user_data, - store_chat_data=store_chat_data, - store_bot_data=store_bot_data) + super().__init__(store_user_data=store_user_data, + store_chat_data=store_chat_data, + store_bot_data=store_bot_data) self.filename = filename self.single_file = single_file self.on_flush = on_flush diff --git a/telegram/ext/regexhandler.py b/telegram/ext/regexhandler.py index 874125c6d..e8df56b11 100644 --- a/telegram/ext/regexhandler.py +++ b/telegram/ext/regexhandler.py @@ -110,21 +110,20 @@ class RegexHandler(MessageHandler): warnings.warn('RegexHandler is deprecated. See https://git.io/fxJuV for more info', TelegramDeprecationWarning, stacklevel=2) - super(RegexHandler, self).__init__(Filters.regex(pattern), - callback, - pass_update_queue=pass_update_queue, - pass_job_queue=pass_job_queue, - pass_user_data=pass_user_data, - pass_chat_data=pass_chat_data, - message_updates=message_updates, - channel_post_updates=channel_post_updates, - edited_updates=edited_updates) + super().__init__(Filters.regex(pattern), + callback, + pass_update_queue=pass_update_queue, + pass_job_queue=pass_job_queue, + pass_user_data=pass_user_data, + pass_chat_data=pass_chat_data, + message_updates=message_updates, + channel_post_updates=channel_post_updates, + edited_updates=edited_updates) self.pass_groups = pass_groups self.pass_groupdict = pass_groupdict def collect_optional_args(self, dispatcher, update=None, check_result=None): - optional_args = super(RegexHandler, self).collect_optional_args(dispatcher, update, - check_result) + optional_args = super().collect_optional_args(dispatcher, update, check_result) if self.pass_groups: optional_args['groups'] = check_result['matches'][0].groups() if self.pass_groupdict: diff --git a/telegram/ext/stringcommandhandler.py b/telegram/ext/stringcommandhandler.py index ca8821140..12cda5bf7 100644 --- a/telegram/ext/stringcommandhandler.py +++ b/telegram/ext/stringcommandhandler.py @@ -18,8 +18,6 @@ # along with this program. If not, see [http://www.gnu.org/licenses/]. """This module contains the StringCommandHandler class.""" -from future.utils import string_types - from .handler import Handler @@ -73,7 +71,7 @@ class StringCommandHandler(Handler): pass_args=False, pass_update_queue=False, pass_job_queue=False): - super(StringCommandHandler, self).__init__( + super().__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue) @@ -90,15 +88,13 @@ class StringCommandHandler(Handler): :obj:`bool` """ - if isinstance(update, string_types) and update.startswith('/'): + if isinstance(update, str) and update.startswith('/'): args = update[1:].split(' ') if args[0] == self.command: return args[1:] def collect_optional_args(self, dispatcher, update=None, check_result=None): - optional_args = super(StringCommandHandler, self).collect_optional_args(dispatcher, - update, - check_result) + optional_args = super().collect_optional_args(dispatcher, update, check_result) if self.pass_args: optional_args['args'] = check_result return optional_args diff --git a/telegram/ext/stringregexhandler.py b/telegram/ext/stringregexhandler.py index f676909ae..2177664bb 100644 --- a/telegram/ext/stringregexhandler.py +++ b/telegram/ext/stringregexhandler.py @@ -20,8 +20,6 @@ import re -from future.utils import string_types - from .handler import Handler @@ -85,12 +83,12 @@ class StringRegexHandler(Handler): pass_groupdict=False, pass_update_queue=False, pass_job_queue=False): - super(StringRegexHandler, self).__init__( + super().__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue) - if isinstance(pattern, string_types): + if isinstance(pattern, str): pattern = re.compile(pattern) self.pattern = pattern @@ -107,14 +105,13 @@ class StringRegexHandler(Handler): :obj:`bool` """ - if isinstance(update, string_types): + if isinstance(update, str): match = re.match(self.pattern, update) if match: return match def collect_optional_args(self, dispatcher, update=None, check_result=None): - optional_args = super(StringRegexHandler, self).collect_optional_args(dispatcher, - update, check_result) + optional_args = super().collect_optional_args(dispatcher, update, check_result) if self.pattern: if self.pass_groups: optional_args['groups'] = check_result.groups() diff --git a/telegram/ext/typehandler.py b/telegram/ext/typehandler.py index 55506f867..d39755e9e 100644 --- a/telegram/ext/typehandler.py +++ b/telegram/ext/typehandler.py @@ -65,7 +65,7 @@ class TypeHandler(Handler): strict=False, pass_update_queue=False, pass_job_queue=False): - super(TypeHandler, self).__init__( + super().__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue) diff --git a/telegram/ext/updater.py b/telegram/ext/updater.py index cced9394e..07e72e0bb 100644 --- a/telegram/ext/updater.py +++ b/telegram/ext/updater.py @@ -33,7 +33,7 @@ from telegram.utils.request import Request from telegram.utils.webhookhandler import (WebhookServer, WebhookAppClass) -class Updater(object): +class Updater: """ This class, which employs the :class:`telegram.ext.Dispatcher`, provides a frontend to :class:`telegram.Bot` to the programmer, so they can focus on coding the bot. Its purpose is to @@ -210,14 +210,14 @@ class Updater(object): def _thread_wrapper(self, target, *args, **kwargs): thr_name = current_thread().name - self.logger.debug('{0} - started'.format(thr_name)) + self.logger.debug('{} - started'.format(thr_name)) try: target(*args, **kwargs) except Exception: self.__exception_event.set() self.logger.exception('unhandled exception in %s', thr_name) raise - self.logger.debug('{0} - ended'.format(thr_name)) + self.logger.debug('{} - ended'.format(thr_name)) def start_polling(self, poll_interval=0.0, @@ -414,7 +414,7 @@ class Updater(object): self.logger.debug('Updater thread started (webhook)') use_ssl = cert is not None and key is not None if not url_path.startswith('/'): - url_path = '/{0}'.format(url_path) + url_path = '/{}'.format(url_path) # Create Tornado app instance app = WebhookAppClass(url_path, self.bot, self.update_queue, @@ -543,9 +543,9 @@ class Updater(object): 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 {} thread to end'.format(thr.name)) thr.join() - self.logger.debug('{0} thread has ended'.format(thr.name)) + self.logger.debug('{} thread has ended'.format(thr.name)) self.__threads = [] def signal_handler(self, signum, frame): diff --git a/telegram/files/animation.py b/telegram/files/animation.py index 4aa69afa5..2e63b1ca4 100644 --- a/telegram/files/animation.py +++ b/telegram/files/animation.py @@ -88,7 +88,7 @@ class Animation(TelegramObject): if not data: return None - data = super(Animation, cls).de_json(data, bot) + data = super().de_json(data, bot) data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot) diff --git a/telegram/files/document.py b/telegram/files/document.py index 89cfe7ef7..43ad2537f 100644 --- a/telegram/files/document.py +++ b/telegram/files/document.py @@ -76,7 +76,7 @@ class Document(TelegramObject): if not data: return None - data = super(Document, cls).de_json(data, bot) + data = super().de_json(data, bot) data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot) diff --git a/telegram/files/file.py b/telegram/files/file.py index 34a5fa803..c97bc06dc 100644 --- a/telegram/files/file.py +++ b/telegram/files/file.py @@ -21,7 +21,7 @@ from base64 import b64decode from os.path import basename import os -from future.backports.urllib import parse as urllib_parse +import urllib.parse as urllib_parse from telegram import TelegramObject from telegram.passport.credentials import decrypt diff --git a/telegram/files/inputfile.py b/telegram/files/inputfile.py index ce00d92b2..96c7c02fe 100644 --- a/telegram/files/inputfile.py +++ b/telegram/files/inputfile.py @@ -29,7 +29,7 @@ from telegram import TelegramError DEFAULT_MIME_TYPE = 'application/octet-stream' -class InputFile(object): +class InputFile: """This object represents a Telegram InputFile. Attributes: @@ -55,11 +55,7 @@ class InputFile(object): if filename: self.filename = filename - elif (hasattr(obj, 'name') - and not isinstance(obj.name, int) # py3 - and obj.name != ''): # py2 - # on py2.7, pylint fails to understand this properly - # pylint: disable=E1101 + elif (hasattr(obj, 'name') and not isinstance(obj.name, int)): self.filename = os.path.basename(obj.name) try: diff --git a/telegram/files/sticker.py b/telegram/files/sticker.py index c8d6518bf..08255a054 100644 --- a/telegram/files/sticker.py +++ b/telegram/files/sticker.py @@ -96,7 +96,7 @@ class Sticker(TelegramObject): if not data: return None - data = super(Sticker, cls).de_json(data, bot) + data = super().de_json(data, bot) data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot) data['mask_position'] = MaskPosition.de_json(data.get('mask_position'), bot) @@ -164,20 +164,20 @@ class StickerSet(TelegramObject): self._id_attrs = (self.name,) - @staticmethod - def de_json(data, bot): + @classmethod + def de_json(cls, data, bot): if not data: return None - data = super(StickerSet, StickerSet).de_json(data, bot) + data = super().de_json(data, bot) data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot) data['stickers'] = Sticker.de_list(data.get('stickers'), bot) - return StickerSet(bot=bot, **data) + return cls(bot=bot, **data) def to_dict(self): - data = super(StickerSet, self).to_dict() + data = super().to_dict() data['stickers'] = [s.to_dict() for s in data.get('stickers')] diff --git a/telegram/files/venue.py b/telegram/files/venue.py index 5ae92e222..6e7fbc5c3 100644 --- a/telegram/files/venue.py +++ b/telegram/files/venue.py @@ -57,7 +57,7 @@ class Venue(TelegramObject): @classmethod def de_json(cls, data, bot): - data = super(Venue, cls).de_json(data, bot) + data = super().de_json(data, bot) if not data: return None diff --git a/telegram/files/video.py b/telegram/files/video.py index a0a57d8e9..b49bf19ec 100644 --- a/telegram/files/video.py +++ b/telegram/files/video.py @@ -83,7 +83,7 @@ class Video(TelegramObject): if not data: return None - data = super(Video, cls).de_json(data, bot) + data = super().de_json(data, bot) data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot) diff --git a/telegram/files/videonote.py b/telegram/files/videonote.py index 529cc42b8..e92528b7d 100644 --- a/telegram/files/videonote.py +++ b/telegram/files/videonote.py @@ -75,7 +75,7 @@ class VideoNote(TelegramObject): if not data: return None - data = super(VideoNote, cls).de_json(data, bot) + data = super().de_json(data, bot) data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot) diff --git a/telegram/files/voice.py b/telegram/files/voice.py index 47892ec4f..22a4a70c2 100644 --- a/telegram/files/voice.py +++ b/telegram/files/voice.py @@ -71,7 +71,7 @@ class Voice(TelegramObject): if not data: return None - data = super(Voice, cls).de_json(data, bot) + data = super().de_json(data, bot) return cls(bot=bot, **data) diff --git a/telegram/games/game.py b/telegram/games/game.py index 68e3f5023..9fbf4b1cc 100644 --- a/telegram/games/game.py +++ b/telegram/games/game.py @@ -77,7 +77,7 @@ class Game(TelegramObject): if not data: return None - data = super(Game, cls).de_json(data, bot) + data = super().de_json(data, bot) data['photo'] = PhotoSize.de_list(data.get('photo'), bot) data['text_entities'] = MessageEntity.de_list(data.get('text_entities'), bot) @@ -86,7 +86,7 @@ class Game(TelegramObject): return cls(**data) def to_dict(self): - data = super(Game, self).to_dict() + data = super().to_dict() data['photo'] = [p.to_dict() for p in self.photo] if self.text_entities: diff --git a/telegram/games/gamehighscore.py b/telegram/games/gamehighscore.py index f09c3b747..93d18bb53 100644 --- a/telegram/games/gamehighscore.py +++ b/telegram/games/gamehighscore.py @@ -46,7 +46,7 @@ class GameHighScore(TelegramObject): if not data: return None - data = super(GameHighScore, cls).de_json(data, bot) + data = super().de_json(data, bot) data['user'] = User.de_json(data.get('user'), bot) diff --git a/telegram/inline/inlinekeyboardmarkup.py b/telegram/inline/inlinekeyboardmarkup.py index 2679fcdb9..6a6c15175 100644 --- a/telegram/inline/inlinekeyboardmarkup.py +++ b/telegram/inline/inlinekeyboardmarkup.py @@ -41,7 +41,7 @@ class InlineKeyboardMarkup(ReplyMarkup): self.inline_keyboard = inline_keyboard def to_dict(self): - data = super(InlineKeyboardMarkup, self).to_dict() + data = super().to_dict() data['inline_keyboard'] = [] for inline_keyboard in self.inline_keyboard: diff --git a/telegram/inline/inlinequery.py b/telegram/inline/inlinequery.py index a52a18c92..3c76e4497 100644 --- a/telegram/inline/inlinequery.py +++ b/telegram/inline/inlinequery.py @@ -65,7 +65,7 @@ class InlineQuery(TelegramObject): @classmethod def de_json(cls, data, bot): - data = super(InlineQuery, cls).de_json(data, bot) + data = super().de_json(data, bot) if not data: return None diff --git a/telegram/inline/inlinequeryresultarticle.py b/telegram/inline/inlinequeryresultarticle.py index 469fe33a6..cb13aae8c 100644 --- a/telegram/inline/inlinequeryresultarticle.py +++ b/telegram/inline/inlinequeryresultarticle.py @@ -72,7 +72,7 @@ class InlineQueryResultArticle(InlineQueryResult): **kwargs): # Required - super(InlineQueryResultArticle, self).__init__('article', id) + super().__init__('article', id) self.title = title self.input_message_content = input_message_content diff --git a/telegram/inline/inlinequeryresultaudio.py b/telegram/inline/inlinequeryresultaudio.py index 227d67c13..1d2026e65 100644 --- a/telegram/inline/inlinequeryresultaudio.py +++ b/telegram/inline/inlinequeryresultaudio.py @@ -75,7 +75,7 @@ class InlineQueryResultAudio(InlineQueryResult): **kwargs): # Required - super(InlineQueryResultAudio, self).__init__('audio', id) + super().__init__('audio', id) self.audio_url = audio_url self.title = title diff --git a/telegram/inline/inlinequeryresultcachedaudio.py b/telegram/inline/inlinequeryresultcachedaudio.py index 58d1d7947..eda2481ce 100644 --- a/telegram/inline/inlinequeryresultcachedaudio.py +++ b/telegram/inline/inlinequeryresultcachedaudio.py @@ -65,7 +65,7 @@ class InlineQueryResultCachedAudio(InlineQueryResult): parse_mode=DEFAULT_NONE, **kwargs): # Required - super(InlineQueryResultCachedAudio, self).__init__('audio', id) + super().__init__('audio', id) self.audio_file_id = audio_file_id # Optionals diff --git a/telegram/inline/inlinequeryresultcacheddocument.py b/telegram/inline/inlinequeryresultcacheddocument.py index c492b71b0..c3c923a8f 100644 --- a/telegram/inline/inlinequeryresultcacheddocument.py +++ b/telegram/inline/inlinequeryresultcacheddocument.py @@ -73,7 +73,7 @@ class InlineQueryResultCachedDocument(InlineQueryResult): parse_mode=DEFAULT_NONE, **kwargs): # Required - super(InlineQueryResultCachedDocument, self).__init__('document', id) + super().__init__('document', id) self.title = title self.document_file_id = document_file_id diff --git a/telegram/inline/inlinequeryresultcachedgif.py b/telegram/inline/inlinequeryresultcachedgif.py index 7e4f570a6..a688b1150 100644 --- a/telegram/inline/inlinequeryresultcachedgif.py +++ b/telegram/inline/inlinequeryresultcachedgif.py @@ -71,7 +71,7 @@ class InlineQueryResultCachedGif(InlineQueryResult): parse_mode=DEFAULT_NONE, **kwargs): # Required - super(InlineQueryResultCachedGif, self).__init__('gif', id) + super().__init__('gif', id) self.gif_file_id = gif_file_id # Optionals diff --git a/telegram/inline/inlinequeryresultcachedmpeg4gif.py b/telegram/inline/inlinequeryresultcachedmpeg4gif.py index d56b6c7f4..644045131 100644 --- a/telegram/inline/inlinequeryresultcachedmpeg4gif.py +++ b/telegram/inline/inlinequeryresultcachedmpeg4gif.py @@ -71,7 +71,7 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult): parse_mode=DEFAULT_NONE, **kwargs): # Required - super(InlineQueryResultCachedMpeg4Gif, self).__init__('mpeg4_gif', id) + super().__init__('mpeg4_gif', id) self.mpeg4_file_id = mpeg4_file_id # Optionals diff --git a/telegram/inline/inlinequeryresultcachedphoto.py b/telegram/inline/inlinequeryresultcachedphoto.py index c38a92223..8c41b3539 100644 --- a/telegram/inline/inlinequeryresultcachedphoto.py +++ b/telegram/inline/inlinequeryresultcachedphoto.py @@ -74,7 +74,7 @@ class InlineQueryResultCachedPhoto(InlineQueryResult): parse_mode=DEFAULT_NONE, **kwargs): # Required - super(InlineQueryResultCachedPhoto, self).__init__('photo', id) + super().__init__('photo', id) self.photo_file_id = photo_file_id # Optionals diff --git a/telegram/inline/inlinequeryresultcachedsticker.py b/telegram/inline/inlinequeryresultcachedsticker.py index 2ac096468..d963e5465 100644 --- a/telegram/inline/inlinequeryresultcachedsticker.py +++ b/telegram/inline/inlinequeryresultcachedsticker.py @@ -54,7 +54,7 @@ class InlineQueryResultCachedSticker(InlineQueryResult): input_message_content=None, **kwargs): # Required - super(InlineQueryResultCachedSticker, self).__init__('sticker', id) + super().__init__('sticker', id) self.sticker_file_id = sticker_file_id # Optionals diff --git a/telegram/inline/inlinequeryresultcachedvideo.py b/telegram/inline/inlinequeryresultcachedvideo.py index 8523e4ad8..8a6c574b3 100644 --- a/telegram/inline/inlinequeryresultcachedvideo.py +++ b/telegram/inline/inlinequeryresultcachedvideo.py @@ -74,7 +74,7 @@ class InlineQueryResultCachedVideo(InlineQueryResult): parse_mode=DEFAULT_NONE, **kwargs): # Required - super(InlineQueryResultCachedVideo, self).__init__('video', id) + super().__init__('video', id) self.video_file_id = video_file_id self.title = title diff --git a/telegram/inline/inlinequeryresultcachedvoice.py b/telegram/inline/inlinequeryresultcachedvoice.py index cdd443086..dfa2ac3af 100644 --- a/telegram/inline/inlinequeryresultcachedvoice.py +++ b/telegram/inline/inlinequeryresultcachedvoice.py @@ -68,7 +68,7 @@ class InlineQueryResultCachedVoice(InlineQueryResult): parse_mode=DEFAULT_NONE, **kwargs): # Required - super(InlineQueryResultCachedVoice, self).__init__('voice', id) + super().__init__('voice', id) self.voice_file_id = voice_file_id self.title = title diff --git a/telegram/inline/inlinequeryresultcontact.py b/telegram/inline/inlinequeryresultcontact.py index 64b97a28e..6233066b3 100644 --- a/telegram/inline/inlinequeryresultcontact.py +++ b/telegram/inline/inlinequeryresultcontact.py @@ -74,7 +74,7 @@ class InlineQueryResultContact(InlineQueryResult): vcard=None, **kwargs): # Required - super(InlineQueryResultContact, self).__init__('contact', id) + super().__init__('contact', id) self.phone_number = phone_number self.first_name = first_name diff --git a/telegram/inline/inlinequeryresultdocument.py b/telegram/inline/inlinequeryresultdocument.py index 718ffdab8..12be44d33 100644 --- a/telegram/inline/inlinequeryresultdocument.py +++ b/telegram/inline/inlinequeryresultdocument.py @@ -88,7 +88,7 @@ class InlineQueryResultDocument(InlineQueryResult): parse_mode=DEFAULT_NONE, **kwargs): # Required - super(InlineQueryResultDocument, self).__init__('document', id) + super().__init__('document', id) self.document_url = document_url self.title = title self.mime_type = mime_type diff --git a/telegram/inline/inlinequeryresultgame.py b/telegram/inline/inlinequeryresultgame.py index 4737eefae..03cc34b12 100644 --- a/telegram/inline/inlinequeryresultgame.py +++ b/telegram/inline/inlinequeryresultgame.py @@ -42,7 +42,7 @@ class InlineQueryResultGame(InlineQueryResult): def __init__(self, id, game_short_name, reply_markup=None, **kwargs): # Required - super(InlineQueryResultGame, self).__init__('game', id) + super().__init__('game', id) self.id = id self.game_short_name = game_short_name diff --git a/telegram/inline/inlinequeryresultgif.py b/telegram/inline/inlinequeryresultgif.py index 16694aa54..e45f569ec 100644 --- a/telegram/inline/inlinequeryresultgif.py +++ b/telegram/inline/inlinequeryresultgif.py @@ -83,7 +83,7 @@ class InlineQueryResultGif(InlineQueryResult): **kwargs): # Required - super(InlineQueryResultGif, self).__init__('gif', id) + super().__init__('gif', id) self.gif_url = gif_url self.thumb_url = thumb_url diff --git a/telegram/inline/inlinequeryresultlocation.py b/telegram/inline/inlinequeryresultlocation.py index fc92eed38..0d315e109 100644 --- a/telegram/inline/inlinequeryresultlocation.py +++ b/telegram/inline/inlinequeryresultlocation.py @@ -74,7 +74,7 @@ class InlineQueryResultLocation(InlineQueryResult): thumb_height=None, **kwargs): # Required - super(InlineQueryResultLocation, self).__init__('location', id) + super().__init__('location', id) self.latitude = latitude self.longitude = longitude self.title = title diff --git a/telegram/inline/inlinequeryresultmpeg4gif.py b/telegram/inline/inlinequeryresultmpeg4gif.py index c470b175c..b3ecd7621 100644 --- a/telegram/inline/inlinequeryresultmpeg4gif.py +++ b/telegram/inline/inlinequeryresultmpeg4gif.py @@ -84,7 +84,7 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult): **kwargs): # Required - super(InlineQueryResultMpeg4Gif, self).__init__('mpeg4_gif', id) + super().__init__('mpeg4_gif', id) self.mpeg4_url = mpeg4_url self.thumb_url = thumb_url diff --git a/telegram/inline/inlinequeryresultphoto.py b/telegram/inline/inlinequeryresultphoto.py index 47edb3aa1..c51fbda4b 100644 --- a/telegram/inline/inlinequeryresultphoto.py +++ b/telegram/inline/inlinequeryresultphoto.py @@ -84,7 +84,7 @@ class InlineQueryResultPhoto(InlineQueryResult): parse_mode=DEFAULT_NONE, **kwargs): # Required - super(InlineQueryResultPhoto, self).__init__('photo', id) + super().__init__('photo', id) self.photo_url = photo_url self.thumb_url = thumb_url diff --git a/telegram/inline/inlinequeryresultvenue.py b/telegram/inline/inlinequeryresultvenue.py index 0caee9151..296db4123 100644 --- a/telegram/inline/inlinequeryresultvenue.py +++ b/telegram/inline/inlinequeryresultvenue.py @@ -83,7 +83,7 @@ class InlineQueryResultVenue(InlineQueryResult): **kwargs): # Required - super(InlineQueryResultVenue, self).__init__('venue', id) + super().__init__('venue', id) self.latitude = latitude self.longitude = longitude self.title = title diff --git a/telegram/inline/inlinequeryresultvideo.py b/telegram/inline/inlinequeryresultvideo.py index 3b93f5b5e..5b1daa0b2 100644 --- a/telegram/inline/inlinequeryresultvideo.py +++ b/telegram/inline/inlinequeryresultvideo.py @@ -97,7 +97,7 @@ class InlineQueryResultVideo(InlineQueryResult): **kwargs): # Required - super(InlineQueryResultVideo, self).__init__('video', id) + super().__init__('video', id) self.video_url = video_url self.mime_type = mime_type self.thumb_url = thumb_url diff --git a/telegram/inline/inlinequeryresultvoice.py b/telegram/inline/inlinequeryresultvoice.py index 1474c3ae4..97a4acfc3 100644 --- a/telegram/inline/inlinequeryresultvoice.py +++ b/telegram/inline/inlinequeryresultvoice.py @@ -73,7 +73,7 @@ class InlineQueryResultVoice(InlineQueryResult): **kwargs): # Required - super(InlineQueryResultVoice, self).__init__('voice', id) + super().__init__('voice', id) self.voice_url = voice_url self.title = title diff --git a/telegram/message.py b/telegram/message.py index 9868158a6..ac3bb235a 100644 --- a/telegram/message.py +++ b/telegram/message.py @@ -364,7 +364,7 @@ class Message(TelegramObject): if not data: return None - data = super(Message, cls).de_json(data, bot) + data = super().de_json(data, bot) data['from_user'] = User.de_json(data.get('from'), bot) data['date'] = from_timestamp(data['date']) @@ -452,7 +452,7 @@ class Message(TelegramObject): return self.chat.id def to_dict(self): - data = super(Message, self).to_dict() + data = super().to_dict() # Required data['date'] = to_timestamp(self.date) diff --git a/telegram/messageentity.py b/telegram/messageentity.py index 308f5801f..5328ee5fe 100644 --- a/telegram/messageentity.py +++ b/telegram/messageentity.py @@ -65,7 +65,7 @@ class MessageEntity(TelegramObject): @classmethod def de_json(cls, data, bot): - data = super(MessageEntity, cls).de_json(data, bot) + data = super().de_json(data, bot) if not data: return None diff --git a/telegram/parsemode.py b/telegram/parsemode.py index d1699fdfc..40a966f21 100644 --- a/telegram/parsemode.py +++ b/telegram/parsemode.py @@ -20,7 +20,7 @@ """This module contains an object that represents a Telegram Message Parse Modes.""" -class ParseMode(object): +class ParseMode: """This object represents a Telegram Message Parse Modes.""" MARKDOWN = 'Markdown' diff --git a/telegram/passport/credentials.py b/telegram/passport/credentials.py index 110f091c4..6981ccecc 100644 --- a/telegram/passport/credentials.py +++ b/telegram/passport/credentials.py @@ -28,7 +28,6 @@ from cryptography.hazmat.primitives.ciphers import Cipher from cryptography.hazmat.primitives.ciphers.algorithms import AES from cryptography.hazmat.primitives.ciphers.modes import CBC from cryptography.hazmat.primitives.hashes import SHA512, SHA256, Hash, SHA1 -from future.utils import bord from telegram import TelegramObject, TelegramError @@ -39,8 +38,7 @@ class TelegramDecryptionError(TelegramError): """ def __init__(self, message): - super(TelegramDecryptionError, self).__init__("TelegramDecryptionError: " - "{}".format(message)) + super().__init__("TelegramDecryptionError: {}".format(message)) def decrypt(secret, hash, data): @@ -83,7 +81,7 @@ def decrypt(secret, hash, data): # Raise a error that is caught inside telegram.PassportData and transformed into a warning raise TelegramDecryptionError("Hashes are not equal! {} != {}".format(data_hash, hash)) # Return data without padding - return data[bord(data[0]):] + return data[data[0]:] def decrypt_json(secret, hash, data): @@ -134,7 +132,7 @@ class EncryptedCredentials(TelegramObject): if not data: return None - data = super(EncryptedCredentials, cls).de_json(data, bot) + data = super().de_json(data, bot) return cls(bot=bot, **data) @@ -347,7 +345,7 @@ class SecureValue(TelegramObject): return cls(bot=bot, **data) def to_dict(self): - data = super(SecureValue, self).to_dict() + data = super().to_dict() data['files'] = [p.to_dict() for p in self.files] data['translation'] = [p.to_dict() for p in self.translation] @@ -402,10 +400,10 @@ class DataCredentials(_CredentialsBase): """ def __init__(self, data_hash, secret, **kwargs): - super(DataCredentials, self).__init__(data_hash, secret, **kwargs) + super().__init__(data_hash, secret, **kwargs) def to_dict(self): - data = super(DataCredentials, self).to_dict() + data = super().to_dict() del data['file_hash'] del data['hash'] @@ -428,10 +426,10 @@ class FileCredentials(_CredentialsBase): """ def __init__(self, file_hash, secret, **kwargs): - super(FileCredentials, self).__init__(file_hash, secret, **kwargs) + super().__init__(file_hash, secret, **kwargs) def to_dict(self): - data = super(FileCredentials, self).to_dict() + data = super().to_dict() del data['data_hash'] del data['hash'] diff --git a/telegram/passport/encryptedpassportelement.py b/telegram/passport/encryptedpassportelement.py index 1959e5244..9297ab87b 100644 --- a/telegram/passport/encryptedpassportelement.py +++ b/telegram/passport/encryptedpassportelement.py @@ -19,8 +19,8 @@ """This module contains an object that represents a Telegram EncryptedPassportElement.""" from base64 import b64decode -from telegram import (TelegramObject, PassportFile, PersonalDetails, IdDocumentData, - ResidentialAddress) +from telegram import (IdDocumentData, PassportFile, PersonalDetails, + ResidentialAddress, TelegramObject) from telegram.passport.credentials import decrypt_json @@ -138,7 +138,7 @@ class EncryptedPassportElement(TelegramObject): if not data: return None - data = super(EncryptedPassportElement, cls).de_json(data, bot) + data = super().de_json(data, bot) data['files'] = PassportFile.de_list(data.get('files'), bot) or None data['front_side'] = PassportFile.de_json(data.get('front_side'), bot) @@ -153,7 +153,7 @@ class EncryptedPassportElement(TelegramObject): if not data: return None - data = super(EncryptedPassportElement, cls).de_json(data, bot) + data = super().de_json(data, bot) if data['type'] not in ('phone_number', 'email'): secure_data = getattr(credentials.secure_data, data['type']) @@ -197,7 +197,7 @@ class EncryptedPassportElement(TelegramObject): return encrypted_passport_elements def to_dict(self): - data = super(EncryptedPassportElement, self).to_dict() + data = super().to_dict() if self.files: data['files'] = [p.to_dict() for p in self.files] diff --git a/telegram/passport/passportdata.py b/telegram/passport/passportdata.py index 29deb6f86..e87a535bc 100644 --- a/telegram/passport/passportdata.py +++ b/telegram/passport/passportdata.py @@ -58,7 +58,7 @@ class PassportData(TelegramObject): if not data: return None - data = super(PassportData, cls).de_json(data, bot) + data = super().de_json(data, bot) data['data'] = EncryptedPassportElement.de_list(data.get('data'), bot) data['credentials'] = EncryptedCredentials.de_json(data.get('credentials'), bot) @@ -66,7 +66,7 @@ class PassportData(TelegramObject): return cls(bot=bot, **data) def to_dict(self): - data = super(PassportData, self).to_dict() + data = super().to_dict() data['data'] = [e.to_dict() for e in self.data] diff --git a/telegram/passport/passportelementerrors.py b/telegram/passport/passportelementerrors.py index d03d6cdc1..185d54d46 100644 --- a/telegram/passport/passportelementerrors.py +++ b/telegram/passport/passportelementerrors.py @@ -76,7 +76,7 @@ class PassportElementErrorDataField(PassportElementError): message, **kwargs): # Required - super(PassportElementErrorDataField, self).__init__('data', type, message) + super().__init__('data', type, message) self.field_name = field_name self.data_hash = data_hash @@ -111,7 +111,7 @@ class PassportElementErrorFile(PassportElementError): message, **kwargs): # Required - super(PassportElementErrorFile, self).__init__('file', type, message) + super().__init__('file', type, message) self.file_hash = file_hash self._id_attrs = (self.source, self.type, self.file_hash, self.message) @@ -145,7 +145,7 @@ class PassportElementErrorFiles(PassportElementError): message, **kwargs): # Required - super(PassportElementErrorFiles, self).__init__('files', type, message) + super().__init__('files', type, message) self.file_hashes = file_hashes self._id_attrs = ((self.source, self.type, self.message) @@ -180,7 +180,7 @@ class PassportElementErrorFrontSide(PassportElementError): message, **kwargs): # Required - super(PassportElementErrorFrontSide, self).__init__('front_side', type, message) + super().__init__('front_side', type, message) self.file_hash = file_hash self._id_attrs = (self.source, self.type, self.file_hash, self.message) @@ -214,7 +214,7 @@ class PassportElementErrorReverseSide(PassportElementError): message, **kwargs): # Required - super(PassportElementErrorReverseSide, self).__init__('reverse_side', type, message) + super().__init__('reverse_side', type, message) self.file_hash = file_hash self._id_attrs = (self.source, self.type, self.file_hash, self.message) @@ -246,7 +246,7 @@ class PassportElementErrorSelfie(PassportElementError): message, **kwargs): # Required - super(PassportElementErrorSelfie, self).__init__('selfie', type, message) + super().__init__('selfie', type, message) self.file_hash = file_hash self._id_attrs = (self.source, self.type, self.file_hash, self.message) @@ -282,8 +282,7 @@ class PassportElementErrorTranslationFile(PassportElementError): message, **kwargs): # Required - super(PassportElementErrorTranslationFile, self).__init__('translation_file', - type, message) + super().__init__('translation_file', type, message) self.file_hash = file_hash self._id_attrs = (self.source, self.type, self.file_hash, self.message) @@ -319,8 +318,7 @@ class PassportElementErrorTranslationFiles(PassportElementError): message, **kwargs): # Required - super(PassportElementErrorTranslationFiles, self).__init__('translation_files', - type, message) + super().__init__('translation_files', type, message) self.file_hashes = file_hashes self._id_attrs = ((self.source, self.type, self.message) @@ -351,7 +349,7 @@ class PassportElementErrorUnspecified(PassportElementError): message, **kwargs): # Required - super(PassportElementErrorUnspecified, self).__init__('unspecified', type, message) + super().__init__('unspecified', type, message) self.element_hash = element_hash self._id_attrs = (self.source, self.type, self.element_hash, self.message) diff --git a/telegram/passport/passportfile.py b/telegram/passport/passportfile.py index bdf6fc441..4936ab608 100644 --- a/telegram/passport/passportfile.py +++ b/telegram/passport/passportfile.py @@ -71,7 +71,7 @@ class PassportFile(TelegramObject): if not data: return None - data = super(PassportFile, cls).de_json(data, bot) + data = super().de_json(data, bot) return cls(bot=bot, **data) @@ -80,7 +80,7 @@ class PassportFile(TelegramObject): if not data: return None - data = super(PassportFile, cls).de_json(data, bot) + data = super().de_json(data, bot) data['credentials'] = credentials diff --git a/telegram/payment/orderinfo.py b/telegram/payment/orderinfo.py index 3cd342003..885f8b1ab 100644 --- a/telegram/payment/orderinfo.py +++ b/telegram/payment/orderinfo.py @@ -50,7 +50,7 @@ class OrderInfo(TelegramObject): if not data: return cls() - data = super(OrderInfo, cls).de_json(data, bot) + data = super().de_json(data, bot) data['shipping_address'] = ShippingAddress.de_json(data.get('shipping_address'), bot) diff --git a/telegram/payment/precheckoutquery.py b/telegram/payment/precheckoutquery.py index a8f6e8d49..ead678252 100644 --- a/telegram/payment/precheckoutquery.py +++ b/telegram/payment/precheckoutquery.py @@ -82,7 +82,7 @@ class PreCheckoutQuery(TelegramObject): if not data: return None - data = super(PreCheckoutQuery, cls).de_json(data, bot) + data = super().de_json(data, bot) data['from_user'] = User.de_json(data.pop('from'), bot) data['order_info'] = OrderInfo.de_json(data.get('order_info'), bot) diff --git a/telegram/payment/shippingoption.py b/telegram/payment/shippingoption.py index 522fb1076..a0aa3adf5 100644 --- a/telegram/payment/shippingoption.py +++ b/telegram/payment/shippingoption.py @@ -45,7 +45,7 @@ class ShippingOption(TelegramObject): self._id_attrs = (self.id,) def to_dict(self): - data = super(ShippingOption, self).to_dict() + data = super().to_dict() data['prices'] = [p.to_dict() for p in self.prices] diff --git a/telegram/payment/shippingquery.py b/telegram/payment/shippingquery.py index 549e35f5b..f0bc2d341 100644 --- a/telegram/payment/shippingquery.py +++ b/telegram/payment/shippingquery.py @@ -59,7 +59,7 @@ class ShippingQuery(TelegramObject): if not data: return None - data = super(ShippingQuery, cls).de_json(data, bot) + data = super().de_json(data, bot) data['from_user'] = User.de_json(data.pop('from'), bot) data['shipping_address'] = ShippingAddress.de_json(data.get('shipping_address'), bot) diff --git a/telegram/payment/successfulpayment.py b/telegram/payment/successfulpayment.py index 870c5b8b9..db010ad3d 100644 --- a/telegram/payment/successfulpayment.py +++ b/telegram/payment/successfulpayment.py @@ -74,7 +74,7 @@ class SuccessfulPayment(TelegramObject): if not data: return None - data = super(SuccessfulPayment, cls).de_json(data, bot) + data = super().de_json(data, bot) data['order_info'] = OrderInfo.de_json(data.get('order_info'), bot) return cls(**data) diff --git a/telegram/poll.py b/telegram/poll.py index f92224837..d8544e8ac 100644 --- a/telegram/poll.py +++ b/telegram/poll.py @@ -165,7 +165,7 @@ class Poll(TelegramObject): if not data: return None - data = super(Poll, cls).de_json(data, bot) + data = super().de_json(data, bot) data['options'] = [PollOption.de_json(option, bot) for option in data['options']] data['explanation_entities'] = MessageEntity.de_list(data.get('explanation_entities'), bot) @@ -174,7 +174,7 @@ class Poll(TelegramObject): return cls(**data) def to_dict(self): - data = super(Poll, self).to_dict() + data = super().to_dict() data['options'] = [x.to_dict() for x in self.options] if self.explanation_entities: diff --git a/telegram/replykeyboardmarkup.py b/telegram/replykeyboardmarkup.py index 5954b046e..c1f4d9ebc 100644 --- a/telegram/replykeyboardmarkup.py +++ b/telegram/replykeyboardmarkup.py @@ -73,7 +73,7 @@ class ReplyKeyboardMarkup(ReplyMarkup): self.selective = bool(selective) def to_dict(self): - data = super(ReplyKeyboardMarkup, self).to_dict() + data = super().to_dict() data['keyboard'] = [] for row in self.keyboard: diff --git a/telegram/update.py b/telegram/update.py index 499eeba9f..c6094d89e 100644 --- a/telegram/update.py +++ b/telegram/update.py @@ -223,7 +223,7 @@ class Update(TelegramObject): if not data: return None - data = super(Update, cls).de_json(data, bot) + data = super().de_json(data, bot) message = data.get('message') if message: diff --git a/telegram/user.py b/telegram/user.py index 69afb57de..095596cde 100644 --- a/telegram/user.py +++ b/telegram/user.py @@ -116,7 +116,7 @@ class User(TelegramObject): def de_json(cls, data, bot): if not data: return None - data = super(User, cls).de_json(data, bot) + data = super().de_json(data, bot) return cls(bot=bot, **data) diff --git a/telegram/userprofilephotos.py b/telegram/userprofilephotos.py index 5101a7f8e..02d26f339 100644 --- a/telegram/userprofilephotos.py +++ b/telegram/userprofilephotos.py @@ -45,14 +45,14 @@ class UserProfilePhotos(TelegramObject): if not data: return None - data = super(UserProfilePhotos, cls).de_json(data, bot) + data = super().de_json(data, bot) data['photos'] = [PhotoSize.de_list(photo, bot) for photo in data['photos']] return cls(**data) def to_dict(self): - data = super(UserProfilePhotos, self).to_dict() + data = super().to_dict() data['photos'] = [] for photo in self.photos: diff --git a/telegram/utils/deprecate.py b/telegram/utils/deprecate.py index 2ab03f320..73338a032 100644 --- a/telegram/utils/deprecate.py +++ b/telegram/utils/deprecate.py @@ -30,7 +30,7 @@ class TelegramDeprecationWarning(Warning): def warn_deprecate_obj(old, new, stacklevel=3): warnings.warn( - '{0} is being deprecated, please use {1} from now on.'.format(old, new), + '{} is being deprecated, please use {} from now on.'.format(old, new), category=TelegramDeprecationWarning, stacklevel=stacklevel) diff --git a/telegram/utils/helpers.py b/telegram/utils/helpers.py index e02bcaf37..b5b766909 100644 --- a/telegram/utils/helpers.py +++ b/telegram/utils/helpers.py @@ -19,19 +19,18 @@ """This module contains helper functions.""" import datetime as dtm # dtm = "DateTime Module" +import re +import signal import time - from collections import defaultdict +from html import escape from numbers import Number try: import ujson as json except ImportError: import json -from html import escape -import re -import signal # From https://stackoverflow.com/questions/2549939/get-signal-names-from-numbers-in-python _signames = {v: k @@ -58,26 +57,29 @@ def escape_markdown(text, version=1, entity_type=None): ``version=2``, will be ignored else. """ if int(version) == 1: - escape_chars = '\*_`\[' + escape_chars = r'_*`[' elif int(version) == 2: if entity_type == 'pre' or entity_type == 'code': - escape_chars = '`\\\\' + escape_chars = r'\`' elif entity_type == 'text_link': - escape_chars = ')\\\\' + escape_chars = r'\)' else: - escape_chars = '_*\[\]()~`>\#\+\-=|{}\.!' + escape_chars = r'_*[]()~`>#+-=|{}.!' else: raise ValueError('Markdown version must be either 1 or 2!') - return re.sub(r'([%s])' % escape_chars, r'\\\1', text) + return re.sub('([{}])'.format(re.escape(escape_chars)), r'\\\1', text) # -------- date/time related helpers -------- # TODO: add generic specification of UTC for naive datetimes to docs def _datetime_to_float_timestamp(dt_obj): - """Converts a datetime object to a float timestamp (with sub-second precision). - If the datetime object is timezone-naive, it is assumed to be in UTC.""" + """ + Converts a datetime object to a float timestamp (with sub-second precision). + If the datetime object is timezone-naive, it is assumed to be in UTC. + """ + if dt_obj.tzinfo is None: dt_obj = dt_obj.replace(tzinfo=dtm.timezone.utc) return dt_obj.timestamp() @@ -288,7 +290,7 @@ def create_deep_linked_url(bot_username, payload=None, group=False): else: key = 'start' - return '{0}?{1}={2}'.format( + return '{}?{}={}'.format( base_url, key, payload diff --git a/telegram/utils/promise.py b/telegram/utils/promise.py index eb93cb29c..76139a6f1 100644 --- a/telegram/utils/promise.py +++ b/telegram/utils/promise.py @@ -25,7 +25,7 @@ from threading import Event logger = logging.getLogger(__name__) -class Promise(object): +class Promise: """A simple Promise implementation for use with the run_async decorator, DelayQueue etc. Args: diff --git a/telegram/utils/request.py b/telegram/utils/request.py index ba1879bae..acc5d7224 100644 --- a/telegram/utils/request.py +++ b/telegram/utils/request.py @@ -22,7 +22,6 @@ import os import socket import sys import warnings -from builtins import str # For PY2 try: import ujson as json @@ -62,11 +61,11 @@ def _render_part(self, name, value): """ Monkey patch urllib3.urllib3.fields.RequestField to make it *not* support RFC2231 compliant Content-Disposition headers since telegram servers don't understand it. Instead just escape - \ and " and replace any \n and \r with a space. + \\ and " and replace any \n and \r with a space. """ value = value.replace(u'\\', u'\\\\').replace(u'"', u'\\"') value = value.replace(u'\r', u' ').replace(u'\n', u' ') - return u'%s="%s"' % (name, value) + return u'{}="{}"'.format(name, value) RequestField._render_part = _render_part @@ -76,7 +75,7 @@ logging.getLogger('urllib3').setLevel(logging.WARNING) USER_AGENT = 'Python Telegram Bot (https://github.com/python-telegram-bot/python-telegram-bot)' -class Request(object): +class Request: """ Helper class for python-telegram-bot which provides methods to perform POST & GET towards telegram servers. @@ -228,7 +227,7 @@ class Request(object): except urllib3.exceptions.HTTPError as error: # HTTPError must come last as its the base urllib3 exception class # TODO: do something smart here; for now just raise NetworkError - raise NetworkError('urllib3 HTTPError {0}'.format(error)) + raise NetworkError('urllib3 HTTPError {}'.format(error)) if 200 <= resp.status <= 299: # 200-299 range are HTTP success statuses @@ -254,7 +253,7 @@ class Request(object): elif resp.status == 502: raise NetworkError('Bad Gateway') else: - raise NetworkError('{0} ({1})'.format(message, resp.status)) + raise NetworkError('{} ({})'.format(message, resp.status)) def get(self, url, timeout=None): """Request an URL. @@ -282,7 +281,7 @@ class Request(object): Args: url (:obj:`str`): The web location we want to retrieve. - data (dict[str, str|int]): A dict of key/value pairs. Note: On py2.7 value is unicode. + data (dict[str, str|int]): A dict of key/value pairs. timeout (:obj:`int` | :obj:`float`): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). diff --git a/telegram/utils/webhookhandler.py b/telegram/utils/webhookhandler.py index 3287e691d..ccda56491 100644 --- a/telegram/utils/webhookhandler.py +++ b/telegram/utils/webhookhandler.py @@ -19,7 +19,6 @@ import sys import logging from telegram import Update -from future.utils import bytes_to_native_str from threading import Lock try: import ujson as json @@ -30,7 +29,7 @@ from tornado.ioloop import IOLoop import tornado.web -class WebhookServer(object): +class WebhookServer: def __init__(self, listen, port, webhook_app, ssl_ctx): self.http_server = HTTPServer(webhook_app, ssl_options=ssl_ctx) @@ -73,7 +72,7 @@ class WebhookAppClass(tornado.web.Application): self.shared_objects = {"bot": bot, "update_queue": update_queue, "default_quote": default_quote} handlers = [ - (r"{0}/?".format(webhook_path), WebhookHandler, + (r"{}/?".format(webhook_path), WebhookHandler, self.shared_objects) ] # noqa tornado.web.Application.__init__(self, handlers) @@ -87,7 +86,7 @@ class WebhookHandler(tornado.web.RequestHandler): SUPPORTED_METHODS = ["POST"] def __init__(self, application, request, **kwargs): - super(WebhookHandler, self).__init__(application, request, **kwargs) + super().__init__(application, request, **kwargs) self.logger = logging.getLogger(__name__) self._init_asyncio_patch() @@ -130,7 +129,7 @@ class WebhookHandler(tornado.web.RequestHandler): def post(self): self.logger.debug('Webhook triggered') self._validate_post() - json_string = bytes_to_native_str(self.request.body) + json_string = self.request.body.decode() data = json.loads(json_string) self.set_status(200) self.logger.debug('Webhook received data: ' + json_string) @@ -158,6 +157,7 @@ class WebhookHandler(tornado.web.RequestHandler): The client ip is prefixed to every message. """ - super(WebhookHandler, self).write_error(status_code, **kwargs) - self.logger.debug("%s - - %s" % (self.request.remote_ip, "Exception in WebhookHandler"), + super().write_error(status_code, **kwargs) + self.logger.debug("{} - - {}".format(self.request.remote_ip, + "Exception in WebhookHandler"), exc_info=kwargs['exc_info']) diff --git a/tests/conftest.py b/tests/conftest.py index 1df673997..e6423476e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -18,7 +18,6 @@ # along with this program. If not, see [http://www.gnu.org/licenses/]. import datetime import os -import sys import re from collections import defaultdict from queue import Queue @@ -164,9 +163,8 @@ def class_thumb_file(): def pytest_configure(config): - if sys.version_info >= (3,): - config.addinivalue_line('filterwarnings', 'ignore::ResourceWarning') - # TODO: Write so good code that we don't need to ignore ResourceWarnings anymore + config.addinivalue_line('filterwarnings', 'ignore::ResourceWarning') + # TODO: Write so good code that we don't need to ignore ResourceWarnings anymore def make_bot(bot_info, **kwargs): diff --git a/tests/test_animation.py b/tests/test_animation.py index 01a1e51e3..6e9597410 100644 --- a/tests/test_animation.py +++ b/tests/test_animation.py @@ -39,7 +39,7 @@ def animation(bot, chat_id): thumb=open('tests/data/thumb.jpg', 'rb')).animation -class TestAnimation(object): +class TestAnimation: animation_file_id = 'CgADAQADngIAAuyVeEez0xRovKi9VAI' animation_file_unique_id = 'adc3145fd2e84d95b64d68eaa22aa33e' width = 320 diff --git a/tests/test_audio.py b/tests/test_audio.py index db0c4afa7..cd9fa266e 100644 --- a/tests/test_audio.py +++ b/tests/test_audio.py @@ -39,7 +39,7 @@ def audio(bot, chat_id): thumb=open('tests/data/thumb.jpg', 'rb')).audio -class TestAudio(object): +class TestAudio: caption = 'Test *audio*' performer = 'Leandro Toledo' title = 'Teste' diff --git a/tests/test_bot.py b/tests/test_bot.py index 3df65b78a..8c4709281 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -22,7 +22,6 @@ from platform import python_implementation import pytest from flaky import flaky -from future.utils import string_types from telegram import (Bot, Update, ChatAction, TelegramError, User, InlineKeyboardMarkup, InlineKeyboardButton, InlineQueryResultArticle, InputTextMessageContent, @@ -55,7 +54,7 @@ def chat_permissions(): return ChatPermissions(can_send_messages=False, can_change_info=False, can_invite_users=False) -class TestBot(object): +class TestBot: @pytest.mark.parametrize('token', argvalues=[ '123', '12a:abcd1234', @@ -879,7 +878,7 @@ class TestBot(object): def test_export_chat_invite_link(self, bot, channel_id): # Each link is unique apparently invite_link = bot.export_chat_invite_link(channel_id) - assert isinstance(invite_link, string_types) + assert isinstance(invite_link, str) assert invite_link != '' @flaky(3, 1) diff --git a/tests/test_botcommand.py b/tests/test_botcommand.py index 9b339276d..79c3b6d5e 100644 --- a/tests/test_botcommand.py +++ b/tests/test_botcommand.py @@ -27,7 +27,7 @@ def bot_command(): return BotCommand(command='start', description='A command') -class TestBotCommand(object): +class TestBotCommand: command = 'start' description = 'A command' diff --git a/tests/test_callbackcontext.py b/tests/test_callbackcontext.py index ce76b5079..f90ef7b6e 100644 --- a/tests/test_callbackcontext.py +++ b/tests/test_callbackcontext.py @@ -22,7 +22,7 @@ from telegram import Update, Message, Chat, User, TelegramError from telegram.ext import CallbackContext -class TestCallbackContext(object): +class TestCallbackContext: def test_non_context_dp(self, dp): with pytest.raises(ValueError): CallbackContext(dp) diff --git a/tests/test_callbackquery.py b/tests/test_callbackquery.py index 098f142f5..be39e7aa2 100644 --- a/tests/test_callbackquery.py +++ b/tests/test_callbackquery.py @@ -37,7 +37,7 @@ def callback_query(bot, request): return cbq -class TestCallbackQuery(object): +class TestCallbackQuery: id_ = 'id' from_user = User(1, 'test_user', False) chat_instance = 'chat_instance' diff --git a/tests/test_callbackqueryhandler.py b/tests/test_callbackqueryhandler.py index 66fe5359e..d81ef59f5 100644 --- a/tests/test_callbackqueryhandler.py +++ b/tests/test_callbackqueryhandler.py @@ -52,7 +52,7 @@ def callback_query(bot): return Update(0, callback_query=CallbackQuery(2, User(1, '', False), None, data='test data')) -class TestCallbackQueryHandler(object): +class TestCallbackQueryHandler: test_flag = False @pytest.fixture(autouse=True) diff --git a/tests/test_chat.py b/tests/test_chat.py index fb77e2485..8c63de4d8 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -33,7 +33,7 @@ def chat(bot): slow_mode_delay=TestChat.slow_mode_delay) -class TestChat(object): +class TestChat: id_ = -28767330 title = 'ToledosPalaceBot - Group' type_ = 'group' diff --git a/tests/test_chatmember.py b/tests/test_chatmember.py index 6591225df..404e55a00 100644 --- a/tests/test_chatmember.py +++ b/tests/test_chatmember.py @@ -34,7 +34,7 @@ def chat_member(user): return ChatMember(user, TestChatMember.status) -class TestChatMember(object): +class TestChatMember: status = ChatMember.CREATOR def test_de_json_required_args(self, bot, user): diff --git a/tests/test_chatpermissions.py b/tests/test_chatpermissions.py index dbf5558e5..c37c8a0a1 100644 --- a/tests/test_chatpermissions.py +++ b/tests/test_chatpermissions.py @@ -30,7 +30,7 @@ def chat_permissions(): can_invite_users=True, can_pin_messages=True) -class TestChatPermissions(object): +class TestChatPermissions: can_send_messages = True can_send_media_messages = True can_send_polls = True diff --git a/tests/test_chatphoto.py b/tests/test_chatphoto.py index 3dab90307..eff33795e 100644 --- a/tests/test_chatphoto.py +++ b/tests/test_chatphoto.py @@ -40,7 +40,7 @@ def chat_photo(bot, super_group_id): return expect_bad_request(func, 'Type of file mismatch', 'Telegram did not accept the file.') -class TestChatPhoto(object): +class TestChatPhoto: chatphoto_small_file_id = 'smallCgADAQADngIAAuyVeEez0xRovKi9VAI' chatphoto_big_file_id = 'bigCgADAQADngIAAuyVeEez0xRovKi9VAI' chatphoto_small_file_unique_id = 'smalladc3145fd2e84d95b64d68eaa22aa33e' diff --git a/tests/test_choseninlineresult.py b/tests/test_choseninlineresult.py index 29772fe03..6511f8b32 100644 --- a/tests/test_choseninlineresult.py +++ b/tests/test_choseninlineresult.py @@ -32,7 +32,7 @@ def chosen_inline_result(user): return ChosenInlineResult(TestChosenInlineResult.result_id, user, TestChosenInlineResult.query) -class TestChosenInlineResult(object): +class TestChosenInlineResult: result_id = 'result id' query = 'query text' diff --git a/tests/test_choseninlineresulthandler.py b/tests/test_choseninlineresulthandler.py index c8e0711eb..f09479e8b 100644 --- a/tests/test_choseninlineresulthandler.py +++ b/tests/test_choseninlineresulthandler.py @@ -55,7 +55,7 @@ def chosen_inline_result(): 'query')) -class TestChosenInlineResultHandler(object): +class TestChosenInlineResultHandler: test_flag = False @pytest.fixture(autouse=True) diff --git a/tests/test_commandhandler.py b/tests/test_commandhandler.py index b37c76594..0783e8e2a 100644 --- a/tests/test_commandhandler.py +++ b/tests/test_commandhandler.py @@ -42,7 +42,7 @@ def is_match(handler, update): return check is not None and check is not False -class BaseTest(object): +class BaseTest: """Base class for command and prefix handler test classes. Contains utility methods an several callbacks used by both classes.""" test_flag = False diff --git a/tests/test_constants.py b/tests/test_constants.py index 780532f2c..c0a279ca0 100644 --- a/tests/test_constants.py +++ b/tests/test_constants.py @@ -23,7 +23,7 @@ from telegram import constants from telegram.error import BadRequest -class TestConstants(object): +class TestConstants: @flaky(3, 1) @pytest.mark.timeout(10) def test_max_message_length(self, bot, chat_id): diff --git a/tests/test_contact.py b/tests/test_contact.py index cbf29f886..a3db548cf 100644 --- a/tests/test_contact.py +++ b/tests/test_contact.py @@ -28,7 +28,7 @@ def contact(): TestContact.user_id) -class TestContact(object): +class TestContact: phone_number = '+11234567890' first_name = 'Leandro' last_name = 'Toledo' diff --git a/tests/test_conversationhandler.py b/tests/test_conversationhandler.py index ff890628c..0bdbc4eb4 100644 --- a/tests/test_conversationhandler.py +++ b/tests/test_conversationhandler.py @@ -37,7 +37,7 @@ def user2(): return User(first_name='Mister Test', id=124, is_bot=False) -class TestConversationHandler(object): +class TestConversationHandler: # State definitions # At first we're thirsty. Then we brew coffee, we drink it # and then we can start coding! diff --git a/tests/test_defaults.py b/tests/test_defaults.py index 1f98ad46e..d67cfc6b8 100644 --- a/tests/test_defaults.py +++ b/tests/test_defaults.py @@ -23,7 +23,7 @@ from telegram.ext import Defaults from telegram import User -class TestDefault(object): +class TestDefault: def test_data_assignment(self, cdp): defaults = Defaults() diff --git a/tests/test_dice.py b/tests/test_dice.py index 1770715d8..50ff23f59 100644 --- a/tests/test_dice.py +++ b/tests/test_dice.py @@ -28,7 +28,7 @@ def dice(request): return Dice(value=5, emoji=request.param) -class TestDice(object): +class TestDice: value = 4 @pytest.mark.parametrize('emoji', Dice.ALL_EMOJI) diff --git a/tests/test_dispatcher.py b/tests/test_dispatcher.py index 84ecd09c3..26949ddc5 100644 --- a/tests/test_dispatcher.py +++ b/tests/test_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/]. -import sys from queue import Queue from threading import current_thread from time import sleep @@ -38,7 +37,7 @@ def dp2(bot): yield dp -class TestDispatcher(object): +class TestDispatcher: message_update = Update(1, message=Message(1, User(1, '', False), None, Chat(1, ''), text='Text')) received = None @@ -350,7 +349,7 @@ class TestDispatcher(object): class OwnPersistence(BasePersistence): def __init__(self): - super(BasePersistence, self).__init__() + super().__init__() self.store_user_data = True self.store_chat_data = True self.store_bot_data = True @@ -450,7 +449,6 @@ class TestDispatcher(object): for thread_name in thread_names: assert thread_name.startswith("Bot:{}:worker:".format(dp2.bot.id)) - @pytest.mark.skipif(sys.version_info < (3, 0), reason='pytest fails this for no reason') def test_non_context_deprecation(self, dp): with pytest.warns(TelegramDeprecationWarning): Dispatcher(dp.bot, dp.update_queue, job_queue=dp.job_queue, workers=0, diff --git a/tests/test_document.py b/tests/test_document.py index 92d90c479..995b36135 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -38,7 +38,7 @@ def document(bot, chat_id): return bot.send_document(chat_id, document=f, timeout=50).document -class TestDocument(object): +class TestDocument: caption = 'DocumentTest - *Caption*' document_file_url = 'https://python-telegram-bot.org/static/testfiles/telegram.gif' file_size = 12948 diff --git a/tests/test_encryptedcredentials.py b/tests/test_encryptedcredentials.py index 867c4da8f..9528eec23 100644 --- a/tests/test_encryptedcredentials.py +++ b/tests/test_encryptedcredentials.py @@ -29,7 +29,7 @@ def encrypted_credentials(): TestEncryptedCredentials.secret) -class TestEncryptedCredentials(object): +class TestEncryptedCredentials: data = 'data' hash = 'hash' secret = 'secret' diff --git a/tests/test_encryptedpassportelement.py b/tests/test_encryptedpassportelement.py index 7aab1549c..bb1076679 100644 --- a/tests/test_encryptedpassportelement.py +++ b/tests/test_encryptedpassportelement.py @@ -34,7 +34,7 @@ def encrypted_passport_element(): selfie=TestEncryptedPassportElement.selfie) -class TestEncryptedPassportElement(object): +class TestEncryptedPassportElement: type_ = 'type' data = 'data' phone_number = 'phone_number' diff --git a/tests/test_error.py b/tests/test_error.py index b9179326e..a20880248 100644 --- a/tests/test_error.py +++ b/tests/test_error.py @@ -23,7 +23,7 @@ from telegram.error import Unauthorized, InvalidToken, NetworkError, BadRequest, ChatMigrated, RetryAfter, Conflict -class TestErrors(object): +class TestErrors: def test_telegram_error(self): with pytest.raises(TelegramError, match="^test message$"): raise TelegramError("test message") diff --git a/tests/test_file.py b/tests/test_file.py index 0a1f2c923..f2626ce92 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -35,7 +35,7 @@ def file(bot): bot=bot) -class TestFile(object): +class TestFile: file_id = 'NOTVALIDDOESNOTMATTER' file_unique_id = 'adc3145fd2e84d95b64d68eaa22aa33e' file_path = ( diff --git a/tests/test_filters.py b/tests/test_filters.py index 6d8917d87..90afd2bf2 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -37,7 +37,7 @@ def message_entity(request): return MessageEntity(request.param, 0, 0, url='', user='') -class TestFilters(object): +class TestFilters: def test_filters_all(self, update): assert Filters.all(update) @@ -912,9 +912,9 @@ class TestFilters(object): update.message.pinned_message = True assert (Filters.text & (Filters.forwarded | Filters.status_update)(update)) - assert str((Filters.text & (Filters.forwarded | Filters.entity( - MessageEntity.MENTION)))) == '>' + assert str(Filters.text & (Filters.forwarded | Filters.entity( + MessageEntity.MENTION))) == '>' def test_inverted_filters(self, update): update.message.text = '/test' diff --git a/tests/test_forcereply.py b/tests/test_forcereply.py index 5f4649dd1..c4ac35464 100644 --- a/tests/test_forcereply.py +++ b/tests/test_forcereply.py @@ -28,7 +28,7 @@ def force_reply(): return ForceReply(TestForceReply.force_reply, TestForceReply.selective) -class TestForceReply(object): +class TestForceReply: force_reply = True selective = True diff --git a/tests/test_game.py b/tests/test_game.py index 23a01565d..febbd8da7 100644 --- a/tests/test_game.py +++ b/tests/test_game.py @@ -32,7 +32,7 @@ def game(): animation=TestGame.animation) -class TestGame(object): +class TestGame: title = 'Python-telegram-bot Test Game' description = 'description' photo = [PhotoSize('Blah', 'ElseBlah', 640, 360, file_size=0)] diff --git a/tests/test_gamehighscore.py b/tests/test_gamehighscore.py index 55788a0c0..15edc1fed 100644 --- a/tests/test_gamehighscore.py +++ b/tests/test_gamehighscore.py @@ -29,7 +29,7 @@ def game_highscore(): TestGameHighScore.score) -class TestGameHighScore(object): +class TestGameHighScore: position = 12 user = User(2, 'test user', False) score = 42 diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 253b500c4..fd74f496b 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -40,23 +40,23 @@ RELATIVE_TIME_SPECS = DELTA_TIME_SPECS + TIME_OF_DAY_TIME_SPECS TIME_SPECS = ABSOLUTE_TIME_SPECS + RELATIVE_TIME_SPECS -class TestHelpers(object): +class TestHelpers: def test_escape_markdown(self): test_str = '*bold*, _italic_, `code`, [text_link](http://github.com/)' - expected_str = '\*bold\*, \_italic\_, \`code\`, \[text\_link](http://github.com/)' + expected_str = r'\*bold\*, \_italic\_, \`code\`, \[text\_link](http://github.com/)' assert expected_str == helpers.escape_markdown(test_str) def test_escape_markdown_v2(self): test_str = 'a_b*c[d]e (fg) h~I`>JK#L+MN -O=|p{qr}s.t! u' - expected_str = 'a\_b\*c\[d\]e \(fg\) h\~I\`\>JK\#L\+MN \-O\=\|p\{qr\}s\.t\! u' + expected_str = r'a\_b\*c\[d\]e \(fg\) h\~I\`\>JK\#L\+MN \-O\=\|p\{qr\}s\.t\! u' assert expected_str == helpers.escape_markdown(test_str, version=2) def test_escape_markdown_v2_monospaced(self): - test_str = 'mono/pre: `abc` \int (`\some \`stuff)' - expected_str = 'mono/pre: \`abc\` \\\\int (\`\\\\some \\\\\`stuff)' + test_str = r'mono/pre: `abc` \int (`\some \`stuff)' + expected_str = 'mono/pre: \\`abc\\` \\\\int (\\`\\\\some \\\\\\`stuff)' assert expected_str == helpers.escape_markdown(test_str, version=2, entity_type=MessageEntity.PRE) @@ -65,8 +65,8 @@ class TestHelpers(object): def test_escape_markdown_v2_text_link(self): - test_str = 'https://url.containing/funny)cha)\\ra\)cter\s' - expected_str = 'https://url.containing/funny\)cha\)\\\\ra\\\\\)cter\\\\s' + test_str = 'https://url.containing/funny)cha)\\ra\\)cter\\s' + expected_str = 'https://url.containing/funny\\)cha\\)\\\\ra\\\\\\)cter\\\\s' assert expected_str == helpers.escape_markdown(test_str, version=2, entity_type=MessageEntity.TEXT_LINK) diff --git a/tests/test_inlinekeyboardbutton.py b/tests/test_inlinekeyboardbutton.py index 2513959ee..077c688a8 100644 --- a/tests/test_inlinekeyboardbutton.py +++ b/tests/test_inlinekeyboardbutton.py @@ -35,7 +35,7 @@ def inline_keyboard_button(): login_url=TestInlineKeyboardButton.login_url) -class TestInlineKeyboardButton(object): +class TestInlineKeyboardButton: text = 'text' url = 'url' callback_data = 'callback data' diff --git a/tests/test_inlinekeyboardmarkup.py b/tests/test_inlinekeyboardmarkup.py index 67a6d5fcd..cf80e93d7 100644 --- a/tests/test_inlinekeyboardmarkup.py +++ b/tests/test_inlinekeyboardmarkup.py @@ -28,7 +28,7 @@ def inline_keyboard_markup(): return InlineKeyboardMarkup(TestInlineKeyboardMarkup.inline_keyboard) -class TestInlineKeyboardMarkup(object): +class TestInlineKeyboardMarkup: inline_keyboard = [[ InlineKeyboardButton(text='button1', callback_data='data1'), InlineKeyboardButton(text='button2', callback_data='data2') diff --git a/tests/test_inlinequery.py b/tests/test_inlinequery.py index 967c7bf50..0099bd78f 100644 --- a/tests/test_inlinequery.py +++ b/tests/test_inlinequery.py @@ -28,7 +28,7 @@ def inline_query(bot): TestInlineQuery.offset, location=TestInlineQuery.location, bot=bot) -class TestInlineQuery(object): +class TestInlineQuery: id_ = 1234 from_user = User(1, 'First name', False) query = 'query text' diff --git a/tests/test_inlinequeryhandler.py b/tests/test_inlinequeryhandler.py index 9e3e7a951..f526aa37d 100644 --- a/tests/test_inlinequeryhandler.py +++ b/tests/test_inlinequeryhandler.py @@ -56,7 +56,7 @@ def inline_query(bot): longitude=-46.788279))) -class TestCallbackQueryHandler(object): +class TestCallbackQueryHandler: test_flag = False @pytest.fixture(autouse=True) diff --git a/tests/test_inlinequeryresultarticle.py b/tests/test_inlinequeryresultarticle.py index ec960648e..7eefe6bb4 100644 --- a/tests/test_inlinequeryresultarticle.py +++ b/tests/test_inlinequeryresultarticle.py @@ -38,7 +38,7 @@ def inline_query_result_article(): thumb_width=TestInlineQueryResultArticle.thumb_width) -class TestInlineQueryResultArticle(object): +class TestInlineQueryResultArticle: id_ = 'id' type_ = 'article' title = 'title' diff --git a/tests/test_inlinequeryresultaudio.py b/tests/test_inlinequeryresultaudio.py index da3e49167..85eea687c 100644 --- a/tests/test_inlinequeryresultaudio.py +++ b/tests/test_inlinequeryresultaudio.py @@ -37,7 +37,7 @@ def inline_query_result_audio(): reply_markup=TestInlineQueryResultAudio.reply_markup) -class TestInlineQueryResultAudio(object): +class TestInlineQueryResultAudio: id_ = 'id' type_ = 'audio' audio_url = 'audio url' diff --git a/tests/test_inlinequeryresultcachedaudio.py b/tests/test_inlinequeryresultcachedaudio.py index 400a89a5a..ae77853dc 100644 --- a/tests/test_inlinequeryresultcachedaudio.py +++ b/tests/test_inlinequeryresultcachedaudio.py @@ -34,7 +34,7 @@ def inline_query_result_cached_audio(): reply_markup=TestInlineQueryResultCachedAudio.reply_markup) -class TestInlineQueryResultCachedAudio(object): +class TestInlineQueryResultCachedAudio: id_ = 'id' type_ = 'audio' audio_file_id = 'audio file id' diff --git a/tests/test_inlinequeryresultcacheddocument.py b/tests/test_inlinequeryresultcacheddocument.py index f8c61f80a..812dec3f6 100644 --- a/tests/test_inlinequeryresultcacheddocument.py +++ b/tests/test_inlinequeryresultcacheddocument.py @@ -36,7 +36,7 @@ def inline_query_result_cached_document(): reply_markup=TestInlineQueryResultCachedDocument.reply_markup) -class TestInlineQueryResultCachedDocument(object): +class TestInlineQueryResultCachedDocument: id_ = 'id' type_ = 'document' document_file_id = 'document file id' diff --git a/tests/test_inlinequeryresultcachedgif.py b/tests/test_inlinequeryresultcachedgif.py index 7b772c58e..f1ec88fa0 100644 --- a/tests/test_inlinequeryresultcachedgif.py +++ b/tests/test_inlinequeryresultcachedgif.py @@ -35,7 +35,7 @@ def inline_query_result_cached_gif(): reply_markup=TestInlineQueryResultCachedGif.reply_markup) -class TestInlineQueryResultCachedGif(object): +class TestInlineQueryResultCachedGif: id_ = 'id' type_ = 'gif' gif_file_id = 'gif file id' diff --git a/tests/test_inlinequeryresultcachedmpeg4gif.py b/tests/test_inlinequeryresultcachedmpeg4gif.py index 0a2ec6d95..95e4419d1 100644 --- a/tests/test_inlinequeryresultcachedmpeg4gif.py +++ b/tests/test_inlinequeryresultcachedmpeg4gif.py @@ -35,7 +35,7 @@ def inline_query_result_cached_mpeg4_gif(): reply_markup=TestInlineQueryResultCachedMpeg4Gif.reply_markup) -class TestInlineQueryResultCachedMpeg4Gif(object): +class TestInlineQueryResultCachedMpeg4Gif: id_ = 'id' type_ = 'mpeg4_gif' mpeg4_file_id = 'mpeg4 file id' diff --git a/tests/test_inlinequeryresultcachedphoto.py b/tests/test_inlinequeryresultcachedphoto.py index 398df63bb..5348b740f 100644 --- a/tests/test_inlinequeryresultcachedphoto.py +++ b/tests/test_inlinequeryresultcachedphoto.py @@ -36,7 +36,7 @@ def inline_query_result_cached_photo(): reply_markup=TestInlineQueryResultCachedPhoto.reply_markup) -class TestInlineQueryResultCachedPhoto(object): +class TestInlineQueryResultCachedPhoto: id_ = 'id' type_ = 'photo' photo_file_id = 'photo file id' diff --git a/tests/test_inlinequeryresultcachedsticker.py b/tests/test_inlinequeryresultcachedsticker.py index 7f1cefc0e..3993d9e05 100644 --- a/tests/test_inlinequeryresultcachedsticker.py +++ b/tests/test_inlinequeryresultcachedsticker.py @@ -33,7 +33,7 @@ def inline_query_result_cached_sticker(): reply_markup=TestInlineQueryResultCachedSticker.reply_markup) -class TestInlineQueryResultCachedSticker(object): +class TestInlineQueryResultCachedSticker: id_ = 'id' type_ = 'sticker' sticker_file_id = 'sticker file id' diff --git a/tests/test_inlinequeryresultcachedvideo.py b/tests/test_inlinequeryresultcachedvideo.py index 53c58f1b7..9c152643f 100644 --- a/tests/test_inlinequeryresultcachedvideo.py +++ b/tests/test_inlinequeryresultcachedvideo.py @@ -36,7 +36,7 @@ def inline_query_result_cached_video(): reply_markup=TestInlineQueryResultCachedVideo.reply_markup) -class TestInlineQueryResultCachedVideo(object): +class TestInlineQueryResultCachedVideo: id_ = 'id' type_ = 'video' video_file_id = 'video file id' diff --git a/tests/test_inlinequeryresultcachedvoice.py b/tests/test_inlinequeryresultcachedvoice.py index 1bb45b9c9..131c32d9c 100644 --- a/tests/test_inlinequeryresultcachedvoice.py +++ b/tests/test_inlinequeryresultcachedvoice.py @@ -35,7 +35,7 @@ def inline_query_result_cached_voice(): reply_markup=TestInlineQueryResultCachedVoice.reply_markup) -class TestInlineQueryResultCachedVoice(object): +class TestInlineQueryResultCachedVoice: id_ = 'id' type_ = 'voice' voice_file_id = 'voice file id' diff --git a/tests/test_inlinequeryresultcontact.py b/tests/test_inlinequeryresultcontact.py index ff5fd199e..68b0ab773 100644 --- a/tests/test_inlinequeryresultcontact.py +++ b/tests/test_inlinequeryresultcontact.py @@ -37,7 +37,7 @@ def inline_query_result_contact(): reply_markup=TestInlineQueryResultContact.reply_markup) -class TestInlineQueryResultContact(object): +class TestInlineQueryResultContact: id_ = 'id' type_ = 'contact' phone_number = 'phone_number' diff --git a/tests/test_inlinequeryresultdocument.py b/tests/test_inlinequeryresultdocument.py index 56ce5d2ca..b23e9653c 100644 --- a/tests/test_inlinequeryresultdocument.py +++ b/tests/test_inlinequeryresultdocument.py @@ -40,7 +40,7 @@ def inline_query_result_document(): reply_markup=TestInlineQueryResultDocument.reply_markup) -class TestInlineQueryResultDocument(object): +class TestInlineQueryResultDocument: id_ = 'id' type_ = 'document' document_url = 'document url' diff --git a/tests/test_inlinequeryresultgame.py b/tests/test_inlinequeryresultgame.py index ec9c56749..2e8a24611 100644 --- a/tests/test_inlinequeryresultgame.py +++ b/tests/test_inlinequeryresultgame.py @@ -30,7 +30,7 @@ def inline_query_result_game(): reply_markup=TestInlineQueryResultGame.reply_markup) -class TestInlineQueryResultGame(object): +class TestInlineQueryResultGame: id_ = 'id' type_ = 'game' game_short_name = 'game short name' diff --git a/tests/test_inlinequeryresultgif.py b/tests/test_inlinequeryresultgif.py index 1b5e0b316..e1b56e2e9 100644 --- a/tests/test_inlinequeryresultgif.py +++ b/tests/test_inlinequeryresultgif.py @@ -39,7 +39,7 @@ def inline_query_result_gif(): reply_markup=TestInlineQueryResultGif.reply_markup) -class TestInlineQueryResultGif(object): +class TestInlineQueryResultGif: id_ = 'id' type_ = 'gif' gif_url = 'gif url' diff --git a/tests/test_inlinequeryresultlocation.py b/tests/test_inlinequeryresultlocation.py index 9286e6876..860088a3f 100644 --- a/tests/test_inlinequeryresultlocation.py +++ b/tests/test_inlinequeryresultlocation.py @@ -38,7 +38,7 @@ def inline_query_result_location(): reply_markup=TestInlineQueryResultLocation.reply_markup) -class TestInlineQueryResultLocation(object): +class TestInlineQueryResultLocation: id_ = 'id' type_ = 'location' latitude = 0.0 diff --git a/tests/test_inlinequeryresultmpeg4gif.py b/tests/test_inlinequeryresultmpeg4gif.py index 93fb857c9..615551a64 100644 --- a/tests/test_inlinequeryresultmpeg4gif.py +++ b/tests/test_inlinequeryresultmpeg4gif.py @@ -39,7 +39,7 @@ def inline_query_result_mpeg4_gif(): reply_markup=TestInlineQueryResultMpeg4Gif.reply_markup) -class TestInlineQueryResultMpeg4Gif(object): +class TestInlineQueryResultMpeg4Gif: id_ = 'id' type_ = 'mpeg4_gif' mpeg4_url = 'mpeg4 url' diff --git a/tests/test_inlinequeryresultphoto.py b/tests/test_inlinequeryresultphoto.py index 6d6da313b..0f27c2a5c 100644 --- a/tests/test_inlinequeryresultphoto.py +++ b/tests/test_inlinequeryresultphoto.py @@ -39,7 +39,7 @@ def inline_query_result_photo(): reply_markup=TestInlineQueryResultPhoto.reply_markup) -class TestInlineQueryResultPhoto(object): +class TestInlineQueryResultPhoto: id_ = 'id' type_ = 'photo' photo_url = 'photo url' diff --git a/tests/test_inlinequeryresultvenue.py b/tests/test_inlinequeryresultvenue.py index 25f0a7ecd..ddb08a24d 100644 --- a/tests/test_inlinequeryresultvenue.py +++ b/tests/test_inlinequeryresultvenue.py @@ -40,7 +40,7 @@ def inline_query_result_venue(): reply_markup=TestInlineQueryResultVenue.reply_markup) -class TestInlineQueryResultVenue(object): +class TestInlineQueryResultVenue: id_ = 'id' type_ = 'venue' latitude = 'latitude' diff --git a/tests/test_inlinequeryresultvideo.py b/tests/test_inlinequeryresultvideo.py index 9a34d995a..464803b15 100644 --- a/tests/test_inlinequeryresultvideo.py +++ b/tests/test_inlinequeryresultvideo.py @@ -41,7 +41,7 @@ def inline_query_result_video(): reply_markup=TestInlineQueryResultVideo.reply_markup) -class TestInlineQueryResultVideo(object): +class TestInlineQueryResultVideo: id_ = 'id' type_ = 'video' video_url = 'video url' diff --git a/tests/test_inlinequeryresultvoice.py b/tests/test_inlinequeryresultvoice.py index 946244eef..5fa5f1eeb 100644 --- a/tests/test_inlinequeryresultvoice.py +++ b/tests/test_inlinequeryresultvoice.py @@ -37,7 +37,7 @@ def inline_query_result_voice(): reply_markup=TestInlineQueryResultVoice.reply_markup) -class TestInlineQueryResultVoice(object): +class TestInlineQueryResultVoice: id_ = 'id' type_ = 'voice' voice_url = 'voice url' diff --git a/tests/test_inputcontactmessagecontent.py b/tests/test_inputcontactmessagecontent.py index 47b91f01f..407b378c6 100644 --- a/tests/test_inputcontactmessagecontent.py +++ b/tests/test_inputcontactmessagecontent.py @@ -29,7 +29,7 @@ def input_contact_message_content(): last_name=TestInputContactMessageContent.last_name) -class TestInputContactMessageContent(object): +class TestInputContactMessageContent: phone_number = 'phone number' first_name = 'first name' last_name = 'last name' diff --git a/tests/test_inputfile.py b/tests/test_inputfile.py index 9bfb78e0d..e1fd01ceb 100644 --- a/tests/test_inputfile.py +++ b/tests/test_inputfile.py @@ -25,7 +25,7 @@ from io import BytesIO from telegram import InputFile -class TestInputFile(object): +class TestInputFile: png = os.path.join('tests', 'data', 'game.png') def test_subprocess_pipe(self): @@ -76,7 +76,7 @@ class TestInputFile(object): assert InputFile(open('tests/data/telegram', 'rb'), filename='blah.jpg').filename == 'blah.jpg' - class MockedFileobject(object): + class MockedFileobject: # A open(?, 'rb') without a .name def __init__(self, f): self.f = open(f, 'rb') diff --git a/tests/test_inputlocationmessagecontent.py b/tests/test_inputlocationmessagecontent.py index 65e02f209..915ed870a 100644 --- a/tests/test_inputlocationmessagecontent.py +++ b/tests/test_inputlocationmessagecontent.py @@ -29,7 +29,7 @@ def input_location_message_content(): live_period=TestInputLocationMessageContent.live_period) -class TestInputLocationMessageContent(object): +class TestInputLocationMessageContent: latitude = -23.691288 longitude = -46.788279 live_period = 80 diff --git a/tests/test_inputmedia.py b/tests/test_inputmedia.py index 4133e5341..3227845bd 100644 --- a/tests/test_inputmedia.py +++ b/tests/test_inputmedia.py @@ -83,7 +83,7 @@ def input_media_document(class_thumb_file): parse_mode=TestInputMediaDocument.parse_mode) -class TestInputMediaVideo(object): +class TestInputMediaVideo: type_ = "video" media = "NOTAREALFILEID" caption = "My Caption" @@ -133,7 +133,7 @@ class TestInputMediaVideo(object): assert input_media_video.caption == "test 3" -class TestInputMediaPhoto(object): +class TestInputMediaPhoto: type_ = "photo" media = "NOTAREALFILEID" caption = "My Caption" @@ -167,7 +167,7 @@ class TestInputMediaPhoto(object): assert input_media_photo.caption == "test 2" -class TestInputMediaAnimation(object): +class TestInputMediaAnimation: type_ = "animation" media = "NOTAREALFILEID" caption = "My Caption" @@ -208,7 +208,7 @@ class TestInputMediaAnimation(object): assert input_media_animation.caption == "test 2" -class TestInputMediaAudio(object): +class TestInputMediaAudio: type_ = "audio" media = "NOTAREALFILEID" caption = "My Caption" @@ -255,7 +255,7 @@ class TestInputMediaAudio(object): assert input_media_audio.caption == "test 3" -class TestInputMediaDocument(object): +class TestInputMediaDocument: type_ = "document" media = "NOTAREALFILEID" caption = "My Caption" @@ -296,7 +296,7 @@ def media_group(photo, thumb): # noqa: F811 InputMediaPhoto(thumb, caption='photo 2', parse_mode='HTML')] -class TestSendMediaGroup(object): +class TestSendMediaGroup: @flaky(3, 1) @pytest.mark.timeout(10) def test_send_media_group_photo(self, bot, chat_id, media_group): diff --git a/tests/test_inputtextmessagecontent.py b/tests/test_inputtextmessagecontent.py index 832b48a7e..54a3739c6 100644 --- a/tests/test_inputtextmessagecontent.py +++ b/tests/test_inputtextmessagecontent.py @@ -30,7 +30,7 @@ def input_text_message_content(): disable_web_page_preview=TestInputTextMessageContent.disable_web_page_preview) -class TestInputTextMessageContent(object): +class TestInputTextMessageContent: message_text = '*message text*' parse_mode = ParseMode.MARKDOWN disable_web_page_preview = True diff --git a/tests/test_inputvenuemessagecontent.py b/tests/test_inputvenuemessagecontent.py index 844bd817e..013ea2729 100644 --- a/tests/test_inputvenuemessagecontent.py +++ b/tests/test_inputvenuemessagecontent.py @@ -32,7 +32,7 @@ def input_venue_message_content(): foursquare_type=TestInputVenueMessageContent.foursquare_type) -class TestInputVenueMessageContent(object): +class TestInputVenueMessageContent: latitude = 1. longitude = 2. title = 'title' diff --git a/tests/test_invoice.py b/tests/test_invoice.py index 16096405f..fb13d4424 100644 --- a/tests/test_invoice.py +++ b/tests/test_invoice.py @@ -29,7 +29,7 @@ def invoice(): TestInvoice.currency, TestInvoice.total_amount) -class TestInvoice(object): +class TestInvoice: payload = 'payload' prices = [LabeledPrice('Fish', 100), LabeledPrice('Fish Tax', 1000)] provider_data = """{"test":"test"}""" diff --git a/tests/test_jobqueue.py b/tests/test_jobqueue.py index 1d96be7a8..24328d429 100644 --- a/tests/test_jobqueue.py +++ b/tests/test_jobqueue.py @@ -19,7 +19,6 @@ import calendar import datetime as dtm import os -import sys import time from queue import Queue from time import sleep @@ -42,7 +41,7 @@ def job_queue(bot, _dp): @pytest.mark.skipif(os.getenv('GITHUB_ACTIONS', False) and os.name == 'nt', reason="On windows precise timings are not accurate.") @flaky(10, 1) # Timings aren't quite perfect -class TestJobQueue(object): +class TestJobQueue: result = 0 job_time = 0 @@ -384,7 +383,6 @@ class TestJobQueue(object): assert job_queue.get_jobs_by_name('name1') == (job1, job2) assert job_queue.get_jobs_by_name('name2') == (job3,) - @pytest.mark.skipif(sys.version_info < (3, 0), reason='pytest fails this for no reason') def test_bot_in_init_deprecation(self, bot): with pytest.warns(TelegramDeprecationWarning): JobQueue(bot) diff --git a/tests/test_keyboardbutton.py b/tests/test_keyboardbutton.py index e3da6dac2..516abd129 100644 --- a/tests/test_keyboardbutton.py +++ b/tests/test_keyboardbutton.py @@ -31,7 +31,7 @@ def keyboard_button(): request_poll=TestKeyboardButton.request_poll) -class TestKeyboardButton(object): +class TestKeyboardButton: text = 'text' request_location = True request_contact = True diff --git a/tests/test_keyboardbuttonpolltype.py b/tests/test_keyboardbuttonpolltype.py index 93394ae61..114a4f2b1 100644 --- a/tests/test_keyboardbuttonpolltype.py +++ b/tests/test_keyboardbuttonpolltype.py @@ -26,7 +26,7 @@ def keyboard_button_poll_type(): return KeyboardButtonPollType(TestKeyboardButtonPollType.type) -class TestKeyboardButtonPollType(object): +class TestKeyboardButtonPollType: type = Poll.QUIZ def test_to_dict(self, keyboard_button_poll_type): diff --git a/tests/test_labeledprice.py b/tests/test_labeledprice.py index 325fa9063..752ae66d8 100644 --- a/tests/test_labeledprice.py +++ b/tests/test_labeledprice.py @@ -27,7 +27,7 @@ def labeled_price(): return LabeledPrice(TestLabeledPrice.label, TestLabeledPrice.amount) -class TestLabeledPrice(object): +class TestLabeledPrice: label = 'label' amount = 100 diff --git a/tests/test_location.py b/tests/test_location.py index 0637101c4..418ebe50d 100644 --- a/tests/test_location.py +++ b/tests/test_location.py @@ -29,7 +29,7 @@ def location(): return Location(latitude=TestLocation.latitude, longitude=TestLocation.longitude) -class TestLocation(object): +class TestLocation: latitude = -23.691288 longitude = -46.788279 diff --git a/tests/test_loginurl.py b/tests/test_loginurl.py index c63bf0fe8..dd0770d68 100644 --- a/tests/test_loginurl.py +++ b/tests/test_loginurl.py @@ -29,7 +29,7 @@ def login_url(): request_write_access=TestLoginUrl.request_write_access) -class TestLoginUrl(object): +class TestLoginUrl: url = "http://www.google.com" forward_text = "Send me forward!" bot_username = "botname" diff --git a/tests/test_message.py b/tests/test_message.py index ef270431f..8feb55d3c 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -116,7 +116,7 @@ def message_params(bot, request): chat=TestMessage.chat, bot=bot, **request.param) -class TestMessage(object): +class TestMessage: id_ = 1 from_user = User(2, 'testuser', False) date = datetime.utcnow() @@ -137,7 +137,7 @@ class TestMessage(object): {'length': 7, 'offset': 16, 'type': 'italic'}, {'length': 6, 'offset': 25, 'type': 'code'}, {'length': 5, 'offset': 33, 'type': 'text_link', - 'url': 'http://github.com/abc\)def'}, + 'url': r'http://github.com/abc\)def'}, {'length': 12, 'offset': 40, 'type': 'text_mention', 'user': User(123456789, 'mentioned user', False)}, {'length': 5, 'offset': 57, 'type': 'pre'}, @@ -146,7 +146,7 @@ class TestMessage(object): {'length': 24, 'offset': 91, 'type': 'bold'}, {'length': 4, 'offset': 101, 'type': 'strikethrough'}, {'length': 10, 'offset': 124, 'type': 'pre', 'language': 'python'}] - test_text_v2 = ('Test for Test for <bold, ita_lic, \`code,' - ' links, ' + test_html_string = ('Test for <bold, ita_lic, ' + r'\`code, ' + r'links, ' 'text-mention and ' - '
`\pre
. http://google.com ' + r'
`\pre
. http://google.com ' 'and bold nested in strk nested in italic. ' '
Python pre
.') text_html = self.test_message_v2.text_html @@ -228,28 +229,30 @@ class TestMessage(object): assert message.text_html is None def test_text_html_urled(self): - test_html_string = ('Test for <bold, ita_lic, \`code,' - ' links, ' + test_html_string = ('Test for <bold, ita_lic, ' + r'\`code, ' + r'links, ' 'text-mention and ' - '
`\pre
. http://google.com ' + r'
`\pre
. http://google.com ' 'and bold nested in strk nested in italic. ' '
Python pre
.') text_html = self.test_message_v2.text_html_urled assert text_html == test_html_string def test_text_markdown_simple(self): - test_md_string = ('Test for <*bold*, _ita_\__lic_, `code`, [links](http://github.com/ab_),' - ' [text-mention](tg://user?id=123456789) and ```python\npre```. ' - 'http://google.com/ab\_') + test_md_string = (r'Test for <*bold*, _ita_\__lic_, `code`, ' + '[links](http://github.com/ab_), ' + '[text-mention](tg://user?id=123456789) and ```python\npre```. ' + r'http://google.com/ab\_') text_markdown = self.test_message.text_markdown assert text_markdown == test_md_string def test_text_markdown_v2_simple(self): test_md_string = (r'__Test__ for <*bold*, _ita\_lic_, `\\\`code`, ' - '[links](http://github.com/abc\\\\\)def), ' - '[text\-mention](tg://user?id=123456789) and ```\`\\\\pre```\. ' - 'http://google\.com and _bold *nested in ~strk~ nested in* italic_\. ' - '```python\nPython pre```\.') + '[links](http://github.com/abc\\\\\\)def), ' + '[text\\-mention](tg://user?id=123456789) and ```\\`\\\\pre```\\. ' + r'http://google\.com and _bold *nested in ~strk~ nested in* italic_\. ' + '```python\nPython pre```\\.') text_markdown = self.test_message_v2.text_markdown_v2 assert text_markdown == test_md_string @@ -277,18 +280,19 @@ class TestMessage(object): assert message.text_markdown_v2 is None def test_text_markdown_urled(self): - test_md_string = ('Test for <*bold*, _ita_\__lic_, `code`, [links](http://github.com/ab_),' - ' [text-mention](tg://user?id=123456789) and ```python\npre```. ' + test_md_string = (r'Test for <*bold*, _ita_\__lic_, `code`, ' + '[links](http://github.com/ab_), ' + '[text-mention](tg://user?id=123456789) and ```python\npre```. ' '[http://google.com/ab_](http://google.com/ab_)') text_markdown = self.test_message.text_markdown_urled assert text_markdown == test_md_string def test_text_markdown_v2_urled(self): test_md_string = (r'__Test__ for <*bold*, _ita\_lic_, `\\\`code`, ' - '[links](http://github.com/abc\\\\\)def), ' - '[text\-mention](tg://user?id=123456789) and ```\`\\\\pre```\. ' - '[http://google\.com](http://google.com) and _bold *nested in ~strk~ ' - 'nested in* italic_\. ```python\nPython pre```\.') + '[links](http://github.com/abc\\\\\\)def), ' + '[text\\-mention](tg://user?id=123456789) and ```\\`\\\\pre```\\. ' + r'[http://google\.com](http://google.com) and _bold *nested in ~strk~ ' + 'nested in* italic_\\. ```python\nPython pre```\\.') text_markdown = self.test_message_v2.text_markdown_v2_urled assert text_markdown == test_md_string @@ -309,10 +313,11 @@ class TestMessage(object): assert expected == message.text_markdown def test_caption_html_simple(self): - test_html_string = ('Test for <bold, ita_lic, \`code,' - ' links, ' + test_html_string = ('Test for <bold, ita_lic, ' + r'\`code, ' + r'links, ' 'text-mention and ' - '
`\pre
. http://google.com ' + r'
`\pre
. http://google.com ' 'and bold nested in strk nested in italic. ' '
Python pre
.') caption_html = self.test_message_v2.caption_html @@ -324,28 +329,30 @@ class TestMessage(object): assert message.caption_html is None def test_caption_html_urled(self): - test_html_string = ('Test for <bold, ita_lic, \`code,' - ' links, ' + test_html_string = ('Test for <bold, ita_lic, ' + r'\`code, ' + r'links, ' 'text-mention and ' - '
`\pre
. http://google.com ' + r'
`\pre
. http://google.com ' 'and bold nested in strk nested in italic. ' '
Python pre
.') caption_html = self.test_message_v2.caption_html_urled assert caption_html == test_html_string def test_caption_markdown_simple(self): - test_md_string = ('Test for <*bold*, _ita_\__lic_, `code`, [links](http://github.com/ab_),' - ' [text-mention](tg://user?id=123456789) and ```python\npre```. ' - 'http://google.com/ab\_') + test_md_string = (r'Test for <*bold*, _ita_\__lic_, `code`, ' + '[links](http://github.com/ab_), ' + '[text-mention](tg://user?id=123456789) and ```python\npre```. ' + r'http://google.com/ab\_') caption_markdown = self.test_message.caption_markdown assert caption_markdown == test_md_string def test_caption_markdown_v2_simple(self): test_md_string = (r'__Test__ for <*bold*, _ita\_lic_, `\\\`code`, ' '[links](http://github.com/abc\\\\\\)def), ' - '[text\-mention](tg://user?id=123456789) and ```\`\\\\pre```\. ' - 'http://google\.com and _bold *nested in ~strk~ nested in* italic_\. ' - '```python\nPython pre```\.') + '[text\\-mention](tg://user?id=123456789) and ```\\`\\\\pre```\\. ' + r'http://google\.com and _bold *nested in ~strk~ nested in* italic_\. ' + '```python\nPython pre```\\.') caption_markdown = self.test_message_v2.caption_markdown_v2 assert caption_markdown == test_md_string @@ -356,8 +363,9 @@ class TestMessage(object): assert message.caption_markdown_v2 is None def test_caption_markdown_urled(self): - test_md_string = ('Test for <*bold*, _ita_\__lic_, `code`, [links](http://github.com/ab_),' - ' [text-mention](tg://user?id=123456789) and ```python\npre```. ' + test_md_string = (r'Test for <*bold*, _ita_\__lic_, `code`, ' + '[links](http://github.com/ab_), ' + '[text-mention](tg://user?id=123456789) and ```python\npre```. ' '[http://google.com/ab_](http://google.com/ab_)') caption_markdown = self.test_message.caption_markdown_urled assert caption_markdown == test_md_string @@ -365,9 +373,9 @@ class TestMessage(object): def test_caption_markdown_v2_urled(self): test_md_string = (r'__Test__ for <*bold*, _ita\_lic_, `\\\`code`, ' '[links](http://github.com/abc\\\\\\)def), ' - '[text\-mention](tg://user?id=123456789) and ```\`\\\\pre```\. ' - '[http://google\.com](http://google.com) and _bold *nested in ~strk~ ' - 'nested in* italic_\. ```python\nPython pre```\.') + '[text\\-mention](tg://user?id=123456789) and ```\\`\\\\pre```\\. ' + r'[http://google\.com](http://google.com) and _bold *nested in ~strk~ ' + 'nested in* italic_\\. ```python\nPython pre```\\.') caption_markdown = self.test_message_v2.caption_markdown_v2_urled assert caption_markdown == test_md_string @@ -453,9 +461,10 @@ class TestMessage(object): assert message.reply_text('test', reply_to_message_id=message.message_id, quote=True) def test_reply_markdown(self, monkeypatch, message): - test_md_string = ('Test for <*bold*, _ita_\__lic_, `code`, [links](http://github.com/ab_),' - ' [text-mention](tg://user?id=123456789) and ```python\npre```. ' - 'http://google.com/ab\_') + test_md_string = (r'Test for <*bold*, _ita_\__lic_, `code`, ' + '[links](http://github.com/ab_), ' + '[text-mention](tg://user?id=123456789) and ```python\npre```. ' + r'http://google.com/ab\_') def test(*args, **kwargs): cid = args[0] == message.chat_id @@ -479,10 +488,10 @@ class TestMessage(object): def test_reply_markdown_v2(self, monkeypatch, message): test_md_string = (r'__Test__ for <*bold*, _ita\_lic_, `\\\`code`, ' - '[links](http://github.com/abc\\\\\)def), ' - '[text\-mention](tg://user?id=123456789) and ```\`\\\\pre```\. ' - 'http://google\.com and _bold *nested in ~strk~ nested in* italic_\. ' - '```python\nPython pre```\.') + '[links](http://github.com/abc\\\\\\)def), ' + '[text\\-mention](tg://user?id=123456789) and ```\\`\\\\pre```\\. ' + r'http://google\.com and _bold *nested in ~strk~ nested in* italic_\. ' + '```python\nPython pre```\\.') def test(*args, **kwargs): cid = args[0] == message.chat_id @@ -505,10 +514,11 @@ class TestMessage(object): quote=True) def test_reply_html(self, monkeypatch, message): - test_html_string = ('Test for <bold, ita_lic, \`code,' - ' links, ' + test_html_string = ('Test for <bold, ita_lic, ' + r'\`code, ' + r'links, ' 'text-mention and ' - '
`\pre
. http://google.com ' + r'
`\pre
. http://google.com ' 'and bold nested in strk nested in italic. ' '
Python pre
.') diff --git a/tests/test_messageentity.py b/tests/test_messageentity.py index 9ecc68e62..fcf38e861 100644 --- a/tests/test_messageentity.py +++ b/tests/test_messageentity.py @@ -38,7 +38,7 @@ def message_entity(request): return MessageEntity(type, 1, 3, url=url, user=user, language=language) -class TestMessageEntity(object): +class TestMessageEntity: type_ = 'url' offset = 1 length = 2 diff --git a/tests/test_messagehandler.py b/tests/test_messagehandler.py index 7e2f5fb63..e44d71c4f 100644 --- a/tests/test_messagehandler.py +++ b/tests/test_messagehandler.py @@ -51,7 +51,7 @@ def message(bot): return Message(1, User(1, '', False), None, Chat(1, ''), bot=bot) -class TestMessageHandler(object): +class TestMessageHandler: test_flag = False SRE_TYPE = type(re.match("", "")) diff --git a/tests/test_messagequeue.py b/tests/test_messagequeue.py index 80ddbaf3a..9ffd373e0 100644 --- a/tests/test_messagequeue.py +++ b/tests/test_messagequeue.py @@ -18,7 +18,7 @@ # along with this program. If not, see [http://www.gnu.org/licenses/]. import os -from time import sleep +from time import sleep, perf_counter import pytest @@ -27,7 +27,7 @@ import telegram.ext.messagequeue as mq @pytest.mark.skipif(os.getenv('GITHUB_ACTIONS', False) and os.name == 'nt', reason="On windows precise timings are not accurate.") -class TestDelayQueue(object): +class TestDelayQueue: N = 128 burst_limit = 30 time_limit_ms = 1000 @@ -35,7 +35,7 @@ class TestDelayQueue(object): testtimes = [] def call(self): - self.testtimes.append(mq.curtime()) + self.testtimes.append(perf_counter()) def test_delayqueue_limits(self): dsp = mq.DelayQueue(burst_limit=self.burst_limit, time_limit_ms=self.time_limit_ms, @@ -45,10 +45,10 @@ class TestDelayQueue(object): for _ in range(self.N): dsp(self.call) - starttime = mq.curtime() + starttime = perf_counter() # wait up to 20 sec more than needed app_endtime = ((self.N * self.burst_limit / (1000 * self.time_limit_ms)) + starttime + 20) - while not dsp._queue.empty() and mq.curtime() < app_endtime: + while not dsp._queue.empty() and perf_counter() < app_endtime: sleep(1) assert dsp._queue.empty() is True # check loop exit condition diff --git a/tests/test_orderinfo.py b/tests/test_orderinfo.py index 70fc20244..2eb822e3d 100644 --- a/tests/test_orderinfo.py +++ b/tests/test_orderinfo.py @@ -28,7 +28,7 @@ def order_info(): TestOrderInfo.email, TestOrderInfo.shipping_address) -class TestOrderInfo(object): +class TestOrderInfo: name = 'name' phone_number = 'phone_number' email = 'email' diff --git a/tests/test_parsemode.py b/tests/test_parsemode.py index 92fc52fbe..3137fb235 100644 --- a/tests/test_parsemode.py +++ b/tests/test_parsemode.py @@ -22,7 +22,7 @@ from flaky import flaky from telegram import ParseMode -class TestParseMode(object): +class TestParseMode: markdown_text = '*bold* _italic_ [link](http://google.com) [name](tg://user?id=123456789).' html_text = ('bold italic link ' 'name.') diff --git a/tests/test_passport.py b/tests/test_passport.py index 2d52c5ca3..aa553c888 100644 --- a/tests/test_passport.py +++ b/tests/test_passport.py @@ -145,7 +145,7 @@ def passport_data(bot): return PassportData.de_json(RAW_PASSPORT_DATA, bot=bot) -class TestPassport(object): +class TestPassport: driver_license_selfie_file_id = 'DgADBAADEQQAAkopgFNr6oi-wISRtAI' driver_license_selfie_file_unique_id = 'd4e390cca57b4da5a65322b304762a12' driver_license_front_side_file_id = 'DgADBAADxwMAApnQgVPK2-ckL2eXVAI' diff --git a/tests/test_passportelementerrordatafield.py b/tests/test_passportelementerrordatafield.py index 11ec30136..247123dd5 100644 --- a/tests/test_passportelementerrordatafield.py +++ b/tests/test_passportelementerrordatafield.py @@ -30,7 +30,7 @@ def passport_element_error_data_field(): TestPassportElementErrorDataField.message) -class TestPassportElementErrorDataField(object): +class TestPassportElementErrorDataField: source = 'data' type_ = 'test_type' field_name = 'test_field' diff --git a/tests/test_passportelementerrorfile.py b/tests/test_passportelementerrorfile.py index 8bedc046c..821cc4811 100644 --- a/tests/test_passportelementerrorfile.py +++ b/tests/test_passportelementerrorfile.py @@ -29,7 +29,7 @@ def passport_element_error_file(): TestPassportElementErrorFile.message) -class TestPassportElementErrorFile(object): +class TestPassportElementErrorFile: source = 'file' type_ = 'test_type' file_hash = 'file_hash' diff --git a/tests/test_passportelementerrorfiles.py b/tests/test_passportelementerrorfiles.py index b519ce06b..6c73ae737 100644 --- a/tests/test_passportelementerrorfiles.py +++ b/tests/test_passportelementerrorfiles.py @@ -29,7 +29,7 @@ def passport_element_error_files(): TestPassportElementErrorFiles.message) -class TestPassportElementErrorFiles(object): +class TestPassportElementErrorFiles: source = 'files' type_ = 'test_type' file_hashes = ['hash1', 'hash2'] diff --git a/tests/test_passportelementerrorfrontside.py b/tests/test_passportelementerrorfrontside.py index ebca892f3..c2375e0fa 100644 --- a/tests/test_passportelementerrorfrontside.py +++ b/tests/test_passportelementerrorfrontside.py @@ -29,7 +29,7 @@ def passport_element_error_front_side(): TestPassportElementErrorFrontSide.message) -class TestPassportElementErrorFrontSide(object): +class TestPassportElementErrorFrontSide: source = 'front_side' type_ = 'test_type' file_hash = 'file_hash' diff --git a/tests/test_passportelementerrorreverseside.py b/tests/test_passportelementerrorreverseside.py index ca568afb3..1d79dfcd9 100644 --- a/tests/test_passportelementerrorreverseside.py +++ b/tests/test_passportelementerrorreverseside.py @@ -29,7 +29,7 @@ def passport_element_error_reverse_side(): TestPassportElementErrorReverseSide.message) -class TestPassportElementErrorReverseSide(object): +class TestPassportElementErrorReverseSide: source = 'reverse_side' type_ = 'test_type' file_hash = 'file_hash' diff --git a/tests/test_passportelementerrorselfie.py b/tests/test_passportelementerrorselfie.py index 1d3ccb75c..7cae0dad1 100644 --- a/tests/test_passportelementerrorselfie.py +++ b/tests/test_passportelementerrorselfie.py @@ -29,7 +29,7 @@ def passport_element_error_selfie(): TestPassportElementErrorSelfie.message) -class TestPassportElementErrorSelfie(object): +class TestPassportElementErrorSelfie: source = 'selfie' type_ = 'test_type' file_hash = 'file_hash' diff --git a/tests/test_passportelementerrortranslationfile.py b/tests/test_passportelementerrortranslationfile.py index c3f9f3d6e..3703e7bf2 100644 --- a/tests/test_passportelementerrortranslationfile.py +++ b/tests/test_passportelementerrortranslationfile.py @@ -29,7 +29,7 @@ def passport_element_error_translation_file(): TestPassportElementErrorTranslationFile.message) -class TestPassportElementErrorTranslationFile(object): +class TestPassportElementErrorTranslationFile: source = 'translation_file' type_ = 'test_type' file_hash = 'file_hash' diff --git a/tests/test_passportelementerrortranslationfiles.py b/tests/test_passportelementerrortranslationfiles.py index 5c9139d6a..0fcf0709a 100644 --- a/tests/test_passportelementerrortranslationfiles.py +++ b/tests/test_passportelementerrortranslationfiles.py @@ -30,7 +30,7 @@ def passport_element_error_translation_files(): TestPassportElementErrorTranslationFiles.message) -class TestPassportElementErrorTranslationFiles(object): +class TestPassportElementErrorTranslationFiles: source = 'translation_files' type_ = 'test_type' file_hashes = ['hash1', 'hash2'] diff --git a/tests/test_passportelementerrorunspecified.py b/tests/test_passportelementerrorunspecified.py index 9e9ef7d6c..74e99681e 100644 --- a/tests/test_passportelementerrorunspecified.py +++ b/tests/test_passportelementerrorunspecified.py @@ -29,7 +29,7 @@ def passport_element_error_unspecified(): TestPassportElementErrorUnspecified.message) -class TestPassportElementErrorUnspecified(object): +class TestPassportElementErrorUnspecified: source = 'unspecified' type_ = 'test_type' element_hash = 'element_hash' diff --git a/tests/test_passportfile.py b/tests/test_passportfile.py index 1d338c3fb..347892a34 100644 --- a/tests/test_passportfile.py +++ b/tests/test_passportfile.py @@ -30,7 +30,7 @@ def passport_file(): file_date=TestPassportFile.file_date) -class TestPassportFile(object): +class TestPassportFile: file_id = 'data' file_unique_id = 'adc3145fd2e84d95b64d68eaa22aa33e' file_size = 50 diff --git a/tests/test_persistence.py b/tests/test_persistence.py index 8c307e51e..eb63f7d7c 100644 --- a/tests/test_persistence.py +++ b/tests/test_persistence.py @@ -121,7 +121,7 @@ def job_queue(bot): jq.stop() -class TestBasePersistence(object): +class TestBasePersistence: def test_creation(self, base_persistence): assert base_persistence.store_chat_data @@ -287,7 +287,7 @@ class TestBasePersistence(object): dp.persistence = base_persistence - class MyUpdate(object): + class MyUpdate: pass dp.add_handler(TypeHandler(MyUpdate, lambda *_: None)) @@ -385,7 +385,7 @@ def update(bot): return Update(0, message=message) -class TestPickelPersistence(object): +class TestPickelPersistence: def test_no_files_present_multi_file(self, pickle_persistence): assert pickle_persistence.get_user_data() == defaultdict(dict) assert pickle_persistence.get_user_data() == defaultdict(dict) @@ -984,7 +984,7 @@ def conversations_json(conversations): {"[123, 321]": 1, "[890, 890]": 2}}""" -class TestDictPersistence(object): +class TestDictPersistence: def test_no_json_given(self): dict_persistence = DictPersistence() assert dict_persistence.get_user_data() == defaultdict(dict) diff --git a/tests/test_photo.py b/tests/test_photo.py index 7ebf59b89..01aa822a4 100644 --- a/tests/test_photo.py +++ b/tests/test_photo.py @@ -53,7 +53,7 @@ def photo(_photo): return _photo[1] -class TestPhoto(object): +class TestPhoto: width = 800 height = 800 caption = u'PhotoTest - *Caption*' diff --git a/tests/test_poll.py b/tests/test_poll.py index bc1c05420..bbc9f930d 100644 --- a/tests/test_poll.py +++ b/tests/test_poll.py @@ -30,7 +30,7 @@ def poll_option(): voter_count=TestPollOption.voter_count) -class TestPollOption(object): +class TestPollOption: text = "test option" voter_count = 3 @@ -58,7 +58,7 @@ def poll_answer(): option_ids=TestPollAnswer.poll_id) -class TestPollAnswer(object): +class TestPollAnswer: poll_id = 'id' user = User(1, '', False) option_ids = [2] @@ -101,7 +101,7 @@ def poll(): ) -class TestPoll(object): +class TestPoll: id_ = 'id' question = 'Test?' options = [PollOption('test', 10), PollOption('test2', 11)] diff --git a/tests/test_pollanswerhandler.py b/tests/test_pollanswerhandler.py index d16c403fb..09b839291 100644 --- a/tests/test_pollanswerhandler.py +++ b/tests/test_pollanswerhandler.py @@ -53,7 +53,7 @@ def poll_answer(bot): return Update(0, poll_answer=PollAnswer(1, User(2, 'test user', False), [0, 1])) -class TestPollAnswerHandler(object): +class TestPollAnswerHandler: test_flag = False @pytest.fixture(autouse=True) diff --git a/tests/test_pollhandler.py b/tests/test_pollhandler.py index 2c3012756..6c09dd47d 100644 --- a/tests/test_pollhandler.py +++ b/tests/test_pollhandler.py @@ -54,7 +54,7 @@ def poll(bot): False, Poll.REGULAR, True)) -class TestPollHandler(object): +class TestPollHandler: test_flag = False @pytest.fixture(autouse=True) diff --git a/tests/test_precheckoutquery.py b/tests/test_precheckoutquery.py index d167c66e2..b3ceb4140 100644 --- a/tests/test_precheckoutquery.py +++ b/tests/test_precheckoutquery.py @@ -34,7 +34,7 @@ def pre_checkout_query(bot): bot=bot) -class TestPreCheckoutQuery(object): +class TestPreCheckoutQuery: id_ = 5 invoice_payload = 'invoice_payload' shipping_option_id = 'shipping_option_id' diff --git a/tests/test_precheckoutqueryhandler.py b/tests/test_precheckoutqueryhandler.py index 72dad97dc..2e2e922a2 100644 --- a/tests/test_precheckoutqueryhandler.py +++ b/tests/test_precheckoutqueryhandler.py @@ -55,7 +55,7 @@ def pre_checkout_query(): 'EUR', 223, 'invoice_payload')) -class TestPreCheckoutQueryHandler(object): +class TestPreCheckoutQueryHandler: test_flag = False @pytest.fixture(autouse=True) diff --git a/tests/test_regexhandler.py b/tests/test_regexhandler.py index ae6b614e5..5b7a75eb2 100644 --- a/tests/test_regexhandler.py +++ b/tests/test_regexhandler.py @@ -50,7 +50,7 @@ def message(bot): return Message(1, User(1, '', False), None, Chat(1, ''), text='test message', bot=bot) -class TestRegexHandler(object): +class TestRegexHandler: test_flag = False @pytest.fixture(autouse=True) diff --git a/tests/test_replykeyboardmarkup.py b/tests/test_replykeyboardmarkup.py index dd63a85c4..fbd28cb61 100644 --- a/tests/test_replykeyboardmarkup.py +++ b/tests/test_replykeyboardmarkup.py @@ -31,7 +31,7 @@ def reply_keyboard_markup(): selective=TestReplyKeyboardMarkup.selective) -class TestReplyKeyboardMarkup(object): +class TestReplyKeyboardMarkup: keyboard = [[KeyboardButton('button1'), KeyboardButton('button2')]] resize_keyboard = True one_time_keyboard = True diff --git a/tests/test_replykeyboardremove.py b/tests/test_replykeyboardremove.py index 40697e18c..b1d9afc52 100644 --- a/tests/test_replykeyboardremove.py +++ b/tests/test_replykeyboardremove.py @@ -28,7 +28,7 @@ def reply_keyboard_remove(): return ReplyKeyboardRemove(selective=TestReplyKeyboardRemove.selective) -class TestReplyKeyboardRemove(object): +class TestReplyKeyboardRemove: remove_keyboard = True selective = True diff --git a/tests/test_shippingaddress.py b/tests/test_shippingaddress.py index 3558b5c86..54d6aea7a 100644 --- a/tests/test_shippingaddress.py +++ b/tests/test_shippingaddress.py @@ -32,7 +32,7 @@ def shipping_address(): TestShippingAddress.post_code) -class TestShippingAddress(object): +class TestShippingAddress: country_code = 'GB' state = 'state' city = 'London' diff --git a/tests/test_shippingoption.py b/tests/test_shippingoption.py index b009a8e8c..0d966120d 100644 --- a/tests/test_shippingoption.py +++ b/tests/test_shippingoption.py @@ -28,7 +28,7 @@ def shipping_option(): TestShippingOption.prices) -class TestShippingOption(object): +class TestShippingOption: id_ = 'id' title = 'title' prices = [ diff --git a/tests/test_shippingquery.py b/tests/test_shippingquery.py index 88ef057a1..cd0a71a90 100644 --- a/tests/test_shippingquery.py +++ b/tests/test_shippingquery.py @@ -31,7 +31,7 @@ def shipping_query(bot): bot=bot) -class TestShippingQuery(object): +class TestShippingQuery: id_ = 5 invoice_payload = 'invoice_payload' from_user = User(0, '', False) diff --git a/tests/test_shippingqueryhandler.py b/tests/test_shippingqueryhandler.py index 65870c76a..676c7b603 100644 --- a/tests/test_shippingqueryhandler.py +++ b/tests/test_shippingqueryhandler.py @@ -56,7 +56,7 @@ def shiping_query(): 'steer_1', '', 'post_code'))) -class TestShippingQueryHandler(object): +class TestShippingQueryHandler: test_flag = False @pytest.fixture(autouse=True) diff --git a/tests/test_sticker.py b/tests/test_sticker.py index a4f199c97..d9289cbd1 100644 --- a/tests/test_sticker.py +++ b/tests/test_sticker.py @@ -22,7 +22,6 @@ from time import sleep import pytest from flaky import flaky -from future.utils import PY2 from telegram import Sticker, PhotoSize, TelegramError, StickerSet, Audio, MaskPosition from telegram.error import BadRequest @@ -54,7 +53,7 @@ def animated_sticker(bot, chat_id): return bot.send_sticker(chat_id, sticker=f, timeout=50).sticker -class TestSticker(object): +class TestSticker: # sticker_file_url = 'https://python-telegram-bot.org/static/testfiles/telegram.webp' # Serving sticker from gh since our server sends wrong content_type sticker_file_url = ('https://github.com/python-telegram-bot/python-telegram-bot/blob/master' @@ -145,10 +144,7 @@ class TestSticker(object): server_file_id = 'CAADAQADHAADyIsGAAFZfq1bphjqlgI' message = bot.send_sticker(chat_id=chat_id, sticker=server_file_id) sticker = message.sticker - if PY2: - assert sticker.emoji == self.emoji.decode('utf-8') - else: - assert sticker.emoji == self.emoji + assert sticker.emoji == self.emoji @flaky(3, 1) @pytest.mark.timeout(10) @@ -288,7 +284,7 @@ def sticker_set_thumb_file(): f.close() -class TestStickerSet(object): +class TestStickerSet: title = 'Test stickers' is_animated = True contains_masks = False @@ -425,7 +421,7 @@ def mask_position(): TestMaskPosition.scale) -class TestMaskPosition(object): +class TestMaskPosition: point = MaskPosition.EYES x_shift = -1 y_shift = 1 diff --git a/tests/test_stringcommandhandler.py b/tests/test_stringcommandhandler.py index 319b2d285..5bd877949 100644 --- a/tests/test_stringcommandhandler.py +++ b/tests/test_stringcommandhandler.py @@ -49,7 +49,7 @@ def false_update(request): return Update(update_id=1, **request.param) -class TestStringCommandHandler(object): +class TestStringCommandHandler: test_flag = False @pytest.fixture(autouse=True) diff --git a/tests/test_stringregexhandler.py b/tests/test_stringregexhandler.py index c198710b9..cd6fb23fd 100644 --- a/tests/test_stringregexhandler.py +++ b/tests/test_stringregexhandler.py @@ -49,7 +49,7 @@ def false_update(request): return Update(update_id=1, **request.param) -class TestStringRegexHandler(object): +class TestStringRegexHandler: test_flag = False @pytest.fixture(autouse=True) diff --git a/tests/test_successfulpayment.py b/tests/test_successfulpayment.py index 2c44fc456..6c2a2d099 100644 --- a/tests/test_successfulpayment.py +++ b/tests/test_successfulpayment.py @@ -33,7 +33,7 @@ def successful_payment(): order_info=TestSuccessfulPayment.order_info) -class TestSuccessfulPayment(object): +class TestSuccessfulPayment: invoice_payload = 'invoice_payload' shipping_option_id = 'shipping_option_id' currency = 'EUR' diff --git a/tests/test_telegramobject.py b/tests/test_telegramobject.py index 156c43b65..19eaa8776 100644 --- a/tests/test_telegramobject.py +++ b/tests/test_telegramobject.py @@ -29,7 +29,7 @@ except ImportError: from telegram import TelegramObject -class TestTelegramObject(object): +class TestTelegramObject: def test_to_json_native(self, monkeypatch): if ujson: monkeypatch.setattr('ujson.dumps', json_lib.dumps) diff --git a/tests/test_typehandler.py b/tests/test_typehandler.py index 3069ecee1..4b9c4e571 100644 --- a/tests/test_typehandler.py +++ b/tests/test_typehandler.py @@ -25,7 +25,7 @@ from telegram import Bot from telegram.ext import TypeHandler, CallbackContext, JobQueue -class TestTypeHandler(object): +class TestTypeHandler: test_flag = False @pytest.fixture(autouse=True) diff --git a/tests/test_update.py b/tests/test_update.py index 33af2bbcc..88c221824 100644 --- a/tests/test_update.py +++ b/tests/test_update.py @@ -52,7 +52,7 @@ def update(request): return Update(update_id=TestUpdate.update_id, **request.param) -class TestUpdate(object): +class TestUpdate: update_id = 868573637 @pytest.mark.parametrize('paramdict', argvalues=params, ids=ids) diff --git a/tests/test_updater.py b/tests/test_updater.py index 59009cb52..f57dfdea4 100644 --- a/tests/test_updater.py +++ b/tests/test_updater.py @@ -28,16 +28,10 @@ from random import randrange from threading import Thread, Event from time import sleep -try: - # python2 - from urllib2 import urlopen, Request, HTTPError -except ImportError: - # python3 - from urllib.request import Request, urlopen - from urllib.error import HTTPError +from urllib.request import Request, urlopen +from urllib.error import HTTPError import pytest -from future.builtins import bytes from telegram import TelegramError, Message, User, Chat, Update, Bot from telegram.error import Unauthorized, InvalidToken, TimedOut, RetryAfter @@ -75,7 +69,7 @@ if sys.platform.startswith("win") and sys.version_info >= (3, 8): asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy()) -class TestUpdater(object): +class TestUpdater: message_count = 0 received = None attempts = 0 diff --git a/tests/test_user.py b/tests/test_user.py index 9328c55fe..702d802ca 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -18,7 +18,7 @@ # along with this program. If not, see [http://www.gnu.org/licenses/]. import pytest -from telegram import User, Update +from telegram import Update, User from telegram.utils.helpers import escape_markdown @@ -46,7 +46,7 @@ def user(bot): supports_inline_queries=TestUser.supports_inline_queries, bot=bot) -class TestUser(object): +class TestUser: id_ = 1 is_bot = True first_name = u'first\u2022name' @@ -209,7 +209,7 @@ class TestUser(object): expected = u'[{}](tg://user?id={})' assert user.mention_markdown() == expected.format(user.full_name, user.id) - assert user.mention_markdown('the_name*\u2022') == expected.format('the\_name\*\u2022', + assert user.mention_markdown('the_name*\u2022') == expected.format('the\\_name\\*\u2022', user.id) assert user.mention_markdown(user.username) == expected.format(user.username, user.id) @@ -221,8 +221,8 @@ class TestUser(object): assert user.mention_markdown_v2() == expected.format(escape_markdown(user.full_name, version=2), user.id) - assert user.mention_markdown_v2('the{name>\u2022') == expected.format('the\{name\>\u2022', - user.id) + assert user.mention_markdown_v2('the{name>\u2022') == expected.format( + 'the\\{name\\>\u2022', user.id) assert user.mention_markdown_v2(user.username) == expected.format(user.username, user.id) def test_equality(self): diff --git a/tests/test_userprofilephotos.py b/tests/test_userprofilephotos.py index 5cfe2ed37..3f5d9ab99 100644 --- a/tests/test_userprofilephotos.py +++ b/tests/test_userprofilephotos.py @@ -19,7 +19,7 @@ from telegram import PhotoSize, UserProfilePhotos -class TestUserProfilePhotos(object): +class TestUserProfilePhotos: total_count = 2 photos = [ [ diff --git a/tests/test_venue.py b/tests/test_venue.py index 3505e88e9..be0c0423e 100644 --- a/tests/test_venue.py +++ b/tests/test_venue.py @@ -31,7 +31,7 @@ def venue(): foursquare_type=TestVenue.foursquare_type) -class TestVenue(object): +class TestVenue: location = Location(longitude=-46.788279, latitude=-23.691288) title = 'title' address = 'address' diff --git a/tests/test_video.py b/tests/test_video.py index 761b52e33..489dc4f23 100644 --- a/tests/test_video.py +++ b/tests/test_video.py @@ -38,7 +38,7 @@ def video(bot, chat_id): return bot.send_video(chat_id, video=f, timeout=50).video -class TestVideo(object): +class TestVideo: width = 360 height = 640 duration = 5 diff --git a/tests/test_videonote.py b/tests/test_videonote.py index 33cd454d0..aefc302b5 100644 --- a/tests/test_videonote.py +++ b/tests/test_videonote.py @@ -37,7 +37,7 @@ def video_note(bot, chat_id): return bot.send_video_note(chat_id, video_note=f, timeout=50).video_note -class TestVideoNote(object): +class TestVideoNote: length = 240 duration = 3 file_size = 132084 diff --git a/tests/test_voice.py b/tests/test_voice.py index 5bf45bae3..525b2ca31 100644 --- a/tests/test_voice.py +++ b/tests/test_voice.py @@ -38,7 +38,7 @@ def voice(bot, chat_id): return bot.send_voice(chat_id, voice=f, timeout=50).voice -class TestVoice(object): +class TestVoice: duration = 3 mime_type = 'audio/ogg' file_size = 9199