You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Discord.py中获取按钮点击者的用户信息?

如何追踪Discord机器人按钮的点击者?

嘿,我看你在尝试用discord-components库实现按钮点击者的追踪,思路是对的,但代码里有个关键错误需要修正,就能顺利拿到点击按钮的用户信息了。

你的代码问题所在

你在按钮点击的回调函数里写了interaction = buttons.click,这完全搞错了——buttons.click是用来注册回调的装饰器,不是用户点击按钮时产生的交互对象,自然拿不到author属性。

修正后的完整代码

async def bottoni(ctx):
    await buttons.send(
        content = "click!",
        channel = ctx.channel.id,
        components = [
            ActionRow([
                Button(
                    label="first",
                    style=ButtonType.Success,  # 简化写法:直接用类静态属性,无需实例化ButtonType()
                    custom_id = "button_one"
                ),
                Button(
                    label="second",
                    style=ButtonType.Danger,
                    custom_id = "button_two"
                )
            ])
        ]
    )

@buttons.click
async def button_one(interaction):
    # interaction是用户点击时传递的交互对象,包含点击者的所有信息
    print(f"{interaction.author} clicked the first button!")
    # 也可以更详细输出:print(f"{interaction.author.name}#{interaction.author.discriminator} clicked!")

@buttons.click
async def button_two(interaction):
    print(f"{interaction.author} clicked the second button!")

关键说明

  1. 交互对象的正确使用:当用户点击按钮时,discord-components会自动把Interaction对象传给你的回调函数,这个对象里的interaction.author就是点击按钮的用户对象,直接调用就能获取用户名、ID等信息。
  2. 参数命名可选:如果你习惯用ctx作为参数名也没问题,因为这里的ctx本质就是Interaction对象,所以ctx.author同样能拿到点击者信息,比如:
    @buttons.click
    async def button_one(ctx):
        print(ctx.author, " clicked!")
    
  3. 简化ButtonType写法:原代码里的ButtonType().Success可以简化为ButtonType.Success,因为这是库提供的类静态属性,不需要实例化ButtonType类。

这样修改后,当用户点击按钮时,你的控制台就会输出类似Username#1234 clicked the first button!的内容,完美实现追踪点击者的需求。

内容的提问来源于stack exchange,提问作者Sphe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 00:33:11