Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need download voice message from Telegram on Python

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
like image 284
Иван Avatar asked Aug 08 '26 14:08

Иван


1 Answers

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)
like image 192
SergioR Avatar answered Aug 10 '26 11:08

SergioR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!