首页 > 解决方案 > 如何在 python-telegram-bot 中获取 file_id(语音)?

问题描述

我对 python 电报机器人中的语音消息有疑问。如何从用户那里获取声音并在 python-telegram-bot 中处理这个声音?

标签: pythonpython-3.xtelegramtelegram-bot

解决方案


为语音文件处理程序尝试这样的事情

def voice_handler(update, context):
    bot = context.bot
    file = bot.getFile(update.message.voice.file_id)
    file.download('voice.mp3')

并在主函数中设置 MessageHandler ,如下所示:

def main():
    updater = Updater(token=lashi_bot,use_context=True)
    updater.dispatcher.add_handler(MessageHandler(Filters.voice, voice_handler))

正如您在此示例中看到的,您可以从中获取 file_id(voice):

update.message.voice.file_id

您需要的一切都在更新中,您可以像这样在函数中打印更新:

def voice_handler(update, context):
    bot = context.bot
    file = bot.getFile(update.message.voice.file_id)
    print(update)
    file.download('voice.mp3')

你会看到里面有什么,它很有用


推荐阅读