【问题标题】:Is there a way to use an async check function for discord.py wait_for()?有没有办法为 discord.py wait_for() 使用异步检查功能?
【发布时间】:2020-12-06 13:30:43
【问题描述】:

我想使用异步检查功能:

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

有什么办法可以有异步检查功能吗?谢谢!

【问题讨论】:

  • 您为什么要删除有关此为不和谐 API 的信息?没有它,这个问题就没有意义。
  • 这篇文章被标记为discord.py,并且discord.py在标题中
  • 那是因为我恢复了您昨天的编辑,删除了标签和标题中的提及....

标签: python async-await discord discord.py discord.py-rewrite


【解决方案1】:

您可以使用以下代码作为示例来编写异步检查:

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

更多信息可以在这里找到:discord.py docs

【讨论】:

    【解决方案2】:
    
        async def predicate(ctx):
            # you can use any async code here
            result = await stuff()
            return result
        return commands.check(predicate)
    
    

    只需添加 async in from 即可使用 await 功能..

    另外,当你调用函数时,在前面使用 Await

    r = 等待谓词()

    【讨论】:

      【解决方案3】:

      试试这个:

      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)
      

      还有一个例子:

      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)
      
          ...
      

      这对我有用

      【讨论】:

        猜你喜欢
        • 2021-02-16
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多