如何在discord.py的Cog文件中编写Slash命令形式的子命令组
在Discord.py Cog中实现Slash命令组(set子命令组)
核心问题修正与完整实现
你原代码的问题主要是缩进错误、子命令描述不符,以及Cog结构不规范。以下是正确的实现方案:
完整Cog示例代码
import discord from discord import app_commands from discord.ext import commands # 自定义的个人介绍模态框示例 class IntroModal(discord.ui.Modal, title="设置个人介绍"): intro_content = discord.ui.TextInput( label="你的个人介绍", style=discord.TextStyle.long, placeholder="在这里输入你的个人介绍...", required=True ) async def on_submit(self, interaction: discord.Interaction): await interaction.response.send_message(f"你的个人介绍已更新:{self.intro_content.value}", ephemeral=True) class SettingsCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @app_commands.group(name="set", description="设置个人相关信息的命令组") async def set_group(self, interaction: discord.Interaction): # 用户仅输入/set时的提示响应 if interaction.invoked_subcommand is None: await interaction.response.send_message( "请指定具体子命令,可用选项:profile、introduction、birthday", ephemeral=True ) @set_group.command(name="introduction", description="设置个人介绍,让他人了解你") async def set_introduction(self, interaction: discord.Interaction): await interaction.response.send_modal(IntroModal()) @set_group.command(name="profile", description="设置个人基础资料") async def set_profile(self, interaction: discord.Interaction): # 此处可添加资料设置的交互逻辑(如模态框、选择器) await interaction.response.send_message("正在打开个人资料设置界面...", ephemeral=True) @set_group.command(name="birthday", description="设置你的生日信息") async def set_birthday(self, interaction: discord.Interaction): # 此处可添加生日设置的交互逻辑 await interaction.response.send_message("正在打开生日设置界面...", ephemeral=True) # Cog加载函数 async def setup(bot: commands.Bot): await bot.add_cog(SettingsCog(bot))
关键注意事项
- 缩进规范:Python对缩进敏感,原代码中
async def set(self, ...)的缩进错误,类内方法需保持统一缩进层级。 - 命名避坑:避免用Python内置函数名(如
set)作为方法名,改用set_group这类自定义名称更安全。 - 命令同步:主文件中需添加命令同步逻辑,确保Slash命令能被Discord识别:
@bot.event async def on_ready(): await bot.tree.sync() print(f"已登录为 {bot.user}") - 私密响应:使用
ephemeral=True让提示消息仅命令发起者可见,避免频道消息杂乱。
内容的提问来源于stack exchange,提问作者TurtleBear
相关产品推荐
相关产品推荐

