【问题标题】:Discord Python button press triggers all buttons in a commandDiscord Python按钮按下触发命令中的所有按钮
【发布时间】:2021-10-11 23:23:38
【问题描述】:

我正在尝试在 Python 中为 Discord 创建一个机器人。但是,我遇到了新添加的按钮的问题。问题如下:我多次使用一个命令,这会导致多个带有按钮的嵌入,但是当我按下其中一个嵌入中的按钮时,也会触发另一个嵌入中具有相同标签的按钮。

我想要的行为是让按钮仅在被点击的嵌入中触发。

我的代码是

async def open(ctx):
    def check(res):
        return ctx.author == res.user and res.channel == ctx.channel
    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")
    m = await ctx.send(embed = em,components=[[no,yes]])
    res = await client.wait_for("button_click", check=check)
    user = res.component.label

    if player=="Yes":
        await m.edit(embed=em,components=[])
    elif player=="No":
        await m.edit(embed=em,components=[])

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    您可以将检查功能更改为:

    def check(res):
        return ctx.author == res.user and res.channel == ctx.channel and m == res.message
    

    但是你必须把它放在这段代码下面:

    yes = Button(style=ButtonStyle.green, label="Yes")
    no = Button(style=ButtonStyle.red, label="No")
    m = await ctx.send(embed = em,components=[[no,yes]])
    

    所以结果应该是:

    yes = Button(style=ButtonStyle.green, label="Yes")
    no = Button(style=ButtonStyle.red, label="No")
    m = await ctx.send(embed = em,components=[[no,yes]])
    def check(res):
        return ctx.author == res.user and res.channel == ctx.channel and m == res.message
    

    新代码检查机器人发送的嵌入消息是否是响应消息。我测试了它,它对我有用。

    【讨论】:

    • 谢谢!像魅力一样工作
    • @Richardx_ 没问题!
    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 2018-02-07
    • 1970-01-01
    相关资源
    最近更新 更多