discord.py按钮无法交互:AttributeError错误求助
我开发的Discord机器人已创建Embed和按钮,二者能正常显示,但点击按钮无法交互,触发错误:
AttributeError: 'Button' object has no attribute 'response'
相关代码
命令与视图实现
class Menu(discord.ui.View): def __init__(self): super().__init__() self.value = None @discord.ui.button(label="Send Message", style=discord.ButtonStyle.grey) async def menu1(self, button: discord.ui.Button, interaction: discord.Interaction): await interaction.response.send_message("Hello you clicked me") @Bot.command() async def embed_with_buttons(ctx): view = Menu() embed = discord.Embed(colour=0xFF5733, title="Title", type="rich", url=None, description="description", timestamp=None) await ctx.send(embed=embed, view=view)
导入语句
import discord from discord.ext import commands from utils import * from functions import * import time import interactions from discord.ui import Button from interactions import Button, ButtonStyle, SelectMenu, SelectOption import random
问题原因
核心冲突来自重复导入不同库的同名类:你同时从discord.ui(Discord.py原生库)和interactions第三方库导入了Button类,导致命名空间混乱。Discord.py的视图系统期望接收原生的discord.ui.Button对象,但实际传入的是interactions库的Button实例,后者并没有response属性,因此触发报错。
解决方案
方案1:移除不必要的库导入
如果你的机器人不需要使用interactions库,直接删除相关导入行即可:
# 删掉以下两行 import interactions from interactions import Button, ButtonStyle, SelectMenu, SelectOption
方案2:给冲突库的导入加别名
如果确实需要保留interactions库,通过别名区分两个库的同名类,避免冲突:
# 修改interactions相关的导入 import interactions as inter from interactions import Button as InterButton, ButtonStyle as InterButtonStyle, SelectMenu as InterSelectMenu, SelectOption as InterSelectOption
同时确保视图类中始终使用Discord.py原生的discord.ui.Button(当前代码中的装饰器和类型注解已经是正确的,无需修改)。
额外检查
确保你的机器人已启用消息内容意图:
- 登录Discord开发者门户,进入你的机器人应用
- 在「Bot」设置中开启「Message Content Intent」
- 初始化Bot时传入必要的意图:
# 示例:开启全部意图 Bot = commands.Bot(command_prefix="你的前缀", intents=discord.Intents.all()) # 或按需开启必要意图(至少包含message_content) intents = discord.Intents.default() intents.message_content = True Bot = commands.Bot(command_prefix="你的前缀", intents=intents)
内容的提问来源于stack exchange,提问作者MCGirgin
相关产品推荐
相关产品推荐

