Tony
Tony

Reputation: 29

Is there a way to use an async check function for discord.py wait_for()?

I would like to use an async check function:

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

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

This yields an error message that says the check function isn't awaited:

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

If I change the code to:

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

I get the following error message:

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

Is there any way to have an async check function? Thanks!

Upvotes: 2

Views: 1266

Answers (3)

seven eighty
seven eighty

Reputation: 38

Try this:

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 = self.bot.wait_for("message", check=check)

and there is an example:

import asyncio

@commands.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 self.bot.wait_for("raw_reaction_add", check=check)

    ...

This work for me

Upvotes: 1

Tri
Tri

Reputation: 73


    async def predicate(ctx):
        # you can use any async code here
        result = await stuff()
        return result
    return commands.check(predicate)

Just add async in from to use await features..

Also when you call the function use Await in front

r = await predicate()

Upvotes: 2

PaxxPatriot
PaxxPatriot

Reputation: 116

You can use the following code as an example to write an async check:

def mycheck():
    async def predicate(ctx):
        # you can use any async code here
        result = await stuff()
        return result
    return commands.check(predicate)

More information can be found here: discord.py docs

Upvotes: 1

Related Questions