How to send audio files to users in Telegram bot with python-telegram-bot library

I’m working on a Telegram bot using Python and the python-telegram-bot library. Everything works fine with text messages, but now I want to send audio messages to users.

Here’s what I have so far:

def welcome_handler(update, context):
    tts_engine = pyttsx3.init()
    tts_engine.save_to_file('Hello and welcome to our bot', 'audio_message.mp3')
    tts_engine.runAndWait()
    
    # Need help here - how to send the audio file?

The MP3 file gets created successfully, but I’m stuck on how to actually send this audio file to the user who triggered the command. What’s the proper way to send voice messages or audio files through the bot?

hit this same issue yesterday! try send_document() if the other methods fail - telegram can be picky about audio formats. also double-check your mp3 file isn’t corrupted. I’ve had pyttsx3 create broken files that telegram just silently rejects.

Use the send_audio() method from the bot API. Generate your MP3 file, open it, and pass it to the method:

def welcome_handler(update, context):
    tts_engine = pyttsx3.init()
    tts_engine.save_to_file('Hello and welcome to our bot', 'audio_message.mp3')
    tts_engine.runAndWait()
    
    with open('audio_message.mp3', 'rb') as audio_file:
        context.bot.send_audio(chat_id=update.effective_chat.id, audio=audio_file)

Open the file in binary mode (‘rb’) or you’ll get encoding errors. I’ve used this for months in my bot - works great. Don’t forget to clean up the files afterward so you don’t fill up your server storage.

Actually, there’s another approach that might work better depending on what you’re doing. You could use BytesIO to handle the audio in memory instead of saving to disk first. But since pyttsx3 needs a file anyway, you’ll still need the file approach I showed above.

One thing though - if you’re sending the same welcome message a lot, just generate it once and reuse it. Don’t recreate it every time. Also, make sure you clean up those temp files properly with a try/finally block or context manager. You don’t want files hanging around if something breaks during the send.

For voice messages specifically (the ones that show up as voice notes), use send_voice() instead of send_audio(). send_voice() creates those circular voice bubbles users can play inline, while send_audio() just sends a regular audio file attachment.