Skip to content

Commit

Permalink
Adding support for Voice object and sendVoice method #39
Browse files Browse the repository at this point in the history
  • Loading branch information
leandrotoledo committed Aug 17, 2015
1 parent 686aecb commit 6e2881b
Show file tree
Hide file tree
Showing 8 changed files with 182 additions and 18 deletions.
4 changes: 3 additions & 1 deletion telegram/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
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
Expand All @@ -48,4 +49,5 @@
'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 changes: 10 additions & 0 deletions telegram/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,33 @@ 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

@staticmethod
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:
Expand Down
73 changes: 70 additions & 3 deletions telegram/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,12 +262,21 @@ def sendPhoto(self,
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:
Expand All @@ -276,6 +285,12 @@ def sendAudio(self,
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:
Expand All @@ -292,6 +307,13 @@ def sendAudio(self,
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
Expand Down Expand Up @@ -409,6 +431,51 @@ def sendVideo(self,

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,
Expand Down
5 changes: 4 additions & 1 deletion telegram/inputfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ def __init__(self,
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()
Expand Down Expand Up @@ -145,7 +148,7 @@ def is_inputfile(data):
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:
Expand Down
11 changes: 11 additions & 0 deletions telegram/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def __init__(self,
photo=None,
sticker=None,
video=None,
voice=None,
caption=None,
contact=None,
location=None,
Expand All @@ -59,6 +60,7 @@ def __init__(self,
self.photo = photo
self.sticker = sticker
self.video = video
self.voice = voice
self.caption = caption
self.contact = contact
self.location = location
Expand Down Expand Up @@ -142,6 +144,12 @@ def de_json(data):
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'])
Expand Down Expand Up @@ -179,6 +187,7 @@ def de_json(data):
photo=photo,
sticker=sticker,
video=video,
voice=voice,
caption=data.get('caption', ''),
contact=contact,
location=location,
Expand Down Expand Up @@ -222,6 +231,8 @@ def to_dict(self):
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:
Expand Down
49 changes: 49 additions & 0 deletions telegram/voice.py
Original file line number Diff line number Diff line change
@@ -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 added tests/telegram.mp3
Binary file not shown.
48 changes: 35 additions & 13 deletions tests/test_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,50 +89,72 @@ def testSendPhoto(self):
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)
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(9199, message.audio.file_size)
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.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.audio.file_id)
self.assertEqual('AwADAQADIQEAAvjAuQABSAXg_GhkhZcC', message.voice.file_id)

def testSendDocument(self):
'''Test the telegram.Bot sendDocument method'''
Expand All @@ -145,15 +167,15 @@ def testSendDocument(self):
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)
Expand All @@ -171,15 +193,15 @@ def testSendVideo(self):
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)
Expand Down

0 comments on commit 6e2881b

Please sign in to comment.