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

使用python-telegram-bot下载MP3文件时遇AttributeError错误求助

解决python-telegram-bot下载MP3时的AttributeError问题

错误原因

你碰到的AttributeError: 'NoneType' object has no attribute 'file_name',根源在于代码里用了filters.ALL作为消息过滤器——这个过滤器会让所有类型的消息(文本、图片、语音、甚至系统通知)都触发music_handler函数。当收到非文档类消息时,update.message.document就是None,自然没法调用file_name属性,直接报错。

修正方案

只需要调整消息过滤器,同时在处理函数里增加必要的校验,就能解决这个问题。以下是完整的修正代码:

from typing import Final
from telegram import Update
from telegram.ext import Application, ContextTypes, MessageHandler, filters

TOKEN: Final = '....'

async def music_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 先确认消息里有文档对象
    if not update.message.document:
        await update.message.reply_text("请发送MP3文件(文档类型)")
        return
    
    # 可选:精准校验是否为MP3格式
    file_name = update.message.document.file_name
    if not file_name.lower().endswith('.mp3'):
        await update.message.reply_text("请发送MP3格式的文件")
        return
    
    try:
        new_file = await update.message.effective_attachment.get_file()
        await new_file.download_to_drive(file_name)
        await update.message.reply_text(f"{file_name} 已成功保存")
    except Exception as e:
        await update.message.reply_text(f"保存失败:{str(e)}")

if __name__ == '__main__':
    app = Application.builder().token(TOKEN).build()
    # 方案1:监听所有文档类型消息
    app.add_handler(MessageHandler(filters.Document.ALL, music_handler))
    
    # 方案2:只监听MP3格式的文档(更精准)
    # app.add_handler(MessageHandler(filters.Document.MimeType("audio/mpeg"), music_handler))
    
    app.run_polling(poll_interval=3)

关键修改说明

  • 替换消息过滤器:把filters.ALL换成filters.Document.ALL,只让文档类消息触发处理函数;如果想更精准,直接用filters.Document.MimeType("audio/mpeg")只接收MP3文件。
  • 增加存在性检查:先判断update.message.document是否存在,避免非文档消息导致的报错。
  • 格式校验(可选):通过文件名后缀校验确保只处理MP3文件,避免无效文件流入。
  • 异常捕获:用try-except包裹下载逻辑,处理网络异常等意外情况,给用户明确的反馈。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:03:11