Discord工单机器人无法启动:slash_command与Cogs安装报错求助
问题1:
AttributeError: module 'discord.ext.commands' has no attribute 'slash_command' 修复方案 原因
pycord 2.0 中,slash_command 并非 discord.ext.commands 模块的属性,正确的 slash 命令定义有两种规范方式。
修复步骤
方式一:使用 Bot 实例的装饰器
若代码中误用了 @commands.slash_command(),改为直接绑定 Bot 实例的装饰器:
# 错误写法 from discord.ext import commands @commands.slash_command(name="ticket", description="创建工单") async def ticket(ctx): # 逻辑代码 # 正确写法 import discord from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @bot.slash_command(name="ticket", description="创建工单") async def ticket(ctx): # 逻辑代码
方式二:使用 app_commands 模块(推荐)
现代 Discord 机器人更推荐用 app_commands 定义 slash 命令,需同步命令到服务器:
import discord from discord import app_commands from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @bot.tree.command(name="ticket", description="创建工单") async def ticket(interaction: discord.Interaction): # 注意参数为 Interaction 而非 Context # 工单逻辑代码,比如创建选择菜单 pass # 同步命令 @bot.event async def on_ready(): # 全局同步(生效较慢)或指定服务器同步 await bot.tree.sync() # 指定服务器:await bot.tree.sync(guild=discord.Object(id=你的服务器ID)) print(f"Logged in as {bot.user}")
问题2:
pip install Cogs 元数据生成失败 修复方案 原因
PyPI 不存在名为 Cogs 的包——Cogs 是 pycord/discord.py 中用于模块化管理命令的机制,无需单独安装,只需自行编写模块化代码并加载。
修复步骤
- 在项目根目录创建
cogs文件夹 - 将你的
ticket_commands.py放入该文件夹,并调整为 Cog 类结构:
from discord.ext import commands from discord import app_commands class TicketCommands(commands.Cog): def __init__(self, bot): self.bot = bot @app_commands.command(name="ticket", description="创建工单") async def ticket(self, interaction: discord.Interaction): # 工单逻辑代码 pass async def setup(bot): await bot.add_cog(TicketCommands(bot))
- 在
main.py中加载这个 Cog:
import discord from discord.ext import commands import os intents = discord.Intents.default() intents.message_content = True intents.members = True bot = commands.Bot(command_prefix="!", intents=intents) @bot.event async def on_ready(): for filename in os.listdir("./cogs"): if filename.endswith(".py"): await bot.load_extension(f"cogs.{filename[:-3]}") print(f"Logged in as {bot.user}")
额外检查项
- 确保 pycord 安装正确:先执行
pip uninstall discord.py(若之前安装过),再运行pip install pycord==2.0.1 - 在 Discord 开发者门户的 Bot 页面,开启 Server Members Intent 和 Message Content Intent,并在代码中传入对应 Intents(如上示例)
内容的提问来源于stack exchange,提问作者jeoer
相关产品推荐
相关产品推荐

