我收到一个小游戏命令的等待外部产量错误

时间:2021-05-18 03:18:13

标签: python discord discord.py

我在我的一个齿轮上设置了一个小游戏,但我收到了这个错误,discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Games' raised an error: SyntaxError: 'await' outside async function (Games.py, line 78) 不过这个命令在我的 main.py 中工作正常。我的代码在下面,谢谢!

@commands.command()
    async def numbergame(self, ctx):

      channel = ctx.channel
      await channel.send("Guess the number from 0-100 by writing the number in this channel!")
 
      number = random.randint(1,100)
 
      def check(m):
        return m.content.isdigit() and m.channel == channel and m.author == ctx.author
  
        while True:
           try:
               msg = await self.bot.wait_for('message', timeout=30.0, check=check)
           except asyncio.TimeoutError:
               return await channel.send(f"{ctx.author.mention}, You are late to guess!")
           guess = int(msg.content)
           if guess == number:
               return await channel.send(f"Correct answer! {ctx.author.mention}")
           elif guess > number:
               await channel.send(f"{ctx.author.mention}, Your guess was too high!")
           elif guess < number:
               await channel.send(f"{ctx.author.mention}, Your guess was too low!")

1 个答案:

答案 0 :(得分:2)

您的 while 循环在 check 函数内,而它假定在 numbergame 函数内。尝试按如下方式取消缩进 while 循环:

@commands.command()
async def numbergame(self, ctx):
    channel = ctx.channel
    await channel.send("Guess the number from 0-100 by writing the number in this channel!")
 
    number = random.randint(1,100)
 
    def check(m):
        return m.content.isdigit() and m.channel == channel and m.author == ctx.author
  
    while True:
        try:
            msg = await self.bot.wait_for('message', timeout=30.0, check=check)
        except asyncio.TimeoutError:
            return await channel.send(f"{ctx.author.mention}, You are late to guess!")
        
        guess = int(msg.content)
        if guess == number:
            return await channel.send(f"Correct answer! {ctx.author.mention}")
        elif guess > number:
            await channel.send(f"{ctx.author.mention}, Your guess was too high!")
        elif guess < number:
            await channel.send(f"{ctx.author.mention}, Your guess was too low!")