python-telegram-bot下载文件报coroutine无download属性错误
问题产生原因
报错的核心原因是异步调用时await关键字位置错误,不符合python-telegram-bot v20全异步版本的调用规则:
- 执行顺序错误:你报错的语句
await context.bot.get_file(update.message.document).download(f'./R{p}.txt')中,Python会先执行context.bot.get_file(update.message.document),这个方法本身是异步协程,不加await的话返回值是协程对象,而非真实的File实例;后续直接在协程对象上调用.download(),协程对象不存在download属性,因此直接抛出AttributeError,外层的await根本没有执行到。 - 多余的await:你贴的功能代码里给
update.message.document加了await属于无效写法,update.message.document是消息对象上的同步属性,存储用户发送的文件元数据,不是可等待的协程对象,不需要加await。 - 版本适配提示:python-telegram-bot v20正式版中,
File类的本地保存方法已经从旧版的download()重命名为download_to_drive(),你使用的20.0a1预览版如果调用download()提示方法不存在,直接替换为新方法名即可。
解决方法
调整await的位置,先等待get_file()执行完成拿到真实的File对象,再调用下载方法,修正后的完整代码如下:
async def Getfile(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: global p, usres # 可选:增加消息类型校验,避免非文件消息触发报错 if not update.message.document: await update.message.reply_text("请发送txt格式文件") return if not update.message.document.file_name.endswith('.txt'): await update.message.reply_text("仅支持接收txt格式文件") return # 先await获取文件对象,再执行下载 tg_file = await context.bot.get_file(update.message.document) # 若download方法报错,替换为 await tg_file.download_to_drive(f'./R{p}.txt') await tg_file.download(f'./R{p}.txt') await update.message.reply_text(f"file saved as R{p}.txt") usres[int(update.message.from_user.id)] = p with open("data.json", "w") as f: json.dump(usres, f, indent=4) p += 1 print("ok")
内容的提问来源于stack exchange,提问作者mehdi_ahmadi
相关产品推荐
相关产品推荐

