I’m working on a Python Telegram bot that can send text messages and photos without any issues. However, I’m struggling to get audio file sending to work properly. The bot should send an MP3 file when users trigger a specific command, but nothing happens.
Here’s my message handler function:
def send_response(message=None, photo=None, sound=None):
if message:
response = urllib2.urlopen(API_URL + 'sendMessage', urllib.urlencode({
'chat_id': str(user_id),
'text': message.encode('utf-8'),
'disable_web_page_preview': 'false',
'reply_markup': keyboard_json,
})).read()
elif photo:
response = multipart.post_multipart(API_URL + 'sendPhoto', [
('chat_id', str(user_id)),
('reply_to_message_id', str(msg_id)),
], [
('photo', 'pic.jpg', photo),
])
elif sound:
response = multipart.post_multipart(API_URL + 'sendAudio', [
('chat_id', str(user_id)),
('reply_to_message_id', str(msg_id)),
], [
('audio', 'track.mp3', sound),
])
And here’s how I handle different message types:
if 'option_a' in message:
send_response(message='Welcome message here')
elif 'option_b' in message:
pic = Image.open('files/sample.jpg')
buffer = StringIO.StringIO()
pic.save(buffer, 'JPEG')
send_response(photo=buffer.getvalue())
elif 'option_c' in message:
audio_file = open('files/sample.mp3')
buffer = StringIO.StringIO()
audio_file.save(buffer, 'MP3')
send_response(sound=buffer.getvalue())
Text and image responses work great, but the audio sending fails completely. Any ideas what might be wrong with my approach?