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

Discord.py单服务器机器人命令同步失败,命令不显示求助

解决discord.py预发布版本单服务器命令同步0条的问题

核心问题排查与修复步骤

1. 命令未绑定目标服务器

你当前的@bot.tree.command默认创建全局命令,而on_ready中仅同步指定服务器的专属命令,全局命令不会被纳入同步结果。需给命令明确绑定目标服务器:

# 确保GUILD_ID是正确的整数常量
GUILD_ID = 1234567890  # 替换为你的服务器实际ID

@bot.tree.command(name='leave', description='Leave vc', guilds=[discord.Object(id=GUILD_ID)])
async def leave_call(interaction: discord.Interaction):
    vc = discord.utils.get(bot.voice_clients, guild=interaction.guild)
    if vc and vc.is_connected():
        if isinstance(vc, voice_recv.VoiceRecvClient):
            vc.stop_listening()
        await vc.disconnect()
        await interaction.response.send_message("Disconnected.", ephemeral=True)
    else:
        await interaction.response.send_message("Not connected.")

2. 加载顺序与重复同步问题

on_ready可能在命令定义完成前触发(比如命令代码写在on_ready之后),导致同步时命令树为空。需确保所有命令定义在bot.run()之前,同时添加标志避免重复同步:

bot.has_synced = False

@bot.event
async def on_ready():
    if bot.has_synced:
        return
    bot.has_synced = True
    print(f"Connected as {bot.user}")
    guild_id = discord.Object(id=GUILD_ID)
    synced = await bot.tree.sync(guild=guild_id)
    print(f"{len(synced)} commands synced on server {GUILD_ID}.")

3. 开发版版本bug排查

你使用的是discord.py==2.7.0a5350+g8f2cb607预发布版,可能存在同步逻辑bug:

  • 尝试升级到最新开发版:pip install -U git+https://github.com/Rapptz/discord.py.git
  • 或临时切换到稳定版(如2.6.0)验证是否能正常同步

4. 基础权限与ID校验

  • 确认机器人在目标服务器拥有applications.commands权限(服务器设置-权限-应用命令权限开启)
  • 检查GUILD_ID为正确整数,无字符串类型或错误ID
  • 确保机器人已成功加入目标服务器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 01:40:04