为何使用Cog后Discord Slash Command无法显示?
问题排查与解决方案
核心问题分析
你的/create-embed斜杠命令未显示,主要源于Cog加载方式错误、未同步斜杠命令以及可能的装饰器使用不当,以下是具体修复步骤:
1. 修正Cog加载方式
你在on_ready事件中手动调用admin.setup(bot),这不符合discord.py的标准加载逻辑。Cog的setup函数应通过load_extension自动触发,而非直接调用。
修复代码(main.py):
import discord import asyncio import env # 启用基础意图 intents = discord.Intents.default() bot = discord.Bot(intents=intents) @bot.event async def on_ready(): # 使用load_extension加载Cog,自动触发setup函数 await bot.load_extension("admin") # 替换为你的Cog文件模块名 print(f"已登录为 {bot.user}") async def main(): await bot.start(env.BOT_TOKEN) if __name__ == "__main__": asyncio.run(main())
2. 同步斜杠命令到Discord API
斜杠命令需要与Discord服务器同步才能在客户端显示,默认不会自动同步。
修复代码(main.py的on_ready事件中添加):
@bot.event async def on_ready(): await bot.load_extension("admin") # 同步命令(仅首次运行时执行,避免触发Discord速率限制) await bot.tree.sync() # 测试阶段可使用 guild 专属同步(立即生效): # await bot.tree.sync(guild=discord.Object(id=你的服务器ID)) print(f"已登录为 {bot.user}")
3. 修正斜杠命令装饰器
确保使用discord.py官方的斜杠命令装饰器,避免自定义别名导致的注册失败。
修复代码(Admin Cog文件):
import discord from discord import app_commands from discord.ext import commands import env import v class Admin(commands.Cog): def __init__(self, bot: discord.Bot): self.bot = bot # 使用官方app_commands.command装饰器 @app_commands.command(name="create-embed", description="Test") async def create_embed(self, ctx: discord.ApplicationContext): block.has_role(ctx, env.METACORE_MODERATOR_ROLE_ID) embed_title = 'Test title' view = v.CreateEmbedView() view.bot = self.bot view.author_id = ctx.author.id result_embed = discord.Embed(title=embed_title) embed_message = await ctx.respond(embed=result_embed, view=view, ephemeral=True) view.embed = result_embed view.embed_message = embed_message # discord.py v2+ 要求setup函数为异步 async def setup(bot): await bot.add_cog(Admin(bot))
额外注意事项
- 全局同步延迟:全局命令同步可能需要1小时才能在所有服务器生效,测试时建议使用服务器专属同步。
- 速率限制:避免频繁同步命令,Discord对命令注册有速率限制。
- 开发者门户配置:确保你的机器人在Discord开发者门户中启用了
applications.commands权限范围,且邀请链接包含该范围。
内容的提问来源于stack exchange,提问作者metacore
相关产品推荐
相关产品推荐

