discord.py中Cogs加载的斜杠命令同步后不显示的问题求助
Discord.py Cogs斜杠命令同步失败解决方案
核心排查与修复方向
1. 确认Cog与命令的正确注册
- Cog内的斜杠命令必须使用
@app_commands.command()装饰,不能用普通前缀命令的@commands.command()。 - 确保Cog已成功加载:
- 要么在
on_ready事件中通过await bot.add_cog(YourCog(bot))手动加载; - 要么在Cog文件中定义
setup函数,让bot自动识别加载(需保证Cog文件在bot可读取的目录下)。
- 要么在
2. 修正tree.sync()的调用逻辑
全局同步命令可能需要1小时左右才能生效,测试阶段优先用指定服务器同步,可即时看到结果:
- 同步操作必须在bot进入就绪状态后执行,避免在bot启动前调用
sync。 - 给同步命令加上所有者权限限制,防止误操作。
3. 权限与环境检查
- 确保bot在目标服务器拥有
applications.commands权限(邀请bot时链接需包含scope=bot%20applications.commands参数)。 - 验证bot Token正确,且bot已成功加入目标服务器。
代码示例
main.py
import discord from discord.ext import commands from discord import app_commands import testing intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents) @bot.event async def on_ready(): print(f"已登录:{bot.user}") # 加载测试Cog await bot.add_cog(testing.TestingCog(bot)) print("TestingCog加载完成") @bot.command() @commands.is_owner() async def sync(ctx): # 替换为你的目标服务器ID,实现即时同步 target_guild = discord.Object(id=1234567890) # 可选:将全局命令同步到指定服务器 bot.tree.copy_global_to(guild=target_guild) # 执行同步 synced = await bot.tree.sync(guild=target_guild) # 若需全局同步,替换为:synced = await bot.tree.sync() await ctx.send(f"已同步 {len(synced)} 条命令") bot.run("你的Bot Token")
testing.py(Cog文件)
from discord.ext import commands from discord import app_commands class TestingCog(commands.Cog): def __init__(self, bot): self.bot = bot @app_commands.command(name="test", description="测试斜杠命令") async def test_cmd(self, interaction: discord.Interaction): await interaction.response.send_message("斜杠命令生效!") # 可选:自动加载Cog的setup函数 async def setup(bot): await bot.add_cog(TestingCog(bot))
额外调试技巧
- 添加全局错误捕获,排查隐藏问题:
@bot.event async def on_error(event, *args, **kwargs): print(f"事件 {event} 发生错误:{args[0]}") - 检查命令名是否重复或包含特殊字符,Discord不允许斜杠命令名含空格或特殊符号。
内容的提问来源于stack exchange,提问作者hyperrr
相关产品推荐
相关产品推荐

