重装py-cord后Discord机器人斜杠命令、事件及按钮失效求助
问题排查与解决方案
1. AttributeError: 'Bot' object has no attribute 'slash_command' 错误
原因:同时安装了discord.py(即discord库)和py-cord,Python优先导入了原生discord.py的Bot类——该类不支持slash_command装饰器,只有py-cord的扩展提供此功能。
解决步骤:
- 卸载冲突库,重装py-cord:
pip uninstall discord.py discord -y pip install py-cord --upgrade - 确保代码导入的是py-cord的模块:
from discord.ext import commands import discord bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
2. 成员加入/离开事件无执行反馈
原因:未开启成员事件对应的网关权限(Intents),Discord不会主动推送这类事件给机器人。
解决步骤:
- 代码中启用成员Intents:
intents = discord.Intents.default() intents.members = True # 必须开启此项才能接收成员相关事件 bot = commands.Bot(command_prefix="!", intents=intents) - 配置Discord开发者后台:
- 进入你的机器人应用的
Bot页面 - 在
Privileged Gateway Intents区域开启Server Members Intent,保存设置
- 进入你的机器人应用的
3. 按钮功能验证
待前两个问题修复后,用以下最小化代码验证按钮功能:
from discord.ui import Button, View @bot.slash_command(name="test_btn", description="测试按钮功能") async def test_btn(ctx): btn = Button(label="点击测试", style=discord.ButtonStyle.primary) async def callback(interaction): await interaction.response.send_message("按钮触发成功!", ephemeral=True) btn.callback = callback view = View() view.add_item(btn) await ctx.respond("点击下方按钮测试", view=view)
若斜杠命令能正常调用,点击按钮有反馈,则按钮功能正常。
内容的提问来源于stack exchange,提问作者Mystic
相关产品推荐
相关产品推荐

