This commit is contained in:
Rahiel Kasim 2016-08-26 11:17:05 +02:00
parent 4753d27bd5
commit da87d4ba78
48 changed files with 298 additions and 306 deletions

View file

@ -618,13 +618,8 @@ class Bot(TelegramObject):
@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.
@ -1132,10 +1127,11 @@ 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).

View file

@ -28,12 +28,10 @@ class Botan(object):
return False
data = message.to_json()
try:
url = self.url_template.format(token=str(self.token),
uid=str(uid),
name=quote(event_name))
request = Request(url,
data=data.encode(),
headers={'Content-Type': 'application/json'})
url = self.url_template.format(
token=str(self.token), uid=str(uid), name=quote(event_name))
request = Request(
url, data=data.encode(), headers={'Content-Type': 'application/json'})
urlopen(request)
return True
except HTTPError as error:

View file

@ -61,9 +61,8 @@ class CallbackQueryHandler(Handler):
pattern=None,
pass_groups=False,
pass_groupdict=False):
super(CallbackQueryHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)
super(CallbackQueryHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
if isinstance(pattern, string_types):
pattern = re.compile(pattern)

View file

@ -43,9 +43,8 @@ class ChosenInlineResultHandler(Handler):
"""
def __init__(self, callback, pass_update_queue=False, pass_job_queue=False):
super(ChosenInlineResultHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)
super(ChosenInlineResultHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
def check_update(self, update):
return isinstance(update, Update) and update.chosen_inline_result

View file

@ -57,9 +57,8 @@ class CommandHandler(Handler):
pass_args=False,
pass_update_queue=False,
pass_job_queue=False):
super(CommandHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)
super(CommandHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
self.command = command
self.allow_edited = allow_edited
self.pass_args = pass_args

View file

@ -60,9 +60,8 @@ class InlineQueryHandler(Handler):
pattern=None,
pass_groups=False,
pass_groupdict=False):
super(InlineQueryHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)
super(InlineQueryHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
if isinstance(pattern, string_types):
pattern = re.compile(pattern)

View file

@ -80,7 +80,7 @@ class Filters(object):
or message.group_chat_created or message.supergroup_chat_created
or message.channel_chat_created or message.migrate_to_chat_id
or message.migrate_from_chat_id or message.pinned_message)
@staticmethod
def forwarded(message):
return bool(message.forward_date)
@ -115,9 +115,8 @@ class MessageHandler(Handler):
allow_edited=False,
pass_update_queue=False,
pass_job_queue=False):
super(MessageHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)
super(MessageHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
self.filters = filters
self.allow_edited = allow_edited

View file

@ -62,9 +62,8 @@ class RegexHandler(Handler):
pass_groupdict=False,
pass_update_queue=False,
pass_job_queue=False):
super(RegexHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)
super(RegexHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
if isinstance(pattern, string_types):
pattern = re.compile(pattern)

View file

@ -52,9 +52,8 @@ class StringCommandHandler(Handler):
pass_args=False,
pass_update_queue=False,
pass_job_queue=False):
super(StringCommandHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)
super(StringCommandHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
self.command = command
self.pass_args = pass_args

View file

@ -61,9 +61,8 @@ class StringRegexHandler(Handler):
pass_groupdict=False,
pass_update_queue=False,
pass_job_queue=False):
super(StringRegexHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)
super(StringRegexHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
if isinstance(pattern, string_types):
pattern = re.compile(pattern)

View file

@ -44,15 +44,10 @@ class TypeHandler(Handler):
Default is ``False``.
"""
def __init__(self,
type,
callback,
strict=False,
pass_update_queue=False,
def __init__(self, type, callback, strict=False, pass_update_queue=False,
pass_job_queue=False):
super(TypeHandler, self).__init__(callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue)
super(TypeHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
self.type = type
self.strict = strict

View file

@ -78,11 +78,12 @@ class Updater(object):
self.update_queue = Queue()
self.job_queue = JobQueue(self.bot)
self.__exception_event = Event()
self.dispatcher = Dispatcher(self.bot,
self.update_queue,
job_queue=self.job_queue,
workers=workers,
exception_event=self.__exception_event)
self.dispatcher = Dispatcher(
self.bot,
self.update_queue,
job_queue=self.job_queue,
workers=workers,
exception_event=self.__exception_event)
self.last_update_id = 0
self.logger = logging.getLogger(__name__)
self.running = False
@ -216,9 +217,8 @@ class Updater(object):
while self.running:
try:
updates = self.bot.getUpdates(self.last_update_id,
timeout=timeout,
network_delay=network_delay)
updates = self.bot.getUpdates(
self.last_update_id, timeout=timeout, network_delay=network_delay)
except TelegramError as te:
self.logger.error("Error while getting Updates: {0}".format(te))
@ -271,10 +271,11 @@ 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")
@ -292,10 +293,8 @@ class Updater(object):
exit_code = 0
if exit_code is 0:
try:
self.httpd.socket = ssl.wrap_socket(self.httpd.socket,
certfile=cert,
keyfile=key,
server_side=True)
self.httpd.socket = ssl.wrap_socket(
self.httpd.socket, certfile=cert, keyfile=key, server_side=True)
except ssl.SSLError as error:
self.logger.exception('Failed to init SSL socket')
raise TelegramError(str(error))

View file

@ -98,7 +98,7 @@ class InlineQueryResultArticle(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultArticle(**data)

View file

@ -88,7 +88,7 @@ class InlineQueryResultAudio(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultAudio(**data)

View file

@ -69,7 +69,7 @@ class InlineQueryResultCachedAudio(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultCachedAudio(**data)

View file

@ -54,7 +54,7 @@ class InlineQueryResultCachedDocument(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultCachedDocument(**data)

View file

@ -51,7 +51,7 @@ class InlineQueryResultCachedGif(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultCachedGif(**data)

View file

@ -52,7 +52,7 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultCachedMpeg4Gif(**data)

View file

@ -54,7 +54,7 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultCachedPhoto(**data)

View file

@ -45,7 +45,7 @@ class InlineQueryResultCachedSticker(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultCachedSticker(**data)

View file

@ -53,7 +53,7 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultCachedVideo(**data)

View file

@ -50,7 +50,7 @@ class InlineQueryResultCachedVoice(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultCachedVoice(**data)

View file

@ -59,7 +59,7 @@ class InlineQueryResultContact(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultContact(**data)

View file

@ -64,7 +64,7 @@ class InlineQueryResultDocument(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultDocument(**data)

View file

@ -60,7 +60,7 @@ class InlineQueryResultGif(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultGif(**data)

View file

@ -58,7 +58,7 @@ class InlineQueryResultLocation(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultLocation(**data)

View file

@ -60,7 +60,7 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultMpeg4Gif(**data)

View file

@ -62,7 +62,7 @@ class InlineQueryResultPhoto(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultPhoto(**data)

View file

@ -64,7 +64,7 @@ class InlineQueryResultVenue(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultVenue(**data)

View file

@ -67,7 +67,7 @@ class InlineQueryResultVideo(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultVideo(**data)

View file

@ -51,7 +51,7 @@ class InlineQueryResultVoice(InlineQueryResult):
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['input_message_content'] = InputMessageContent.de_json(
data.get('input_message_content'))
return InlineQueryResultVoice(**data)

View file

@ -125,9 +125,9 @@ class InputFile(object):
# Add input_file to upload
form.extend([
form_boundary, 'Content-Disposition: form-data; name="%s"; filename="%s"' % (
self.input_name, self.filename
), 'Content-Type: %s' % self.mimetype, '', self.input_file_content
form_boundary, 'Content-Disposition: form-data; name="%s"; filename="%s"' %
(self.input_name,
self.filename), 'Content-Type: %s' % self.mimetype, '', self.input_file_content
])
form.append('--' + self.boundary + '--')

View file

@ -52,12 +52,13 @@ def _get_con_pool():
def _init_con_pool():
global _CON_POOL
kwargs = dict(maxsize=CON_POOL_SIZE,
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where(),
socket_options=HTTPConnection.default_socket_options + [
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
])
kwargs = dict(
maxsize=CON_POOL_SIZE,
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where(),
socket_options=HTTPConnection.default_socket_options + [
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
])
proxy_url = _get_con_pool_proxy()
if not proxy_url:
mgr = urllib3.PoolManager(**kwargs)
@ -238,11 +239,12 @@ def post(url, data, timeout=None):
result = _request_wrapper('POST', url, body=data.to_form(), headers=data.headers)
else:
data = json.dumps(data)
result = _request_wrapper('POST',
url,
body=data.encode(),
headers={'Content-Type': 'application/json'},
**urlopen_kwargs)
result = _request_wrapper(
'POST',
url,
body=data.encode(),
headers={'Content-Type': 'application/json'},
**urlopen_kwargs)
return _parse(result)

View file

@ -36,8 +36,8 @@ class BaseTest(object):
def __init__(self, *args, **kwargs):
super(BaseTest, self).__init__(*args, **kwargs)
bot = telegram.Bot(os.environ.get('TOKEN',
'133505823:AAHZFMHno3mzVLErU5b5jJvaeG--qUyLyG0'))
bot = telegram.Bot(
os.environ.get('TOKEN', '133505823:AAHZFMHno3mzVLErU5b5jJvaeG--qUyLyG0'))
chat_id = os.environ.get('CHAT_ID', '12173560')
self._group_id = os.environ.get('GROUP_ID', '-49740850')

View file

@ -70,13 +70,14 @@ class AudioTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_audio_all_args(self):
message = self._bot.sendAudio(self._chat_id,
self.audio_file,
duration=self.duration,
performer=self.performer,
title=self.title,
mime_type=self.mime_type,
file_size=self.file_size)
message = self._bot.sendAudio(
self._chat_id,
self.audio_file,
duration=self.duration,
performer=self.performer,
title=self.title,
mime_type=self.mime_type,
file_size=self.file_size)
audio = message.audio
@ -91,11 +92,12 @@ class AudioTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_audio_mp3_file(self):
message = self._bot.sendAudio(chat_id=self._chat_id,
audio=self.audio_file,
duration=self.duration,
performer=self.performer,
title=self.title)
message = self._bot.sendAudio(
chat_id=self._chat_id,
audio=self.audio_file,
duration=self.duration,
performer=self.performer,
title=self.title)
audio = message.audio
@ -110,12 +112,13 @@ class AudioTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_audio_mp3_file_custom_filename(self):
message = self._bot.sendAudio(chat_id=self._chat_id,
audio=self.audio_file,
duration=self.duration,
performer=self.performer,
title=self.title,
filename='telegram_custom.mp3')
message = self._bot.sendAudio(
chat_id=self._chat_id,
audio=self.audio_file,
duration=self.duration,
performer=self.performer,
title=self.title,
filename='telegram_custom.mp3')
audio = message.audio
@ -130,11 +133,12 @@ class AudioTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_audio_mp3_url_file(self):
message = self._bot.sendAudio(chat_id=self._chat_id,
audio=self.audio_file_url,
duration=self.duration,
performer=self.performer,
title=self.title)
message = self._bot.sendAudio(
chat_id=self._chat_id,
audio=self.audio_file_url,
duration=self.duration,
performer=self.performer,
title=self.title)
audio = message.audio
@ -149,11 +153,12 @@ class AudioTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_audio_resend(self):
message = self._bot.sendAudio(chat_id=self._chat_id,
audio=self.audio_file_id,
duration=self.duration,
performer=self.performer,
title=self.title)
message = self._bot.sendAudio(
chat_id=self._chat_id,
audio=self.audio_file_id,
duration=self.duration,
performer=self.performer,
title=self.title)
audio = message.audio

View file

@ -47,8 +47,8 @@ class BotTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def testSendMessage(self):
message = self._bot.sendMessage(chat_id=self._chat_id,
text='Моё судно на воздушной подушке полно угрей')
message = self._bot.sendMessage(
chat_id=self._chat_id, text='Моё судно на воздушной подушке полно угрей')
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, u'Моё судно на воздушной подушке полно угрей')
@ -57,9 +57,10 @@ class BotTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def testSilentSendMessage(self):
message = self._bot.sendMessage(chat_id=self._chat_id,
text='Моё судно на воздушной подушке полно угрей',
disable_notification=True)
message = self._bot.sendMessage(
chat_id=self._chat_id,
text='Моё судно на воздушной подушке полно угрей',
disable_notification=True)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, u'Моё судно на воздушной подушке полно угрей')
@ -77,9 +78,8 @@ class BotTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def testForwardMessage(self):
message = self._bot.forwardMessage(chat_id=self._chat_id,
from_chat_id=self._chat_id,
message_id=2398)
message = self._bot.forwardMessage(
chat_id=self._chat_id, from_chat_id=self._chat_id, message_id=2398)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, 'teste')
@ -89,9 +89,10 @@ class BotTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def testSendPhoto(self):
message = self._bot.sendPhoto(photo=open('tests/data/telegram.png', 'rb'),
caption='testSendPhoto',
chat_id=self._chat_id)
message = self._bot.sendPhoto(
photo=open('tests/data/telegram.png', 'rb'),
caption='testSendPhoto',
chat_id=self._chat_id)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.photo[0].file_size, 1451)
@ -100,10 +101,11 @@ class BotTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def testSilentSendPhoto(self):
message = self._bot.sendPhoto(photo=open('tests/data/telegram.png', 'rb'),
caption='testSendPhoto',
chat_id=self._chat_id,
disable_notification=True)
message = self._bot.sendPhoto(
photo=open('tests/data/telegram.png', 'rb'),
caption='testSendPhoto',
chat_id=self._chat_id,
disable_notification=True)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.photo[0].file_size, 1451)
@ -113,8 +115,7 @@ class BotTest(BaseTest, unittest.TestCase):
@timeout(10)
def testResendPhoto(self):
message = self._bot.sendPhoto(
photo='AgADAQAD1y0yGx8j9Qf8f_m3CKeS6Iy95y8ABI1ggfVJ4-UvwJcAAgI',
chat_id=self._chat_id)
photo='AgADAQAD1y0yGx8j9Qf8f_m3CKeS6Iy95y8ABI1ggfVJ4-UvwJcAAgI', chat_id=self._chat_id)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.photo[0].file_id,
@ -124,8 +125,7 @@ class BotTest(BaseTest, unittest.TestCase):
@timeout(10)
def testSendJPGURLPhoto(self):
message = self._bot.sendPhoto(
photo='http://dummyimage.com/600x400/000/fff.jpg&text=telegram',
chat_id=self._chat_id)
photo='http://dummyimage.com/600x400/000/fff.jpg&text=telegram', chat_id=self._chat_id)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.photo[0].file_size, 822)
@ -134,8 +134,7 @@ class BotTest(BaseTest, unittest.TestCase):
@timeout(10)
def testSendPNGURLPhoto(self):
message = self._bot.sendPhoto(
photo='http://dummyimage.com/600x400/000/fff.png&text=telegram',
chat_id=self._chat_id)
photo='http://dummyimage.com/600x400/000/fff.png&text=telegram', chat_id=self._chat_id)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.photo[0].file_size, 685)
@ -144,8 +143,7 @@ class BotTest(BaseTest, unittest.TestCase):
@timeout(10)
def testSendGIFURLPhoto(self):
message = self._bot.sendPhoto(
photo='http://dummyimage.com/600x400/000/fff.gif&text=telegram',
chat_id=self._chat_id)
photo='http://dummyimage.com/600x400/000/fff.gif&text=telegram', chat_id=self._chat_id)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.photo[0].file_size, 685)

View file

@ -33,12 +33,12 @@ class ConstantsTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def testMaxMessageLength(self):
self._bot.sendMessage(chat_id=self._chat_id,
text='a' * telegram.constants.MAX_MESSAGE_LENGTH)
self._bot.sendMessage(
chat_id=self._chat_id, text='a' * telegram.constants.MAX_MESSAGE_LENGTH)
try:
self._bot.sendMessage(chat_id=self._chat_id,
text='a' * (telegram.constants.MAX_MESSAGE_LENGTH + 1))
self._bot.sendMessage(
chat_id=self._chat_id, text='a' * (telegram.constants.MAX_MESSAGE_LENGTH + 1))
except BadRequest as e:
err = str(e)
@ -47,14 +47,16 @@ class ConstantsTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def testMaxCaptionLength(self):
self._bot.sendPhoto(photo=open('tests/data/telegram.png', 'rb'),
caption='a' * telegram.constants.MAX_CAPTION_LENGTH,
chat_id=self._chat_id)
self._bot.sendPhoto(
photo=open('tests/data/telegram.png', 'rb'),
caption='a' * telegram.constants.MAX_CAPTION_LENGTH,
chat_id=self._chat_id)
try:
self._bot.sendPhoto(photo=open('tests/data/telegram.png', 'rb'),
caption='a' * (telegram.constants.MAX_CAPTION_LENGTH + 1),
chat_id=self._chat_id)
self._bot.sendPhoto(
photo=open('tests/data/telegram.png', 'rb'),
caption='a' * (telegram.constants.MAX_CAPTION_LENGTH + 1),
chat_id=self._chat_id)
except BadRequest as e:
err = str(e)

View file

@ -118,9 +118,8 @@ class ConversationHandlerTest(BaseTest, unittest.TestCase):
user = User(first_name="Misses Test", id=123)
second_user = User(first_name="Mister Test", id=124)
handler = ConversationHandler(entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks)
handler = ConversationHandler(
entry_points=self.entry_points, states=self.states, fallbacks=self.fallbacks)
d.add_handler(handler)
queue = self.updater.start_polling(0.01)

View file

@ -70,9 +70,8 @@ class DocumentTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_document_png_file_with_custom_file_name(self):
message = self._bot.sendDocument(self._chat_id,
self.document_file,
filename='telegram_custom.png')
message = self._bot.sendDocument(
self._chat_id, self.document_file, filename='telegram_custom.png')
document = message.document

View file

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

View file

@ -32,10 +32,9 @@ class InlineKeyboardMarkupTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram KeyboardButton."""
def setUp(self):
self.inline_keyboard = [[telegram.InlineKeyboardButton(text='button1',
callback_data='data1'),
telegram.InlineKeyboardButton(text='button2',
callback_data='data2')]]
self.inline_keyboard = [[telegram.InlineKeyboardButton(
text='button1', callback_data='data1'), telegram.InlineKeyboardButton(
text='button2', callback_data='data2')]]
self.json_dict = {
'inline_keyboard': [[self.inline_keyboard[0][0].to_dict(),
@ -60,8 +59,9 @@ class InlineKeyboardMarkupTest(BaseTest, unittest.TestCase):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict)
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard, list))
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard[0][0],
telegram.InlineKeyboardButton))
self.assertTrue(
isinstance(inline_keyboard_markup.inline_keyboard[0][0],
telegram.InlineKeyboardButton))
def test_inline_keyboard_markup_to_json(self):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict)
@ -72,8 +72,9 @@ class InlineKeyboardMarkupTest(BaseTest, unittest.TestCase):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict)
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard, list))
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard[0][0],
telegram.InlineKeyboardButton))
self.assertTrue(
isinstance(inline_keyboard_markup.inline_keyboard[0][0],
telegram.InlineKeyboardButton))
if __name__ == '__main__':

View file

@ -35,7 +35,8 @@ class InputLocationMessageContentTest(BaseTest, unittest.TestCase):
self.latitude = 1.
self.longitude = 2.
self.json_dict = {'longitude': self.longitude, 'latitude': self.latitude,}
self.json_dict = {'longitude': self.longitude,
'latitude': self.latitude,}
def test_ilmc_de_json(self):
ilmc = telegram.InputLocationMessageContent.de_json(self.json_dict)

View file

@ -44,9 +44,8 @@ class LocationTest(BaseTest, unittest.TestCase):
self.assertEqual(location.longitude, self.longitude)
def test_send_location_explicit_args(self):
message = self._bot.sendLocation(chat_id=self._chat_id,
latitude=self.latitude,
longitude=self.longitude)
message = self._bot.sendLocation(
chat_id=self._chat_id, latitude=self.latitude, longitude=self.longitude)
location = message.location

View file

@ -37,17 +37,15 @@ class ParseMode(BaseTest, unittest.TestCase):
self.formatted_text_formatted = u'bold italic link.'
def test_send_message_with_parse_mode_markdown(self):
message = self._bot.sendMessage(chat_id=self._chat_id,
text=self.markdown_text,
parse_mode=telegram.ParseMode.MARKDOWN)
message = self._bot.sendMessage(
chat_id=self._chat_id, text=self.markdown_text, parse_mode=telegram.ParseMode.MARKDOWN)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, self.formatted_text_formatted)
def test_send_message_with_parse_mode_html(self):
message = self._bot.sendMessage(chat_id=self._chat_id,
text=self.html_text,
parse_mode=telegram.ParseMode.HTML)
message = self._bot.sendMessage(
chat_id=self._chat_id, text=self.html_text, parse_mode=telegram.ParseMode.HTML)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, self.formatted_text_formatted)

View file

@ -35,7 +35,8 @@ class ReplyKeyboardHideTest(BaseTest, unittest.TestCase):
self.hide_keyboard = True
self.selective = True
self.json_dict = {'hide_keyboard': self.hide_keyboard, 'selective': self.selective,}
self.json_dict = {'hide_keyboard': self.hide_keyboard,
'selective': self.selective,}
def test_send_message_with_reply_keyboard_hide(self):
message = self._bot.sendMessage(

View file

@ -180,9 +180,8 @@ class UpdaterTest(BaseTest, unittest.TestCase):
# Remove handler
d.removeHandler(handler)
handler = MessageHandler([Filters.text],
self.telegramHandlerEditedTest,
allow_edited=False)
handler = MessageHandler(
[Filters.text], self.telegramHandlerEditedTest, allow_edited=False)
d.addHandler(handler)
self.reset()
@ -414,11 +413,12 @@ class UpdaterTest(BaseTest, unittest.TestCase):
def test_additionalArgs(self):
self._setup_updater('', messages=0)
handler = StringCommandHandler('test5',
self.additionalArgsTest,
pass_update_queue=True,
pass_job_queue=True,
pass_args=True)
handler = StringCommandHandler(
'test5',
self.additionalArgsTest,
pass_update_queue=True,
pass_job_queue=True,
pass_args=True)
self.updater.dispatcher.add_handler(handler)
queue = self.updater.start_polling(0.01)
@ -430,10 +430,11 @@ class UpdaterTest(BaseTest, unittest.TestCase):
def test_regexGroupHandler(self):
self._setup_updater('', messages=0)
d = self.updater.dispatcher
handler = StringRegexHandler('^(This).*?(?P<testgroup>regex group).*',
self.regexGroupHandlerTest,
pass_groupdict=True,
pass_groups=True)
handler = StringRegexHandler(
'^(This).*?(?P<testgroup>regex group).*',
self.regexGroupHandlerTest,
pass_groupdict=True,
pass_groups=True)
d.add_handler(handler)
queue = self.updater.start_polling(0.01)
queue.put('This is a test message for regex group matching.')
@ -444,15 +445,18 @@ class UpdaterTest(BaseTest, unittest.TestCase):
def test_regexGroupHandlerInlineQuery(self):
self._setup_updater('', messages=0)
d = self.updater.dispatcher
handler = InlineQueryHandler(self.regexGroupHandlerTest,
pattern='^(This).*?(?P<testgroup>regex group).*',
pass_groupdict=True,
pass_groups=True)
handler = InlineQueryHandler(
self.regexGroupHandlerTest,
pattern='^(This).*?(?P<testgroup>regex group).*',
pass_groupdict=True,
pass_groups=True)
d.add_handler(handler)
queue = self.updater.start_polling(0.01)
queue.put(Update(update_id=0,
inline_query=InlineQuery(
0, None, 'This is a test message for regex group matching.', None)))
queue.put(
Update(
update_id=0,
inline_query=InlineQuery(
0, None, 'This is a test message for regex group matching.', None)))
sleep(.1)
self.assertEqual(self.received_message, (('This', 'regex group'),
@ -461,15 +465,18 @@ class UpdaterTest(BaseTest, unittest.TestCase):
def test_regexGroupHandlerCallbackQuery(self):
self._setup_updater('', messages=0)
d = self.updater.dispatcher
handler = CallbackQueryHandler(self.regexGroupHandlerTest,
pattern='^(This).*?(?P<testgroup>regex group).*',
pass_groupdict=True,
pass_groups=True)
handler = CallbackQueryHandler(
self.regexGroupHandlerTest,
pattern='^(This).*?(?P<testgroup>regex group).*',
pass_groupdict=True,
pass_groups=True)
d.add_handler(handler)
queue = self.updater.start_polling(0.01)
queue.put(Update(update_id=0,
callback_query=CallbackQuery(
0, None, 'This is a test message for regex group matching.')))
queue.put(
Update(
update_id=0,
callback_query=CallbackQuery(0, None,
'This is a test message for regex group matching.')))
sleep(.1)
self.assertEqual(self.received_message, (('This', 'regex group'),
@ -493,21 +500,21 @@ class UpdaterTest(BaseTest, unittest.TestCase):
ip = '127.0.0.1'
port = randrange(1024, 49152) # Select random port for travis
self.updater.start_webhook(ip,
port,
url_path='TOKEN',
cert='./tests/test_updater.py',
key='./tests/test_updater.py',
webhook_url=None)
self.updater.start_webhook(
ip,
port,
url_path='TOKEN',
cert='./tests/test_updater.py',
key='./tests/test_updater.py',
webhook_url=None)
sleep(0.5)
# SSL-Wrapping will fail, so we start the server without SSL
Thread(target=self.updater.httpd.serve_forever).start()
# Now, we send an update to the server via urlopen
message = Message(1,
User(1, "Tester"),
datetime.now(),
Chat(1, "group", title="Test Group"))
message = Message(
1, User(1, "Tester"), datetime.now(), Chat(
1, "group", title="Test Group"))
message.text = "Webhook Test"
update = Update(1)
@ -524,8 +531,7 @@ class UpdaterTest(BaseTest, unittest.TestCase):
self.assertEqual(200, response.code)
response = self._send_webhook_msg(
ip, port, None, 'webookhandler.py',
get_method=lambda: 'HEAD')
ip, port, None, 'webookhandler.py', get_method=lambda: 'HEAD')
self.assertEqual(b'', response.read())
self.assertEqual(200, response.code)
@ -547,10 +553,9 @@ class UpdaterTest(BaseTest, unittest.TestCase):
sleep(0.5)
# Now, we send an update to the server via urlopen
message = Message(1,
User(1, "Tester 2"),
datetime.now(),
Chat(1, 'group', title="Test Group 2"))
message = Message(
1, User(1, "Tester 2"), datetime.now(), Chat(
1, 'group', title="Test Group 2"))
message.text = "Webhook Test 2"
update = Update(1)
@ -576,8 +581,7 @@ class UpdaterTest(BaseTest, unittest.TestCase):
def test_bootstrap_retries_unauth(self):
retries = 3
self._setup_updater(
'', messages=0, bootstrap_retries=retries,
bootstrap_err=Unauthorized())
'', messages=0, bootstrap_retries=retries, bootstrap_err=Unauthorized())
self.assertRaises(Unauthorized, self.updater._bootstrap, retries, False, 'path', None)
self.assertEqual(self.updater.bot.bootstrap_attempts, 1)
@ -585,8 +589,7 @@ class UpdaterTest(BaseTest, unittest.TestCase):
def test_bootstrap_retries_invalid_token(self):
retries = 3
self._setup_updater(
'', messages=0, bootstrap_retries=retries,
bootstrap_err=InvalidToken())
'', messages=0, bootstrap_retries=retries, bootstrap_err=InvalidToken())
self.assertRaises(InvalidToken, self.updater._bootstrap, retries, False, 'path', None)
self.assertEqual(self.updater.bot.bootstrap_attempts, 1)
@ -604,18 +607,16 @@ class UpdaterTest(BaseTest, unittest.TestCase):
ip = '127.0.0.1'
port = randrange(1024, 49152) # select random port for travis
thr = Thread(target=self.updater._start_webhook,
args=(ip, port, '', None, None, 0, False, None))
thr = Thread(
target=self.updater._start_webhook, args=(ip, port, '', None, None, 0, False, None))
thr.start()
sleep(0.5)
try:
with self.assertRaises(HTTPError) as ctx:
self._send_webhook_msg(ip,
port,
'<root><bla>data</bla></root>',
content_type='application/xml')
self._send_webhook_msg(
ip, port, '<root><bla>data</bla></root>', content_type='application/xml')
self.assertEqual(ctx.exception.code, 403)
with self.assertRaises(HTTPError) as ctx:

View file

@ -79,11 +79,12 @@ class VideoTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_video_all_args(self):
message = self._bot.sendVideo(self._chat_id,
self.video_file,
timeout=10,
duration=self.duration,
caption=self.caption)
message = self._bot.sendVideo(
self._chat_id,
self.video_file,
timeout=10,
duration=self.duration,
caption=self.caption)
video = message.video
@ -101,11 +102,12 @@ class VideoTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_video_mp4_file(self):
message = self._bot.sendVideo(chat_id=self._chat_id,
video=self.video_file,
timeout=10,
duration=self.duration,
caption=self.caption)
message = self._bot.sendVideo(
chat_id=self._chat_id,
video=self.video_file,
timeout=10,
duration=self.duration,
caption=self.caption)
video = message.video
@ -123,12 +125,13 @@ class VideoTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_video_mp4_file_with_custom_filename(self):
message = self._bot.sendVideo(chat_id=self._chat_id,
video=self.video_file,
timeout=10,
duration=self.duration,
caption=self.caption,
filename='telegram_custom.mp4')
message = self._bot.sendVideo(
chat_id=self._chat_id,
video=self.video_file,
timeout=10,
duration=self.duration,
caption=self.caption,
filename='telegram_custom.mp4')
video = message.video
@ -146,11 +149,12 @@ class VideoTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_video_mp4_file_url(self):
message = self._bot.sendVideo(chat_id=self._chat_id,
video=self.video_file_url,
timeout=10,
duration=self.duration,
caption=self.caption)
message = self._bot.sendVideo(
chat_id=self._chat_id,
video=self.video_file_url,
timeout=10,
duration=self.duration,
caption=self.caption)
video = message.video
@ -167,11 +171,12 @@ class VideoTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_video_resend(self):
message = self._bot.sendVideo(chat_id=self._chat_id,
video=self.video_file_id,
timeout=10,
duration=self.duration,
caption=self.caption)
message = self._bot.sendVideo(
chat_id=self._chat_id,
video=self.video_file_id,
timeout=10,
duration=self.duration,
caption=self.caption)
video = message.video

View file

@ -64,11 +64,12 @@ class VoiceTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_voice_all_args(self):
message = self._bot.sendVoice(self._chat_id,
self.voice_file,
self.duration,
mime_type=self.mime_type,
file_size=self.file_size)
message = self._bot.sendVoice(
self._chat_id,
self.voice_file,
self.duration,
mime_type=self.mime_type,
file_size=self.file_size)
voice = message.voice
@ -81,9 +82,8 @@ class VoiceTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_voice_ogg_file(self):
message = self._bot.sendVoice(chat_id=self._chat_id,
voice=self.voice_file,
duration=self.duration)
message = self._bot.sendVoice(
chat_id=self._chat_id, voice=self.voice_file, duration=self.duration)
voice = message.voice
@ -96,10 +96,11 @@ class VoiceTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_voice_ogg_file_with_custom_filename(self):
message = self._bot.sendVoice(chat_id=self._chat_id,
voice=self.voice_file,
duration=self.duration,
filename='telegram_custom.ogg')
message = self._bot.sendVoice(
chat_id=self._chat_id,
voice=self.voice_file,
duration=self.duration,
filename='telegram_custom.ogg')
voice = message.voice
@ -112,9 +113,8 @@ class VoiceTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_voice_ogg_url_file(self):
message = self._bot.sendVoice(chat_id=self._chat_id,
voice=self.voice_file_url,
duration=self.duration)
message = self._bot.sendVoice(
chat_id=self._chat_id, voice=self.voice_file_url, duration=self.duration)
voice = message.voice
@ -127,9 +127,8 @@ class VoiceTest(BaseTest, unittest.TestCase):
@flaky(3, 1)
@timeout(10)
def test_send_voice_resend(self):
message = self._bot.sendVoice(chat_id=self._chat_id,
voice=self.voice_file_id,
duration=self.duration)
message = self._bot.sendVoice(
chat_id=self._chat_id, voice=self.voice_file_id, duration=self.duration)
voice = message.voice