我可以使机器人全局检查 return 成为有用的值而不是布尔值吗?

Can I make a bot global check return a useful value instead of a bool?

我正在尝试通过 @bot.check 装饰器在 Python 中对我的 Discord 机器人实施全局检查。

检查的目的是验证命令作者的 ID 是否可以在 MongoDB 集合中找到,如果是,则提取相关数据。

我想完成的是将提取的数据传递给实际命令,从而避免再次查询数据库。

根据 discord.py 文档,check() 装饰器只能将结果评估为类似 True 或 False 的值,并在后一种情况下引发 CheckFailure

这是我的情况的简化示例:

@bot.check
async def is_member(ctx):
    member = mongo_collection.find_one({"_id": ctx.author.id}) # first query
    if member is None:
        await ctx.send("You need to join the community first!")
    return member

@bot.command()
async def my_command(ctx):
    member = mongo_collection.find_one({"_id": ctx.author.id}) # redundant
    ...

理论上我可以为此目的定义一个自定义装饰器,但是我必须在每个命令之前指定它。 我什至可以创建一个 Bot 子类来覆盖检查方法和装饰器,但我认为对于这样一个简单的问题来说有点过劳了。

你不能真的那样做,但你可以创建自己的实例变量

@bot.check
async def is_member(ctx):
    member = mongo_collection.find_one({"_id": ctx.author.id}) # first query
    ctx.mongo_member = member 
    return member is not None


@bot.command()
async def my_command(ctx):
    member = ctx.mongo_member
    ...