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

Discord机器人斜杠命令本地同步失败(同步0条)求助

Discord机器人斜杠命令Guild专属同步失败排查方案

当前问题

  • 调用bot.tree.sync(guild=discord.Object(id=1283589491298402314))时,控制台输出同步0条命令,无报错信息
  • 移除guild参数后可正常完成全局同步,但需求是实现指定服务器的本地同步
  • 代码结构与官方示例一致,未发现明显语法错误

排查与解决步骤

1. 验证Guild ID与机器人服务器状态

  • 确认1283589491298402314是目标服务器的正确ID:开启Discord开发者模式,右键服务器名称复制ID
  • 查看on_ready中打印的bot.guilds列表,确认机器人已成功加入目标服务器。若列表中无该服务器,需重新生成包含applications.commands权限的邀请链接,邀请机器人加入

2. 修正同步时机与Guild对象获取方式

机器人未完成缓存加载时执行同步,可能导致Guild对象无法被识别。修改on_ready事件逻辑,确保机器人完全就绪后再同步:

@bot.event
async def on_ready():
    # 等待机器人完成所有缓存加载
    await bot.wait_until_ready()
    # 直接通过bot获取目标Guild对象,避免手动创建Object的潜在问题
    target_guild = bot.get_guild(1283589491298402314)
    if not target_guild:
        print("未找到目标服务器,请检查机器人是否已加入")
        return
    synced = await bot.tree.sync(guild=target_guild)
    print(f'Синхронизированно {len(synced)} команд!')
    print(bot.guilds)

3. 修复Cog代码的缩进与文件名问题

Python对缩进敏感,且文件名错误会导致Cog无法加载:

  • 检查./cogs目录下的文件名:当前代码中是utuls.py,可能是拼写错误(应为utils.py),需确保文件名与load()函数中的遍历逻辑匹配
  • 修正utuls.py的缩进错误(原代码中__init__和setup函数缩进不正确):
import discord
from discord.ext import commands
from discord import app_commands

class UtilsCommand(commands.Cog):
    def __init__(self, bot: discord.Client):
        self.bot = bot

    @app_commands.command(name='ping', description='Check ping')
    async def ping(self, interaction: discord.Interaction):
        await interaction.response.send_message(content=f"Pong! ({self.bot.latency:.2f}s)")

async def setup(bot):
    await bot.add_cog(UtilsCommand(bot))

4. 确认机器人权限

邀请机器人到服务器时,必须勾选applications.commands权限,否则无法在该服务器同步斜杠命令。重新生成邀请链接:
在Discord开发者门户→OAuth2→URL Generator,勾选bot和applications.commands权限,复制链接重新邀请机器人

5. 强制清除旧命令缓存

若Discord端存在旧命令缓存,可能导致同步异常,可先清除目标服务器的所有命令再重新同步:

@bot.event
async def on_ready():
    await bot.wait_until_ready()
    target_guild = bot.get_guild(1283589491298402314)
    if not target_guild:
        print("未找到目标服务器")
        return
    # 清除目标服务器的所有命令
    await bot.tree.clear_commands(guild=target_guild)
    # 重新同步命令
    synced = await bot.tree.sync(guild=target_guild)
    print(f'Синхронизированно {len(synced)} команд!')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 13:57:21