Need download voice message from Telegram on Python
Asked Answered
H

2

7

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
Holley answered 4/6, 2020 at 2:27 Comment(0)
B
5

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)
Bioclimatology answered 4/6, 2020 at 9:42 Comment(0)
F
0

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()
Finalist answered 9/5, 2022 at 20:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.