Discord.py -与多个按钮交互



我已经为我的Discord bot创建了一个带有按钮的命令。使用下面的当前代码,与蓝色按钮(button1)的交互工作得很好。绿色按钮(button3)的交互不工作。

如何在同一个命令中为不同的按钮创建不同的交互?

我正在使用discord.py和discord_components

@bot.command()
async def test(ctx):
await ctx.send(
"This is a button test.",
components=[
[
Button( 
style=ButtonStyle.blue,
custom_id="button1",
label="Blue button",
emoji="🚀",
),
Button(
style=ButtonStyle.red,
custom_id="button2",
label="Red button",
disabled=True,
emoji="🐺",
),
Button(
style=ButtonStyle.green,
custom_id="button3",
label="Green button",
emoji="😄",
),
]
]
)
blue = await bot.wait_for(
"button_click", check = lambda i: i.custom_id == "button1"
)
await blue.send(content="Button clicked!", ephemeral=False)
green = await bot.wait_for(
"button_click", check = lambda k: k.custom_id == "button3"
)
await green.send(content="Button smashed!", ephemeral=False)

机器人当前正在等待蓝色按钮被按下。然后绿色按钮工作。显然我希望他们同时工作。

您可以简单地检查按钮的自定义id是button1(蓝色)还是button3(绿色)

button = await bot.wait_for(
"button_click", check = lambda i: i.custom_id in ["button1", "button3"]
)
if button.custom_id == "button1":
await button.send(content="Button clicked!", ephemeral=False)
else:
await button.send(content="Button smashed!", ephemeral=False)

如果您希望按钮持续工作,请将上面的代码放入while循环

最新更新