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

discord.py混合命令同步异常及残留命令清除问题

Discord.py混合命令同步问题

问题概述

使用discord.py同步hybrid命令(混合命令)时出现以下异常:

  • 执行$sync命令,@bot.tree.command()修饰的test1命令可正常同步运行,但hybrid命令无法同步。
  • 存在残留的test命令,多次同步无法移除,执行该命令触发CommandNotFound错误。
  • 最初用@commands.hybrid_command时,$test1提示“command not found”,/test1无响应;改为@bot.hybrid_command后,$test1可正常运行,但/test1仍无响应(后续test1出现在斜杠命令列表,但残留test命令依旧存在)。

代码示例

import discord
import os
import sys
import subprocess
import random
from dotenv import load_dotenv
from discord.ext import commands
from discord import app_commands
from typing import Literal, Optional
from discord.ext.commands import Greedy, Context


intents = discord.Intents.default()
bot = commands.Bot(command_prefix='$', intents=intents)
intents.message_content = True
load_dotenv()

bot.help_command=None

# 省略部分代码

# 启动确认消息
@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord! Version {discord.__version__}')

@bot.command()
@commands.guild_only()
@commands.is_owner()
async def sync(
  ctx: Context, guilds: Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
    if not guilds:
        if spec == "~":
            synced = await ctx.bot.tree.sync(guild=ctx.guild)
        elif spec == "*":
            ctx.bot.tree.copy_global_to(guild=ctx.guild)
            synced = await ctx.bot.tree.sync(guild=ctx.guild)
        elif spec == "^":
            ctx.bot.tree.clear_commands(guild=ctx.guild)
            await ctx.bot.tree.sync(guild=ctx.guild)
            synced = []
        else:
            synced = await ctx.bot.tree.sync()

        await ctx.reply(
            f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
        )
        return

    ret = 0
    for guild in guilds:
        try:
            await ctx.bot.tree.sync(guild=guild)
        except discord.HTTPException:
            pass
        else:
            ret += 1

    await ctx.reply(f"Synced the tree to {ret}/{len(guilds)}.")


@bot.hybrid_command(name='help', with_app_command=True)
async def help2(ctx: commands.Context):
    await ctx.send("Test was good!")

@bot.tree.command()
async def test1(interaction: discord.Interaction) -> None:
    await interaction.response.send_message("test successful")

# 省略部分代码

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

错误信息

执行残留的test命令时触发如下错误:

2023-10-11 17:45:35 ERROR    discord.app_commands.tree Ignoring exception in command tree
Traceback (most recent call last):
  File "C:\Users\malak\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1089, in wrapper
    await self._call(interaction)
  File "C:\Users\malak\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1221, in _call
    command, options = self._get_app_command_options(data)
  File "C:\Users\malak\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1125, in _get_app_command_options
    raise CommandNotFound(name, parents)
discord.app_commands.errors.CommandNotFound: Application command 'test' not found

解决建议

1. 修正Intents配置顺序

你的代码中先创建bot实例再修改intents.message_content,这会导致意图设置无效。调整为:

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='$', intents=intents)

同时确保Discord开发者门户中已开启message_content权限。

2. 修复混合命令斜杠同步问题

  • 全局命令同步存在1小时左右的缓存延迟,优先用服务器级同步测试:执行$sync ~,仅同步当前服务器的命令,可立即看到效果。
  • 混合命令默认with_app_command=True,无需额外声明,确保命令定义使用@bot.hybrid_command而非@commands.hybrid_command。
  • 在on_ready事件中添加缓存等待逻辑:
    @bot.event
    async def on_ready():
        await bot.wait_until_ready()
        print(f'{bot.user} has connected to Discord! Version {discord.__version__}')
    

3. 彻底清除残留命令

  • 执行$sync ^清空当前服务器的所有命令,再重新同步。
  • 若为全局残留命令,需在sync函数中添加全局清除逻辑:
    elif spec == "!":
        ctx.bot.tree.clear_commands(guild=None)
        await ctx.bot.tree.sync()
        synced = []
    
    之后执行$sync !即可清空全局命令。
  • 也可直接在Discord开发者门户的「应用程序-命令」页面手动删除残留命令。

4. 优化混合命令响应逻辑

混合命令需同时支持消息前缀和斜杠两种触发方式,可统一响应逻辑:

@bot.hybrid_command(name='help', description='获取帮助信息')
async def help2(ctx: commands.Context):
    # 兼容两种触发方式的响应
    await ctx.send("Test was good!")
    if ctx.interaction:
        await ctx.interaction.response.send_message("Test was good!", ephemeral=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:28:10