You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PTB 13.15:Telegram录制音频无法触发handle_audio回调问题咨询

问题原因与解决方案

问题根源

Telegram对两类音频消息的类型定义不同:

  • 本地上传的音频文件属于audio类型
  • 实时录制的语音消息属于voice类型

你当前仅注册了Filters.audio的消息处理器,所以录制的语音消息无法触发handle_audio回调。

解决方法

方法一:同时处理两种类型

修改消息处理器的过滤器,用逻辑或同时匹配audio和voice类型:

def main():
    updater = Updater(TOKEN, use_context=True)
    dp = updater.dispatcher

    # Register handlers
    dp.add_handler(CommandHandler("start", start))
    # 同时匹配音频文件和语音消息
    dp.add_handler(MessageHandler(Filters.audio | Filters.voice, handle_audio))
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

在回调函数中可区分两种消息类型:

def handle_audio(update, context):
    msg = update.effective_message
    if msg.audio:
        # 处理上传的音频文件
        file_id = msg.audio.file_id
        print(f"收到上传音频,文件ID:{file_id}")
    elif msg.voice:
        # 处理录制的语音消息
        file_id = msg.voice.file_id
        print(f"收到录制语音,文件ID:{file_id}")
    # 统一执行下载等后续操作
    context.bot.get_file(file_id).download()

方法二:分开处理两种类型

如果需要对上传音频和录制语音执行不同逻辑,可分别注册两个处理器:

def main():
    updater = Updater(TOKEN, use_context=True)
    dp = updater.dispatcher

    # Register handlers
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(MessageHandler(Filters.audio, handle_uploaded_audio))
    dp.add_handler(MessageHandler(Filters.voice, handle_recorded_voice))
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

随后分别实现handle_uploaded_audio和handle_recorded_voice两个回调函数即可。

内容的提问来源于stack exchange,提问作者BaruchLi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 03:09:58