Alex Kedrov Alex Kedrov - 1 year ago 255
JSON Question

How to use sendAudio in Telegram bot (Python)

I have a Telegram bot, it replies with text and images, but I have a problem with sending an MP3 file in the reply. Can anyone please help?

This part of code defines the reply:

def reply(msg=None, img=None, aud=None):
if msg:
resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
'chat_id': str(chat_id),
'text': msg.encode('utf-8'),
'disable_web_page_preview': 'false',
# 'reply_to_message_id': str(message_id),
'reply_markup': json_keyboard,
elif img:
resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
('chat_id', str(chat_id)),
('reply_to_message_id', str(message_id)),
], [
('photo', 'image.jpg', img),
elif aud:
resp = multipart.post_multipart(BASE_URL + 'sendAudio', [
('chat_id', str(chat_id)),
('reply_to_message_id', str(message_id)),
], [
('audio', 'aud.mp3', aud),
logging.error('no msg or img specified')
resp = None

And this one defines the type of message it should return:

elif 'Two' in text:
img ='statimg/firstf.jpg')
output = StringIO.StringIO(), 'JPEG')
elif 'Three' in text:
aud = open('statimg/firsta.mp3')
output = StringIO.StringIO(), 'MP3')
elif 'One' in text:
# json_keyboard = json.dumps({keym: [bline3]})
bline1 = [b1]
bline2 = [b2]
json_keyboard = json.dumps({keym: [bline1, bline2]})
if func6.state == 0:
reply('Hello text1')
elif func6.state == 1:
reply('Hello text2')

For "One" and "Two" in text ot works perfectly (returns text for "One" and image for "Two"), but for "Three" it doesn't return an mp3 file.

What could be the problem? Thanks a lot in advance!

Answer Source

Simply solved the issue this way:

        elif aud:
            resp = multipart.post_multipart(BASE_URL + 'sendAudio', [
                ('chat_id', str(chat_id)),
                #('caption', 'Music in the park'),
                ('reply_markup', json_keyboard),
            ], [
                ('audio', 'Play', aud),

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download