需要在 Python 上从 Telegram 下载语音消息

Ива*_*ван 7 python python-requests telegram python-telegram-bot telegram-bot

我开始开发一个与电报机器人相关的宠物项目。问题之一是,如何从机器人下载语音消息?

任务:需要从电报机器人下载音频文件并保存在项目文件夹中。

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}}}]}
Run Code Online (Sandbox Code Playgroud)


我检查了pyTelegramBotAPI文档,但没有找到确切如何下载文件的解释。

我根据文档创建了代码:

@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))
Run Code Online (Sandbox Code Playgroud)
print(type(file), file)
------------------------------------------------------------
Output: <class 'requests.models.Response'>, <Response [200]>
Run Code Online (Sandbox Code Playgroud)


我还发现了一个例子,作者以块的形式下载音频。我不明白到底是怎么回事,但它使用了类似的功能

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

        yield chunk

        if not bytes:
            break
Run Code Online (Sandbox Code Playgroud)

Ser*_*ioR 5

在该项目的 github 中有一个示例

@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)
Run Code Online (Sandbox Code Playgroud)