You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py调试服务器斜杠命令无法同步求助

排查Discord机器人Cog添加后斜杠命令同步失败的问题

1. 检查Cog的加载与结构

  • 确认Cog类正确继承commands.Cog,且setup函数为异步并正确调用add_cog:
# 正确的Cog示例结构
from discord.ext import commands

class ExampleCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.hybrid_command(name="test", description="测试混合命令")
    async def test_cmd(self, ctx):
        await ctx.send("命令生效")

async def setup(bot):
    await bot.add_cog(ExampleCog(bot))
  • 加载Cog时添加错误捕获,排查加载失败原因:
# 主文件中加载Cog的代码
async def load_cogs(bot):
    cogs_list = ["cogs.example"]  # 替换为你的Cog路径
    for cog in cogs_list:
        try:
            await bot.load_extension(cog)
            print(f"成功加载Cog: {cog}")
        except Exception as e:
            print(f"加载Cog失败 {cog}: {str(e)}")

2. 修正同步命令的实现

  • 确保同步命令指定调试服务器ID,避免全局同步的延迟问题:
@commands.command()
@commands.is_owner()
async def sync(ctx):
    # 指定当前服务器同步,仅对调试服务器生效
    synced_commands = await ctx.bot.tree.sync(guild=ctx.guild)
    # 输出同步的命令名称列表
    await ctx.send(f"Registered commands: {[cmd.name for cmd in synced_commands]}")
  • 若在on_ready中同步,添加单次执行判断(避免重复同步):
@bot.event
async def on_ready():
    if not hasattr(bot, 'synced'):
        # 替换为你的调试服务器ID
        test_guild = discord.Object(id=1234567890)
        await bot.tree.sync(guild=test_guild)
        bot.synced = True
    print(f"已登录为 {bot.user}")

3. 验证Hybrid命令的配置

  • 所有需要同步为斜杠命令的函数,必须使用@commands.hybrid_command()装饰器,而非普通的@commands.command()。
  • 命令参数需使用Discord支持的类型(如discord.Member、str、int),自定义类型需实现转换逻辑。

4. 检查机器人权限与API状态

  • 确认机器人在调试服务器中拥有applications.commands权限(可在服务器设置→角色→机器人角色中开启)。
  • 重启机器人,清除本地缓存;登录Discord开发者门户,检查应用命令列表是否有异常。
  • 验证机器人Token正确且未过期,确保与开发者门户中的应用匹配。

内容的提问来源于stack exchange,提问作者FragileBox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 16:22:01