Discord Python开发:按钮点击触发其他同标签按钮问题求助
问题原因
- 现有
check校验规则仅验证触发用户和所在频道,未限制点击的按钮属于当前命令生成的embed消息,同频道同用户触发的任意按钮点击事件都会被当前wait_for捕获,导致跨消息触发 - 代码存在变量名不匹配问题,按钮标签赋值给了
user变量,但后续判断使用未定义的player变量,运行时会抛出异常 - 未对按钮交互做响应处理,点击后Discord前端会提示交互失败
修复方案
在check逻辑中新增消息ID匹配规则,确保只有当前命令生成的消息上的按钮触发才会被捕获,同时修正变量错误和交互响应逻辑即可。
修改后完整代码
async def open(ctx): blue = ["Possibly", "No"] blueresult = random.choice(blue) em = discord.Embed(title= f"Congratulations!",description =f"The result is **{blueresult}**!",color = discord.Color.blue()) yes = Button(style=ButtonStyle.green, label="Yes") no = Button(style=ButtonStyle.red, label="No") # 先发送消息拿到消息ID,再构造校验规则 m = await ctx.send(embed = em,components=[[no,yes]]) def check(res): # 新增消息ID匹配校验 return ctx.author == res.user and res.channel == ctx.channel and res.message.id == m.id res = await client.wait_for("button_click", check=check) # 响应交互,避免前端报错 await res.respond() # 修正变量名不匹配问题 player = res.component.label if player=="Yes": await m.edit(embed=em,components=[]) elif player=="No": await m.edit(embed=em,components=[])
内容的提问来源于stack exchange,提问作者Richardx_
相关产品推荐
相关产品推荐

