按钮按下命令工作,但仍然显示交互失败;使用discord-components



代码做了应该做的事情,但是在每次按下按钮后它都显示"此交互失败"。按下该按钮可编辑嵌入以将其更改为另一个嵌入。我该如何消除按下按钮后出现的交互失败信息?

问题:https://i.stack.imgur.com/i4dTd.png

收到的代码来自:https://github.com/elixss/YouTube/blob/main/source/buttons.py

代码如下:

@bot.group(invoke_without_command=True)
async def help(ctx):
# buttons
one = Button(style=1, label="Commands", id="em1")
two = Button(style=1, label="Depression", id="em2")
three = Button(style=1, label="Moderator", id="em3")
four = Button(style=1, label="Language", id="em4")
# embeds
em1 = Embed(title="Commands Plugin",color=0x5865F2)
em2 = Embed(title="Depression Plugin", description="placeholder", color=0x5865F2)
em3 = Embed(title="Moderator Plugin", description="placeholder", color=0x5865F2)
em4 = Embed(title="Language Plugin", description="placeholder", color=0x5865F2)
# main help embed
help_embed = Embed(description="> **Help Module**nPress on any button to view the commands for that selected plugin.",
color=discord.Color.random())
# buttons to embeds
buttons = {
"em1": em1,
"em2": em2,
"em3": em3,
"em4": em4
}
msg = await ctx.send(embed=help_embed,
components=[[one, two, three, four]])
while True:
event = await bot.wait_for("button_click", timeout=60.0)
if event.channel is not ctx.channel:
return
if event.channel == ctx.channel:
response = buttons.get(event.component.id)
await msg.edit(embed=response)
if response is None:
await event.channel.send("error, try again.")

正如Elias所说,您必须响应交互,否则它将显示"此交互失败",但不是使用常规的ctx.send(),而是使用(在您的情况下)

await event.respond(type=4, message="Responded!")

如果您不想发送消息作为对按钮点击或选择的响应,您可以使用不带消息的type=6:

await event.respond(type=6)

更多类型,请参见文档。

最好的方法是在按下按钮后删除所有按钮,或者添加冷却时间,在一定时间后自动删除按钮。

在你的情况下,它看起来像这样:

msg = await ctx.send(embed=help_embed, components=[[one, two, three, four]])
try: 
res = await client.wait_for("button_click", timeout = 60)
except asyncio.TimeoutError:
await msg.edit(components = []) #removes buttons from message
else:
if res.author == message.author:
#when button is clicked
await msg.edit(components = [])

这也防止了速率限制,所以你不会有按钮一直等待响应。