Running yapf for codebase #259

This commit is contained in:
Leandro Toledo 2016-05-14 22:46:40 -03:00
parent 703b8d1301
commit d445d35ceb
79 changed files with 312 additions and 695 deletions

View file

@ -2,7 +2,6 @@
sha: 'v0.7.1'
hooks:
- id: yapf
args: ['-i', '-r']
- repo: git://github.com/pre-commit/pre-commit-hooks
sha: 'v0.5.0'
@ -14,4 +13,4 @@
sha: 'v1.5.5'
hooks:
- id: pylint
args: ['--errors-only', '--disable=no-name-in-module,import-error']
args: ['--errors-only', '--disable=no-name-in-module,import-error', 'telegram']

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -18,7 +18,6 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents an Emoji."""
from future.utils import bytes_to_native_str as n
@ -858,7 +857,8 @@ class Emoji(object):
NO_MOBILE_PHONES = n(b'\xF0\x9F\x93\xB5')
TWISTED_RIGHTWARDS_ARROWS = n(b'\xF0\x9F\x94\x80')
CLOCKWISE_RIGHTWARDS_AND_LEFTWARDS_OPEN_CIRCLE_ARROWS = n(b'\xF0\x9F\x94\x81')
CLOCKWISE_RIGHTWARDS_AND_LEFTWARDS_OPEN_CIRCLE_ARROWS_WITH_CIRCLED_ONE_OVERLAY = n(b'\xF0\x9F\x94\x82')
CLOCKWISE_RIGHTWARDS_AND_LEFTWARDS_OPEN_CIRCLE_ARROWS_WITH_CIRCLED_ONE_OVERLAY = n(
b'\xF0\x9F\x94\x82')
ANTICLOCKWISE_DOWNWARDS_AND_UPWARDS_OPEN_CIRCLE_ARROWS = n(b'\xF0\x9F\x94\x84')
LOW_BRIGHTNESS_SYMBOL = n(b'\xF0\x9F\x94\x85')
HIGH_BRIGHTNESS_SYMBOL = n(b'\xF0\x9F\x94\x86')

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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