使用Pycord添加Discord斜杠命令遇AttributeError问题求助
斜杠命令报错修复方案
1. 先确认Pycord的正确安装
你大概率是安装了错误的库(比如discord.py而非Pycord),或者脚本文件名和库模块冲突。执行以下步骤:
- 卸载冲突库:
pip uninstall discord.py py-cord -y - 重新安装Pycord:
pip install py-cord - 重要:不要把你的脚本文件命名为
discord.py或bot.py,否则Python会优先导入你自己的文件,导致模块冲突报错。
2. 修正代码中的错误
写法一:使用discord.Bot(纯斜杠命令机器人)
你的原代码有两处错误:类型标注写错(discord_Interaction应为discord.Interaction)、同时创建了Client和Bot实例(两者只需保留一个)。修正后代码:
import discord import youtube_dl import asyncio from discord.ext import commands intents = discord.Intents.default() intents.members = True intents.message_content = True intents.voice_states = True # 仅初始化一个Bot实例 bot = discord.Bot(intents=intents) @bot.slash_command(name='hello') async def hello(ctx: discord.Interaction): await ctx.respond('Hello there!') # 启动机器人(替换为你的令牌) bot.run('YOUR_BOT_TOKEN')
写法二:使用commands.Bot(混合传统命令与斜杠命令)
如果需要同时支持前缀命令和斜杠命令,commands.Bot需要用@bot.tree.command()来定义斜杠命令,同时要同步命令到Discord服务器:
import discord import youtube_dl import asyncio from discord.ext import commands intents = discord.Intents.default() intents.members = True intents.message_content = True intents.voice_states = True # 指定前缀,初始化Bot bot = commands.Bot(command_prefix='!', intents=intents) # 定义斜杠命令 @bot.tree.command(name='hello') async def hello(interaction: discord.Interaction): await interaction.response.send_message('Hello there!') # 机器人就绪后同步命令到服务器 @bot.event async def on_ready(): await bot.tree.sync() # 全局同步,测试可加 guild_id=xxx 指定服务器 print(f'已登录:{bot.user}') bot.run('YOUR_BOT_TOKEN')
3. 版本排查
如果上述步骤无效,检查当前Pycord版本:
pip show py-cord
建议使用最新稳定版,若安装的是测试版,可切换到稳定版:
pip install py-cord==2.4.1
内容的提问来源于stack exchange,提问作者skee
相关产品推荐
相关产品推荐

