Discord Py 2.0按钮点击报错求助:AttributeError问题排查
问题排查与解决
错误原因
你的按钮回调函数参数顺序错误。在Discord.py 2.0中,discord.ui.button装饰的回调函数默认仅传入两个参数:self(当前View实例)和interaction(交互对象)。你将button放在第二个参数位置,导致实际传入的interaction被赋值给了button变量,执行button.disabled = True时本质是操作Interaction对象,而该对象没有disabled属性,因此抛出AttributeError。
修正后的代码
class Buttons(discord.ui.View): def __init__(self, *, timeout=180): super().__init__(timeout=timeout) @discord.ui.button(label="Blurple Button", style=discord.ButtonStyle.blurple) async def blurple_button(self, interaction: discord.Interaction): print('1') # 通过self获取当前按钮实例 self.blurple_button.disabled = True # 编辑消息更新视图,让客户端显示按钮状态变化 await interaction.response.edit_message(view=self)
正确使用按钮组件的核心要点
- 回调参数规范:按钮回调的标准签名为
async def 函数名(self, interaction: discord.Interaction),无需额外声明button参数。 - 获取按钮实例:要操作触发的按钮,可直接通过
self.按钮函数名获取(装饰器会将按钮实例绑定为View的属性,属性名与回调函数名一致)。 - 视图更新逻辑:修改按钮状态(禁用、修改标签等)后,必须通过
interaction.response.edit_message(view=self)更新消息视图,否则客户端不会同步状态变化。 - 超时控制:View的
timeout参数控制按钮有效时长,超时后按钮自动失效;如需永久有效,可设置timeout=None(注意内存占用问题)。
内容的提问来源于stack exchange,提问作者Gwindi 555
相关产品推荐
相关产品推荐

