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
In the github of the project there is an example for that:
For those using python-telegram-bot, you can download a voice note like this: