python - 在 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 秒后它不起作用。
解决方案
TimeoutError
是异步的,所以要使用超时错误,您需要添加except asyncio.TimeoutError:
推荐阅读
- java - 为什么几秒钟后我的刷新比开始后立即刷新要慢
- node.js - bulkWrite - 类型错误:无法在 applyTimestampsToUpdate 的数字 '0' 上创建属性 '$set' - mongoose 或 mongodb
- c# - WCF 客户端,XML 命名空间前缀导致空对象
- java - 如何为 ExecutorServices 编写测试用例?
- intellij-idea - IntelliJ 不会从 Lombok 找到生成的代码,而 gradle 会
- c# - 为什么我无法在 LINQ Select() 查询中向 StringBuilder 插入值
- python - 简单的数据操作:R vs python
- c# - 如何将范围应用于 NServiceBus 行为中间件中的日志
- web-component - 我什么时候可以在 `shadowRoot` 上使用 `querySelector`?
- python - SpaCy - ValueError:操作数无法与形状一起广播(1,2)(1,5)