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

Pycord开发Discord机器人 命令重复同步触发应用命令重名报错

Pycord斜杠命令重复同步报错修复

问题表现

开发Discord机器人时程序可正常启动连接,但所有斜杠命令无法生效,触发Application command names must be unique(应用程序命令名称必须唯一)报错,排查发现/cogs命令存在重复同步问题。

原始业务代码

import discord
import os
from dotenv import load_dotenv
from discord.ext import commands
from discord import slash_command

bot = commands.Bot(command_prefix='>', intents=discord.Intents.all(),debug_guilds=[964126154774679582,740616442034258002,965533467557371944], activity=discord.Activity(type=discord.ActivityType.watching, name='Over The Felbcord'))
load_dotenv()
directories = ["./commands", "./Embeds"]

for directory in directories:
   for filename in os.listdir(directory):
      if filename.endswith(".py"):
       bot.load_extension(f"{directory[2:]}.{filename[:-3]}")
@bot.event
async def on_ready():
    print('Connected to bot: {}'.format(bot.user.name))

@bot.event
async def on_application_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.respond(error)
    else:
        raise error
@bot.event
async def on_message(message):
    if bot.user in message.mentions:
        Welcome=discord.Embed(title="Felbot", description="Hello! I am a personal bot who helps around moderating and providing fun into the server! \n If you have any questions about me feel free to ask my creator \n Join the official server via the invite link shared in the rules channel",color=discord.Color.blue())
        Welcome.set_author(name="FelBot", icon_url="本地/CDN托管的机器人头像地址")
        await message.channel.send(embed=Welcome)
    await bot.process_commands(message)

bot.run(os.getenv("TOKEN"))

触发原因

  • 扩展加载逻辑无去重校验:同时遍历./commands、./Embeds两个目录加载Cog扩展时,若两个目录存在同名.py文件,会重复加载同名命令
  • 旧命令残留无清理逻辑:Pycord启动时会自动同步斜杠命令,之前测试阶段残留的全局/调试服务器命令没有被清理,和新注册的同名命令产生冲突
  • 代码存在重复命令定义:主文件和Cog文件、不同Cog文件之间定义了同名的斜杠命令(含拼写一致、大小写不同的命令)

修复步骤

  • 给扩展加载逻辑增加去重判断,避免重复加载同名模块
loaded_extensions = set()
for directory in directories:
    for filename in os.listdir(directory):
        if filename.endswith(".py"):
            ext_path = f"{directory[2:]}.{filename[:-3]}"
            if ext_path not in loaded_extensions:
                bot.load_extension(ext_path)
                loaded_extensions.add(ext_path)
  • 增加一次性命令同步逻辑,启动时先清空残留旧命令再重新同步,注意该逻辑仅需启动时执行一次,不要每次触发on_ready都重复调用
from discord.ext import tasks

@bot.event
async def on_ready():
    print('Connected to bot: {}'.format(bot.user.name))
    if not command_sync.is_running():
        command_sync.start()

@tasks.loop(count=1)
async def command_sync():
    # 清空所有调试服务器的残留旧命令
    for guild_id in bot.debug_guilds:
        target_guild = bot.get_guild(guild_id)
        if target_guild:
            bot.tree.clear_commands(guild=target_guild)
    # 清空全局残留旧命令
    bot.tree.clear_commands(guild=None)
    # 开发阶段仅同步调试服务器即可,减少接口频率触发风险
    for guild_id in bot.debug_guilds:
        await bot.tree.sync(guild=discord.Object(id=guild_id))
    # 正式上线时再执行全局同步
    # await bot.tree.sync()
    print("Slash commands synced, no duplicate conflicts")
  • 全局排查所有代码文件,确认不存在重名的斜杠主命令、子命令,不要在多个位置重复定义同一个命令
  • 若修改代码后仍报错,前往Discord开发者后台对应机器人的应用管理页面,手动删除残留的重复命令定义后重启机器人即可

注意:Discord对命令同步接口有频率限制,不要频繁调用sync方法,开发阶段使用调试服务器同步测试即可,全局同步仅在正式版本发布时执行一次。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 21:33:25