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

discord.py指令组如何实现不存在子指令时发送自定义提示消息

解决方法

当前逻辑没有区分「用户仅输入主指令;id」和「用户输入主指令+不存在的子指令」两种场景,两种场景都会触发ctx.invoked_subcommand is None的判断,所以都会返回主指令提示。可以用以下两种方案实现需求:

方案1:兼容所有discord.py版本,修改现有主指令逻辑

直接在原主指令的判断中增加对额外输入的检测即可:

@commands.group(invoke_without_command=True)
async def id(self, ctx):
    # 读取剩余未解析的内容,判断用户是否输入了额外的无效参数
    extra_args = ctx.view.read_rest().strip()
    if extra_args:
        # 存在额外内容,说明是输入了不存在的子指令,发送自定义错误提示
        await ctx.send("错误:不存在的子指令,请输入有效的子指令名称")
    else:
        # 没有额外内容,用户仅输入了主指令,返回原有帮助
        await ctx.send("This command help you find the name of anyone in the server! ")

@id.command()
async def Slayer(self, ctx):
    await ctx.send("Bob Miller")

@id.command()
async def Skel(self, ctx):
    await ctx.send("John Dove")

这里添加的invoke_without_command=True参数会确保只有没有匹配到有效子指令时,才会触发主指令的函数逻辑,避免主、子指令逻辑重复执行。

方案2:discord.py 2.0及以上版本,使用fallback装饰器

你可以用fallback装饰器专门处理所有无效子指令的请求,逻辑更清晰:

@commands.group(invoke_without_command=True)
async def id(self, ctx):
    # 仅处理用户输入纯主指令的情况
    await ctx.send("This command help you find the name of anyone in the server! ")

@id.command()
async def Slayer(self, ctx):
    await ctx.send("Bob Miller")

@id.command()
async def Skel(self, ctx):
    await ctx.send("John Dove")

# 专门处理所有无效的子指令请求
@id.fallback()
async def id_fallback(self, ctx, *, args):
    await ctx.send("错误:不存在的子指令,请输入有效的子指令名称")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 12:06:03