首页 > 解决方案 > Discord.py 按钮交互在用户单击时失败

问题描述

我正在尝试使用按钮为 Discord Bot 创建验证功能。我已经尝试创建它,但不确定它是否有效(测试目的)。

我需要它来提供一个角色来验证一个用户,比如一个名为 Verified 的角色,还想要一个关于我如何使它不是命令的建议,只是让它嵌入到一个新成员可以简单地点击它的单个频道中并获取要验证的角色。

我在开发控制台中没有收到任何错误,只是说当我单击 UI(Discord 应用程序)中的按钮时,我收到一条消息说“交互失败”。

@client.command()
async def verify(ctx):
    member = ctx.message.author
    role = get(member.guild.roles, name="Sexy EGirl")
    await ctx.send(
        embed = discord.Embed(description="Click below to verify", color=getcolor(client.user.avatar_url)),
        components = [
            Button(style=ButtonStyle.blue, label = 'Verify')
        ]
        )
    interaction = await client.wait_for("button_click", check=lambda i: i.component.label.startswith("Verify"))
    await interaction.respond(member.add_roles(role))

标签: pythondiscord

解决方案


如果您不发送响应消息,则会收到“交互失败”。

@client.event
async def on_button_click(interaction):

    message = interaction.message
    button_id = interaction.component.id
    if button_id == "verify_button":
        member = message.guild.get_member(interaction.user.id)
        role = message.guild.get_role(859852728260231198)  # replace role_id with your roleID
        await member.add_roles(role)

        response = await interaction.respond(embed=discord.Embed(title="Verified"))


@client.command()
@commands.has_permissions(administrator=True) # you need to import command from discord.ext if you want to use this -> from discord.ext import commands
async def verify(ctx):
    await ctx.send(
        embed=discord.Embed(title="Embed - Title", description="Click below to verify"),
        components=[
            Button(style=ButtonStyle.blue, label='Verify', custom_id="verify_button")
        ])

使用此代码,您可以在频道中发送带有验证按钮的嵌入。(如果您有管理员权限)然后用户可以按下按钮并触发 on_button_click 事件。

要处理交互失败,您将发送响应消息。


推荐阅读