如何在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!")
关键说明
- 交互对象的正确使用:当用户点击按钮时,
discord-components会自动把Interaction对象传给你的回调函数,这个对象里的interaction.author就是点击按钮的用户对象,直接调用就能获取用户名、ID等信息。 - 参数命名可选:如果你习惯用
ctx作为参数名也没问题,因为这里的ctx本质就是Interaction对象,所以ctx.author同样能拿到点击者信息,比如:@buttons.click async def button_one(ctx): print(ctx.author, " clicked!") - 简化ButtonType写法:原代码里的
ButtonType().Success可以简化为ButtonType.Success,因为这是库提供的类静态属性,不需要实例化ButtonType类。
这样修改后,当用户点击按钮时,你的控制台就会输出类似Username#1234 clicked the first button!的内容,完美实现追踪点击者的需求。
内容的提问来源于stack exchange,提问作者Sphe
相关产品推荐
相关产品推荐

