skip to Main Content

I started developing a pet project related to telegram bot. One of the points was the question, how to download a voice message from the bot?

Task: Need to download a audiofile from telegram bot and save in project folder.

GetUpdates
https://api.telegram.org/bot/getUpdates:

{"duration":2,"mime_type":"audio/ogg","file_id":"<file_id>","file_unique_id":"<file_unique_id>","file_size":8858}}}]}

I checked pyTelegramBotAPI documentation, but I didn’t find an explanation for exactly how to download the file.

I created the code based on the documentation:

@bot.message_handler(content_types=['voice'])
def voice_processing(message):
    file_info = bot.get_file(message.voice.file_id)
    file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(cfg.TOKEN, file_info.file_path))
print(type(file), file)
------------------------------------------------------------
Output: <class 'requests.models.Response'>, <Response [200]>

I also found one example where the author downloaded audio in chunks. How exactly I did not understand, but it used a similar function:

def read_chunks(chunk_size, bytes):
    while True:
        chunk = bytes[:chunk_size]
        bytes = bytes[chunk_size:]

        yield chunk

        if not bytes:
            break

2

Answers


  1. In the github of the project there is an example for that:

    @bot.message_handler(content_types=['voice'])
    def voice_processing(message):
        file_info = bot.get_file(message.voice.file_id)
        downloaded_file = bot.download_file(file_info.file_path)
        with open('new_file.ogg', 'wb') as new_file:
            new_file.write(downloaded_file)
    
    Login or Signup to reply.
  2. For those using python-telegram-bot, you can download a voice note like this:

    from telegram import Update
    from telegram.ext import Updater, CallbackContext, MessageHandler, Filters
    
    
    def get_voice(update: Update, context: CallbackContext) -> None:
        # get basic info about the voice note file and prepare it for downloading
        new_file = context.bot.get_file(update.message.voice.file_id)
        # download the voice note as a file
        new_file.download(f"voice_note.ogg")
    
    updater = Updater("1234:TOKEN")
    
    # Add handler for voice messages
    updater.dispatcher.add_handler(MessageHandler(Filters.voice , get_voice))
    
    updater.start_polling()
    updater.idle()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search