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

使用MongoDB异步驱动motor时出现_asyncio.Future对象不可下标错误如何解决

问题修复方案

错误原因

报错是因为await关键字的运算优先级低于下标取值[],原代码执行顺序是先对coll.find_one(...)返回的未等待的_asyncio.Future对象执行["message_coins"]下标操作,而Future对象本身不支持下标取值,因此抛出TypeError。

同时你的代码还存在一个致命逻辑错误:事件函数末尾的asyncio.get_event_loop().run_until_complete(on_message(message))会导致on_message被无限递归调用,很快就会触发栈溢出、程序崩溃,必须删除。

修复步骤

  1. 给await coll.find_one(...)整体加上括号,确保先等待异步查询返回结果字典,再取下标值
  2. 删除末尾的递归调用代码行

修正后的完整代码

@bot.event
async def on_message(message):
    if isinstance(message.channel, discord.DMChannel):
        return
    collection = db[f"{message.guild.id}"]
    coll = db.guilds
    if message.author.bot:
        return
    if message.channel.id != 796145301013397544:
        if not await coll.count_documents({"_id": message.guild.id}):
            await coll.insert_one({"_id": message.guild.id, "suggest_channel": "None", "message_coins": 0.5, "log_channel": "None", 'prefix': '.', 'ignore_channel': 'None', 'likes': 0})
        # 核心修正:给await查询部分加括号,先等待返回结果再取字段
        message_coins = (await coll.find_one({"_id": message.guild.id}))["message_coins"]
        if not await collection.count_documents({"_id": message.author.id}):
            await collection.insert_one({"_id": message.author.id, "msg": 0, "happy": 0, "coins": 0, "badge": "Нет", "cookie": 0, "minvoice": 0, "color": 0xFFFFFF, "osebe": "Отсутствует", "age": "Неизвестно"})
        await collection.update_one({"_id": message.author.id}, {"$inc": {"msg": 1}})
        await collection.update_one({"_id": message.author.id}, {"$inc": {"coins": message_coins}})
    await bot.process_commands(message)

优化建议

如果想要更高的代码可读性,也可以提前把查询结果赋值给变量再取字段:

guild_config = await coll.find_one({"_id": message.guild.id})
message_coins = guild_config["message_coins"]

内容的提问来源于stack exchange,提问作者Чёткая ворона

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:24:01