【问题标题】:TypeError: '_asyncio.Future' object is not subscriptable, using async motor driver for mongodbTypeError:“_asyncio.Future”对象不可下标,使用 mongodb 的异步电机驱动程序
【发布时间】:2021-12-17 15:12:51
【问题描述】:

我有一个代码,每当用户发布新消息时,我都会尝试更新他的数据:

@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
    else:
        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})
            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}})
        else:
            pass
    await bot.process_commands(message)
    asyncio.get_event_loop().run_until_complete(on_message(message))

但是,当它被激活时,我得到一个 TypeError:

Ignoring exception in on_message
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/app/bot.py", line 187, in on_message
message_coins = await coll.find_one({"_id": message.guild.id})["message_coins"]
TypeError: '_asyncio.Future' object is not subscriptable

如何修复这个 TypeError?

【问题讨论】:

  • 你正在尝试下标未来的对象,你需要在它周围加上括号来下标等待的对象,例如message_coins = (await coll.find_one({"_id": message.guild.id}))["message_coins"]
  • 非常感谢,但出现新错误:await asyncio.get_event_loop().run_until_complete(on_message(message)) RuntimeError: This event loop is already running
  • 这是一个新问题。您应该关闭此问题并打开一个新问题。

标签: python mongodb discord.py motordriver


【解决方案1】:

您的问题在于 python 将解释这行代码的性质

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

它将看到调用 coll 对象的 find_one 方法,使用下标获取“message_coins”元素,然后将该对象传递给await。然而,这并不是你真正想要的。

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

您需要在这里使用圆括号来强制执行操作顺序。因此,通过包装 await 和方法调用,它告诉 python 将其传递给 await,然后一旦您从 await 调用返回最终结果,您就可以使用下标来定位“message_coins”元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    • 2021-12-01
    相关资源
    最近更新 更多