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

discord.py混合命令仅文本端生效,Slash命令无法同步求助

Discord.py混合命令同步失败问题排查

以下是你代码中存在的几个明显错误:

  • 混合命令函数名与内置命令冲突:你用@commands.hybrid_command(name='ping')装饰了名为help的函数,help是discord.py内置命令名称,会和内置命令产生命名冲突;同时函数名与指定的命令名不一致,会导致应用命令树无法正确识别该混合命令。

  • 同步逻辑未匹配Cog绑定的服务器:你的Cog通过guilds=[discord.Object(id=874842871801479208)]指定了特定服务器加载,这意味着Cog内的混合命令默认仅对该服务器可见。但你的sync命令是基于当前上下文的服务器同步,若执行sync的服务器ID与Cog绑定的ID不一致,就会同步0条命令;即使ID一致,也需要确保同步逻辑对应到绑定的服务器命令树。

  • ephemeral参数使用错误:传统文本命令的ctx.send()不支持ephemeral参数,该参数仅适用于应用命令的Interaction对象。虽然你说文本命令能运行,但实际执行时会抛出参数错误,需要区分上下文类型使用该参数。


修正后的示例代码:

import discord
from discord.ext import commands
from discord import app_commands

class Survey(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.target_guild = discord.Object(id=874842871801479208)  # 统一存储目标服务器ID

    @commands.Cog.listener()
    async def on_ready(self):
        print('Survey cog loaded.')

    @commands.command()
    async def sync(self, ctx) -> None:
        # 同步Cog绑定的目标服务器命令树
        fmt = await ctx.bot.tree.sync(guild=self.target_guild)
        await ctx.send(f"Synced {len(fmt)} commands to the target guild.")

    @commands.command()
    async def unsync(self, ctx) -> None:
        ctx.bot.tree.clear_commands(guild=self.target_guild)
        sync_tree = await ctx.bot.tree.sync(guild=self.target_guild)
        await ctx.send(f"Unsynced {len(sync_tree)} commands from the target guild.")

    # 重命名函数名避免冲突,同时明确指定适用服务器
    @commands.hybrid_command(name='ping', guilds=[discord.Object(id=874842871801479208)])
    async def ping(self, ctx: commands.Context):
        # 根据上下文类型判断是否使用ephemeral
        if isinstance(ctx.interaction, discord.Interaction):
            await ctx.send("pong", ephemeral=True)
        else:
            await ctx.send("pong")

async def setup(bot):
    await bot.add_cog(Survey(bot), guilds=[discord.Object(id=874842871801479208)])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:15:35