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

Need download voice message from Telegram on Python

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

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

获取更新 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}}}]}


我查看了 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))
print(type(file), file)
------------------------------------------------------------
Output: <class 'requests.models.Response'>, <Response [200]>


我还发现了一个 example,其中作者在 chunks 中下载了音频。具体怎么没看懂,不过用了一个类似的函数:

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

        yield chunk

        if not bytes:
            break

在项目的github中有一个example

@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)

对于那些使用 python-telegram-bot 的用户,您可以下载这样的语音留言:

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()