使用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被无限递归调用,很快就会触发栈溢出、程序崩溃,必须删除。
修复步骤
- 给
await coll.find_one(...)整体加上括号,确保先等待异步查询返回结果字典,再取下标值 - 删除末尾的递归调用代码行
修正后的完整代码
@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,提问作者Чёткая ворона
相关产品推荐
相关产品推荐

