繁体   English   中英

有没有办法对discord.py wait_for使用异步检查功能?

[英]Is there a way to use an async check function for discord.py wait_for?

我想要一种改变的方法

async def check(reaction, user):
   await x
   return y

await self.bot.wait_for('reaction_add', check=check)

这会产生一条错误消息,指出不等待检查函数:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionFailed: Extension 'cogs.boost' raised an error: SyntaxError: 'await' outside async function 

如果我将代码更改为:

async def check(reaction, user):
   await x
   return y
await self.bot.wait_for('reaction_add', check=await check)

我收到以下错误消息:

TypeError: object function can't be used in 'await' expression

有什么办法可以有异步检查功能吗? 谢谢!当前帮助命令到自定义命令,在我的机器人中使用 discord.py

从深入研究代码(在 discord.py 1.5.1 上),似乎没有办法使用协程作为检查函数。 可能存在一种 hacky 解决方法,但这不是最佳实践,并且会导致比您通过实施它解决的问题更多的问题。 如果您想使用check ,只需编写执行检查的函数的同步版本,并确保使其尽可能高效以避免阻塞。

尝试这个:

import asyncio
@...
async def your_command(ctx, ...):

    async def run():
        # you can use await there
        return ...


    def check(msg):
        result = asyncio.create_task(run()) # run the async function
        return resul

    ctx = client.wait_for("message", check=check)

有一个例子:

import asyncio

@client.command()
async def test(ctx):

    async def run(msg):
        await msg.send("This message is not yours!", hidden=True)
        return


    def check(msg):

        if msg.author.id == ctx.author.id:
            return True
        else:
            asyncio.create_task(run(msg))
            return False

    ctx = await client.wait_for("raw_reaction_add", check=check)

    ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM