Compare commits

..

8 Commits

Author SHA1 Message Date
Leandro Toledo 53f5911aad Update README.rst 2015-08-17 11:45:28 -03:00
Leandro Toledo d4870148c7 Add telegram.voice to docs and minor docstring fixes #39 2015-08-17 11:40:21 -03:00
Leandro Toledo 6e2881b31b Adding support for Voice object and sendVoice method #39 2015-08-17 11:34:42 -03:00
Leandro Toledo 686aecb914 Fix tests for Python 3 2015-08-17 10:01:17 -03:00
Leandro Toledo 35f31bf136 Merge branch 'master' of https://github.com/leandrotoledo/python-telegram-bot 2015-08-17 09:57:07 -03:00
Leandro Toledo 56f6845969 Adding is_json tests and fixes json serialization when a forwared message #38 2015-08-17 09:56:51 -03:00
Leandro Toledo 505df01ae1 Update AUTHORS.rst 2015-08-15 15:19:17 -03:00
Leandro Toledo 3be58b759f Releasing v2.6.1 2015-08-15 15:06:32 -03:00
14 changed files with 232 additions and 24 deletions
+1
View File
@@ -13,6 +13,7 @@ The following wonderful people contributed directly or indirectly to this projec
- `franciscod <https://github.com/franciscod>`_
- `JASON0916 <https://github.com/JASON0916>`_
- `JRoot3D <https://github.com/JRoot3D>`_
- `macrojames <https://github.com/macrojames>`_
- `sooyhwang <https://github.com/sooyhwang>`_
- `wjt <https://github.com/wjt>`_
+5
View File
@@ -1,3 +1,8 @@
2015-08-15
Released 2.6.1
Fixed parsing image header issue on < Python 2.7.3
2015-08-14
Released 2.6.0
Depreciation of require_authentication and clearCredentials methods
+3 -2
View File
@@ -89,6 +89,7 @@ sendAudio Yes
sendDocument Yes
sendSticker Yes
sendVideo Yes
sendVoice Yes
sendLocation Yes
sendChatAction Yes
getUpdates Yes
@@ -194,9 +195,9 @@ To post an image file via URL (right now only sendPhoto supports this)::
>>> bot.sendPhoto(chat_id=chat_id, photo='https://telegram.org/img/t_logo.png')
To post an audio file::
To post a voice file::
>>> bot.sendAudio(chat_id=chat_id, audio=open('tests/telegram.ogg', 'rb'))
>>> bot.sendVoice(chat_id=chat_id, voice=open('tests/telegram.ogg', 'rb'))
To tell the user that something is happening on bot's side::
+1
View File
@@ -29,6 +29,7 @@ Submodules
telegram.user
telegram.userprofilephotos
telegram.video
telegram.voice
Module contents
---------------
+7
View File
@@ -0,0 +1,7 @@
telegram.voice module
=====================
.. automodule:: telegram.voice
:members:
:undoc-members:
:show-inheritance:
+1 -1
View File
@@ -15,7 +15,7 @@ def read(*paths):
setup(
name='python-telegram-bot',
version='2.6.0',
version='2.6.1',
author='Leandro Toledo',
author_email='leandrotoledodesouza@gmail.com',
license='LGPLv3',
+4 -2
View File
@@ -18,7 +18,7 @@
__author__ = 'leandrotoledodesouza@gmail.com'
__version__ = '2.6.0'
__version__ = '2.6.1'
from .base import TelegramObject
from .user import User
@@ -27,6 +27,7 @@ from .update import Update
from .groupchat import GroupChat
from .photosize import PhotoSize
from .audio import Audio
from .voice import Voice
from .document import Document
from .sticker import Sticker
from .video import Video
@@ -48,4 +49,5 @@ __all__ = ['Bot', 'Emoji', 'TelegramError', 'InputFile', 'ReplyMarkup',
'ForceReply', 'ReplyKeyboardHide', 'ReplyKeyboardMarkup',
'UserProfilePhotos', 'ChatAction', 'Location', 'Contact',
'Video', 'Sticker', 'Document', 'Audio', 'PhotoSize', 'GroupChat',
'Update', 'Message', 'User', 'TelegramObject', 'NullHandler']
'Update', 'Message', 'User', 'TelegramObject', 'NullHandler',
'Voice']
+10
View File
@@ -24,10 +24,14 @@ class Audio(TelegramObject):
def __init__(self,
file_id,
duration,
performer=None,
title=None,
mime_type=None,
file_size=None):
self.file_id = file_id
self.duration = duration
self.performer = performer
self.title = title
self.mime_type = mime_type
self.file_size = file_size
@@ -35,12 +39,18 @@ class Audio(TelegramObject):
def de_json(data):
return Audio(file_id=data.get('file_id', None),
duration=data.get('duration', None),
performer=data.get('performer', None),
title=data.get('title', None),
mime_type=data.get('mime_type', None),
file_size=data.get('file_size', None))
def to_dict(self):
data = {'file_id': self.file_id,
'duration': self.duration}
if self.performer:
data['performer'] = self.performer
if self.title:
data['title'] = self.title
if self.mime_type:
data['mime_type'] = self.mime_type
if self.file_size:
+70 -3
View File
@@ -262,12 +262,21 @@ class Bot(TelegramObject):
def sendAudio(self,
chat_id,
audio,
duration=None,
performer=None,
title=None,
reply_to_message_id=None,
reply_markup=None):
"""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
sent as telegram.Document).
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
files of up to 50 MB in size, this limit may be changed in the future.
For backward compatibility, when both fields title and description are
empty and mime-type of the sent file is not "audio/mpeg", file is sent
as playable voice message. In this case, your audio must be in an .ogg
file encoded with OPUS. This will be removed in the future. You need to
use sendVoice method instead.
Args:
chat_id:
@@ -276,6 +285,12 @@ class Bot(TelegramObject):
Audio file to send. You can either pass a file_id as String to
resend an audio that is already on the Telegram servers, or upload
a new audio file using multipart/form-data.
duration:
Duration of sent audio in seconds. [Optional]
performer:
Performer of sent audio. [Optional]
title:
Title of sent audio. [Optional]
reply_to_message_id:
If the message is a reply, ID of the original message. [Optional]
reply_markup:
@@ -292,6 +307,13 @@ class Bot(TelegramObject):
data = {'chat_id': chat_id,
'audio': audio}
if duration:
data['duration'] = duration
if performer:
data['performer'] = performer
if title:
data['title'] = title
return url, data
@log
@@ -409,6 +431,51 @@ class Bot(TelegramObject):
return url, data
@log
@message
def sendVoice(self,
chat_id,
voice,
duration=None,
reply_to_message_id=None,
reply_markup=None):
"""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
sent as Audio or Document). On success, the sent Message is returned.
Bots can currently send audio files of up to 50 MB in size, this limit
may be changed in the future.
Args:
chat_id:
Unique identifier for the message recipient - User or GroupChat id.
voice:
Audio file to send. You can either pass a file_id as String to
resend an audio that is already on the Telegram servers, or upload
a new audio file using multipart/form-data.
duration:
Duration of sent audio in seconds. [Optional]
reply_to_message_id:
If the message is a reply, ID of the original message. [Optional]
reply_markup:
Additional interface options. A JSON-serialized object for a
custom reply keyboard, instructions to hide keyboard or to force a
reply from the user. [Optional]
Returns:
A telegram.Message instance representing the message posted.
"""
url = '%s/sendVoice' % self.base_url
data = {'chat_id': chat_id,
'voice': voice}
if duration:
data['duration'] = duration
return url, data
@log
@message
def sendLocation(self,
+6 -2
View File
@@ -54,6 +54,9 @@ class InputFile(object):
if 'video' in data:
self.input_name = 'video'
self.input_file = data.pop('video')
if 'voice' in data:
self.input_name = 'voice'
self.input_file = data.pop('voice')
if isinstance(self.input_file, file):
self.input_file_content = self.input_file.read()
@@ -136,7 +139,8 @@ class InputFile(object):
@staticmethod
def is_inputfile(data):
"""Check if the request is a file request
"""Check if the request is a file request.
Args:
data:
A dict of (str, unicode) key/value pairs
@@ -145,7 +149,7 @@ class InputFile(object):
bool
"""
if data:
file_types = ['audio', 'document', 'photo', 'video']
file_types = ['audio', 'document', 'photo', 'video', 'voice']
file_type = [i for i in list(data.keys()) if i in file_types]
if file_type:
+12 -1
View File
@@ -37,6 +37,7 @@ class Message(TelegramObject):
photo=None,
sticker=None,
video=None,
voice=None,
caption=None,
contact=None,
location=None,
@@ -59,6 +60,7 @@ class Message(TelegramObject):
self.photo = photo
self.sticker = sticker
self.video = video
self.voice = voice
self.caption = caption
self.contact = contact
self.location = location
@@ -142,6 +144,12 @@ class Message(TelegramObject):
else:
video = None
if 'voice' in data:
from telegram import Voice
voice = Voice.de_json(data['voice'])
else:
voice = None
if 'contact' in data:
from telegram import Contact
contact = Contact.de_json(data['contact'])
@@ -179,6 +187,7 @@ class Message(TelegramObject):
photo=photo,
sticker=sticker,
video=video,
voice=voice,
caption=data.get('caption', ''),
contact=contact,
location=location,
@@ -207,7 +216,7 @@ class Message(TelegramObject):
data['forward_date'] = self._totimestamp(self.forward_date)
if self.forward_from:
data['forward_from'] = self.forward_from
data['forward_from'] = self.forward_from.to_dict()
if self.reply_to_message:
data['reply_to_message'] = self.reply_to_message
if self.text:
@@ -222,6 +231,8 @@ class Message(TelegramObject):
data['sticker'] = self.sticker.to_dict()
if self.video:
data['video'] = self.video.to_dict()
if self.voice:
data['voice'] = self.voice.to_dict()
if self.caption:
data['caption'] = self.caption
if self.contact:
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
from telegram import TelegramObject
class Voice(TelegramObject):
def __init__(self,
file_id,
duration=None,
mime_type=None,
file_size=None):
self.file_id = file_id
self.duration = duration
self.mime_type = mime_type
self.file_size = file_size
@staticmethod
def de_json(data):
return Voice(file_id=data.get('file_id', None),
duration=data.get('duration', None),
mime_type=data.get('mime_type', None),
file_size=data.get('file_size', None))
def to_dict(self):
data = {'file_id': self.file_id}
if self.duration:
data['duration'] = self.duration
if self.mime_type:
data['mime_type'] = self.mime_type
if self.file_size:
data['file_size'] = self.file_size
return data
Binary file not shown.
+63 -13
View File
@@ -19,12 +19,21 @@
import os
import json
import telegram
import unittest
from datetime import datetime
class BotTest(unittest.TestCase):
@staticmethod
def is_json(string):
try:
json.loads(string)
except ValueError:
return False
return True
def setUp(self):
bot = telegram.Bot(token=os.environ.get('TOKEN'))
self._bot = bot
@@ -34,6 +43,7 @@ class BotTest(unittest.TestCase):
'''Test the telegram.Bot getMe method'''
print('Testing getMe')
bot = self._bot.getMe()
self.assertTrue(self.is_json(bot.to_json()))
self.assertEqual(120405045, bot.id)
self.assertEqual('Toledo\'s Palace Bot', bot.first_name)
self.assertEqual(None, bot.last_name)
@@ -44,6 +54,7 @@ class BotTest(unittest.TestCase):
print('Testing sendMessage')
message = self._bot.sendMessage(chat_id=12173560,
text='Моё судно на воздушной подушке полно угрей')
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(u'Моё судно на воздушной подушке полно угрей', message.text)
self.assertIsInstance(message.date, datetime)
@@ -51,6 +62,7 @@ class BotTest(unittest.TestCase):
'''Test the telegram.Bot getUpdates method'''
print('Testing getUpdates')
updates = self._bot.getUpdates()
self.assertTrue(self.is_json(updates[0].to_json()))
self.assertIsInstance(updates[0], telegram.Update)
def testForwardMessage(self):
@@ -59,6 +71,7 @@ class BotTest(unittest.TestCase):
message = self._bot.forwardMessage(chat_id=12173560,
from_chat_id=12173560,
message_id=138)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual('Oi', message.text)
self.assertEqual('leandrotoledo', message.forward_from.username)
self.assertIsInstance(message.forward_date, datetime)
@@ -69,70 +82,102 @@ class BotTest(unittest.TestCase):
message = self._bot.sendPhoto(photo=open('tests/telegram.png', 'rb'),
caption='testSendPhoto',
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(1451, message.photo[0].file_size)
self.assertEqual('testSendPhoto', message.caption)
def testResendPhoto(self):
'''Test the telegram.Bot sendPhoto method'''
print('Testing sendPhoto - Resend')
message = self._bot.sendPhoto(photo=str('AgADAQADr6cxGzU8LQe6q0dMJD2rHYkP2ykABFymiQqJgjxRGGMAAgI'),
message = self._bot.sendPhoto(photo='AgADAQADr6cxGzU8LQe6q0dMJD2rHYkP2ykABFymiQqJgjxRGGMAAgI',
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual('AgADAQADr6cxGzU8LQe6q0dMJD2rHYkP2ykABFymiQqJgjxRGGMAAgI', message.photo[0].file_id)
def testSendJPGURLPhoto(self):
'''Test the telegram.Bot sendPhoto method'''
print('Testing testSendJPGURLPhoto - URL')
message = self._bot.sendPhoto(photo=str('http://dummyimage.com/600x400/000/fff.jpg&text=telegram'),
message = self._bot.sendPhoto(photo='http://dummyimage.com/600x400/000/fff.jpg&text=telegram',
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(822, message.photo[0].file_size)
def testSendPNGURLPhoto(self):
'''Test the telegram.Bot sendPhoto method'''
print('Testing testSendPNGURLPhoto - URL')
message = self._bot.sendPhoto(photo=str('http://dummyimage.com/600x400/000/fff.png&text=telegram'),
message = self._bot.sendPhoto(photo='http://dummyimage.com/600x400/000/fff.png&text=telegram',
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(684, message.photo[0].file_size)
def testSendGIFURLPhoto(self):
'''Test the telegram.Bot sendPhoto method'''
print('Testing testSendGIFURLPhoto - URL')
message = self._bot.sendPhoto(photo=str('http://dummyimage.com/600x400/000/fff.gif&text=telegram'),
message = self._bot.sendPhoto(photo='http://dummyimage.com/600x400/000/fff.gif&text=telegram',
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(684, message.photo[0].file_size)
def testSendAudio(self):
'''Test the telegram.Bot sendAudio method'''
print('Testing sendAudio - File')
message = self._bot.sendAudio(audio=open('tests/telegram.ogg', 'rb'),
chat_id=12173560)
self.assertEqual(9199, message.audio.file_size)
message = self._bot.sendAudio(audio=open('tests/telegram.mp3', 'rb'),
chat_id=12173560,
performer='Leandro Toledo',
title='Teste')
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(28232, message.audio.file_size)
self.assertEqual('Leandro Toledo', message.audio.performer)
self.assertEqual('Teste', message.audio.title)
def testResendAudio(self):
'''Test the telegram.Bot sendAudio method'''
print('Testing sendAudio - Resend')
message = self._bot.sendAudio(audio=str('AwADAQADIQEAAvjAuQABSAXg_GhkhZcC'),
message = self._bot.sendAudio(audio='BQADAQADwwcAAjU8LQdBRsl3_qD2TAI',
chat_id=12173560,
performer='Leandro Toledo', # Bug #39
title='Teste') # Bug #39
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual('BQADAQADwwcAAjU8LQdBRsl3_qD2TAI', message.audio.file_id)
def testSendVoice(self):
'''Test the telegram.Bot sendVoice method'''
print('Testing sendVoice - File')
message = self._bot.sendVoice(voice=open('tests/telegram.ogg', 'rb'),
chat_id=12173560)
self.assertEqual('AwADAQADIQEAAvjAuQABSAXg_GhkhZcC', message.audio.file_id)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(9199, message.voice.file_size)
def testResendVoice(self):
'''Test the telegram.Bot sendVoice method'''
print('Testing sendVoice - Resend')
message = self._bot.sendVoice(voice='AwADAQADIQEAAvjAuQABSAXg_GhkhZcC',
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual('AwADAQADIQEAAvjAuQABSAXg_GhkhZcC', message.voice.file_id)
def testSendDocument(self):
'''Test the telegram.Bot sendDocument method'''
print('Testing sendDocument - File')
message = self._bot.sendDocument(document=open('tests/telegram.png', 'rb'),
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(12948, message.document.file_size)
def testSendGIFURLDocument(self):
'''Test the telegram.Bot sendDocument method'''
print('Testing sendDocument - File')
message = self._bot.sendPhoto(photo=str('http://dummyimage.com/600x400/000/fff.gif&text=telegram'),
message = self._bot.sendPhoto(photo='http://dummyimage.com/600x400/000/fff.gif&text=telegram',
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(684, message.photo[0].file_size)
def testResendDocument(self):
'''Test the telegram.Bot sendDocument method'''
print('Testing sendDocument - Resend')
message = self._bot.sendDocument(document=str('BQADAQADHAADNTwtBxZxUGKyxYbYAg'),
message = self._bot.sendDocument(document='BQADAQADHAADNTwtBxZxUGKyxYbYAg',
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual('BQADAQADHAADNTwtBxZxUGKyxYbYAg', message.document.file_id)
def testSendVideo(self):
@@ -141,21 +186,24 @@ class BotTest(unittest.TestCase):
message = self._bot.sendVideo(video=open('tests/telegram.mp4', 'rb'),
caption='testSendVideo',
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(326534, message.video.file_size)
self.assertEqual('testSendVideo', message.caption)
def testResendVideo(self):
'''Test the telegram.Bot sendVideo method'''
print('Testing sendVideo - Resend')
message = self._bot.sendVideo(video=str('BAADAQADIgEAAvjAuQABOuTB937fPTgC'),
message = self._bot.sendVideo(video='BAADAQADIgEAAvjAuQABOuTB937fPTgC',
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(4, message.video.duration)
def testResendSticker(self):
'''Test the telegram.Bot sendSticker method'''
print('Testing sendSticker - Resend')
message = self._bot.sendSticker(sticker=str('BQADAQADHAADyIsGAAFZfq1bphjqlgI'),
message = self._bot.sendSticker(sticker='BQADAQADHAADyIsGAAFZfq1bphjqlgI',
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(39518, message.sticker.file_size)
def testSendLocation(self):
@@ -164,6 +212,7 @@ class BotTest(unittest.TestCase):
message = self._bot.sendLocation(latitude=-23.558873,
longitude=-46.659732,
chat_id=12173560)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(-23.558873, message.location.latitude)
self.assertEqual(-46.659732, message.location.longitude)
@@ -177,4 +226,5 @@ class BotTest(unittest.TestCase):
'''Test the telegram.Bot getUserProfilePhotos method'''
print('Testing getUserProfilePhotos')
upf = self._bot.getUserProfilePhotos(user_id=12173560)
self.assertTrue(self.is_json(upf.to_json()))
self.assertEqual(6547, upf.photos[0][0].file_size)