首页 > 解决方案 > 在 Discord Bot (Python) 中无法捕获超时错误

问题描述

我目前正在为我自己的不和谐机器人工作(石头剪刀布游戏)

async def rps(ctx) :
    comp = rpslist[random.randint(0,2)]
    yet = discord.Embed(title=f"{ctx.message.author}'s Rock Paper Scissors {comp} Game!", description="Click on a button to start! Respond in 15 seconds.", color=0xFFEA00)
    win = discord.Embed(title=f"{ctx.message.author} won!", description = f"I have chosen {comp}.", color = 0x17ff0f)
    out = discord.Embed(title=f"{ctx.message.author}, you didn't respond in time!", description = "Make sure to click faster next time!")
    lose = discord.Embed(title=f"A bot is better than you.", description = f"I have chosen {comp}.", color = 0xff0000)
    tie = discord.Embed(title=f"You have the same level of cleverness as this bot", description = f"I chose {comp}.")
    m = await ctx.send(
      embed = yet, 
      components = [Button(style=1, label = "Rock"), Button(style=3, label = "Paper"), Button(style=ButtonStyle.red, label="Scissors")])
    def check(res):
        return ctx.message.author == res.user and res.channel == ctx.channel
    try:
        res = await client.wait_for("button_click", check=check, timeout=15)
        player = res.component.label
        if player == comp:
            await m.edit(embed=tie, components=[Button(label="Round ended", disabled=True)])
        elif player == "Rock" and comp == "Paper":
            await m.edit(embed=lose, components=[Button(label="Round ended", disabled=True)])
        elif player == "Rock" and comp == "Scissors":
            await m.edit(embed=win, components=[Button(label="Round ended", disabled=True)])
        elif player == "Paper" and comp == "Rock":
            await m.edit(embed=win, components=[Button(label="Round ended", disabled=True)])
        elif player == "Paper" and comp == "Scissors":
            await m.edit(embed=lose, components=[Button(label="Round ended", disabled=True)])
        elif player == "Scissors" and comp == "Rock":
            await m.edit(embed=lose, components=[Button(label="Round ended", disabled=True)])
        elif player == "Scissors" and comp == "Paper":
            await m.edit(embed=win, components=[Button(label="Round ended", disabled=True)])
   except TimeoutError:
    await m.edit(embed=out, components=[Button(label="Round ended", disabled=True)])

我已经尝试捕捉超时错误,但显然没有。有什么我需要添加或删除的吗?

注意:所有按钮都在这 15 秒内起作用,但在 15 秒后它不起作用。

标签: pythondiscord.py

解决方案


TimeoutError是异步的,所以要使用超时错误,您需要添加except asyncio.TimeoutError:


推荐阅读