如何在discord.py中添加子命令支持?解决命令未找到错误
解决discord.py子命令报错问题
问题原因
你当前通过字符串参数模拟子命令的方式不符合discord.py官方子命令的实现规范,Discord无法识别这种自定义的"subcommand"参数为合法应用命令,因此触发CommandNotFound错误。正确的做法是使用官方提供的*命令组(Group)*来定义子命令。
正确实现子命令的步骤
- 创建命令组:使用
discord.app_commands.Group构建父命令框架 - 定义子命令:为命令组绑定具体功能的子命令函数
- 同步命令树:启动Bot时将命令结构同步到Discord,确保服务器识别新命令
修正后的代码示例
import discord from discord import app_commands import handlers import asyncio import random import csv from project_types import unopened_file import lol import re intents = discord.Intents.default() intents.messages = True intents.message_content = True intents.reactions = True intents.members = True bot = discord.Client(intents=intents) tree = app_commands.CommandTree(bot) # 创建group命令组,作为父命令 group_group = app_commands.Group(name="group", description="群组相关操作") # 添加add子命令 @group_group.command(name="add", description="添加成员到群组") async def group_add(interaction: discord.Interaction, member: discord.Member): await interaction.response.send_message(f"已将{member.mention}添加到群组") # 添加remove子命令 @group_group.command(name="remove", description="从群组移除成员") async def group_remove(interaction: discord.Interaction, member: discord.Member): await interaction.response.send_message(f"已将{member.mention}从群组移除") # 将命令组注册到命令树 tree.add_command(group_group) @bot.event async def on_ready(): await tree.sync() # 同步命令结构到Discord print(f"已登录为{bot.user}") bot.run("你的Bot令牌")
关键说明
- 官方子命令会被Discord自动识别,用户输入
/group add时会弹出参数选择器,避免手动输入字符串的错误 - 每次修改命令结构后,必须调用
tree.sync()让Discord更新命令列表,否则新子命令无法被识别 - 可以直接使用Discord内置类型(如
discord.Member),提升用户交互体验
内容的提问来源于stack exchange,提问作者imeesa
相关产品推荐
相关产品推荐

