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

如何下载用户发送给Telegram bot的文件?文档消息handler未触发怎么解决

问题原因及修复方案

  • 第一个核心问题:消息处理器的入参类型错误,@dp.message_handler 装饰的异步函数第一个入参必须是 types.Message 对象,而非直接传入 types.File,参数类型不匹配会直接导致 handler 匹配失败,无法触发执行。
  • 第二个隐藏问题:bot.download_file 是异步方法,必须加 await 关键字调用,否则不会实际执行下载逻辑。
  • 附加优化点:可以先判断文件后缀是否为PDF,避免下载其他类型的文档。

修正后的可运行代码如下:

@dp.message_handler(content_types=types.ContentType.DOCUMENT)
async def scan_message(message: types.Message):
    print("downloading document")
    # 从消息对象中获取文档信息
    document = message.document
    # 可选校验:仅处理PDF格式文件
    if not document.file_name.lower().endswith(".pdf"):
        await message.answer("仅支持接收PDF格式文件")
        return
    # 获取文件对象
    file = await bot.get_file(document.file_id)
    file_path = file.file_path
    destination = r"C:\users\aleks\PycharmProjects\pythonProject\file.pdf"
    # 异步方法必须加await调用
    await bot.download_file(file_path, destination)
    print("success")
    await message.answer("PDF文件已下载完成")

如果你使用的是aiogram 3.x版本,装饰器写法需要调整为@dp.message(F.document),核心获取文件、下载的逻辑保持一致即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:06:04