如何在Discord斜杠命令(nextcord/discord.py)中添加空格?
解决Discord斜杠命令带空格形式的实现问题
你看到的/channellink list这类带空格的命令,不是给主命令名加空格,而是Discord应用命令的子命令结构——主命令+子命令的层级组合,这才是合规的实现方式,具体说明如下:
核心原理
Discord应用命令的主命令名称不允许包含空格(必须符合正则^[\w-]{1,32}$,只能用字母、数字、下划线、连字符),直接给主命令加空格自然会触发验证错误。而子命令是主命令下的二级指令,用户输入时会呈现出/主命令 子命令的形式,和你想要的效果完全一致,且每个子命令可以独立配置专属参数,完美适配你三个操作(initiate/terminate/list)的不同参数需求。
实现方式(以discord.py v2.x为例)
创建主命令channellink,然后给它添加三个子命令,每个子命令单独定义参数和逻辑:
from discord import app_commands from discord.ext import commands import discord class ChannelLinkCog(commands.Cog): def __init__(self, bot): self.bot = bot # 用字典存储已链接的频道对 self.linked_channels = {} # 子命令:initiate - 启动频道链接 @app_commands.command(name="channellink", description="管理频道消息链接功能") @app_commands.subcommand(name="initiate", description="建立两个频道的消息双向链接") @app_commands.describe(source="源频道", target="目标频道") async def cl_initiate(self, interaction: discord.Interaction, source: discord.TextChannel, target: discord.TextChannel): if (source.id, target.id) not in self.linked_channels and (target.id, source.id) not in self.linked_channels: self.linked_channels[(source.id, target.id)] = True await interaction.response.send_message(f"已成功建立 {source.mention} 和 {target.mention} 的消息链接") else: await interaction.response.send_message("这两个频道已经处于链接状态") # 子命令:terminate - 终止频道链接 @app_commands.command(name="channellink", description="管理频道消息链接功能") @app_commands.subcommand(name="terminate", description="终止指定频道的所有消息链接") @app_commands.describe(channel="要取消链接的频道") async def cl_terminate(self, interaction: discord.Interaction, channel: discord.TextChannel): to_remove = [] for (ch1, ch2) in self.linked_channels: if ch1 == channel.id or ch2 == channel.id: to_remove.append((ch1, ch2)) for pair in to_remove: del self.linked_channels[pair] await interaction.response.send_message(f"已终止 {channel.mention} 的所有消息链接") # 子命令:list - 列出所有链接 @app_commands.command(name="channellink", description="管理频道消息链接功能") @app_commands.subcommand(name="list", description="查看当前所有已建立的消息链接") async def cl_list(self, interaction: discord.Interaction): if not self.linked_channels: await interaction.response.send_message("当前没有任何已建立的频道链接") return link_list = [] guild = interaction.guild for (ch1, ch2) in self.linked_channels: channel1 = guild.get_channel(ch1) channel2 = guild.get_channel(ch2) if channel1 and channel2: link_list.append(f"{channel1.mention} ↔ {channel2.mention}") await interaction.response.send_message("当前已建立的频道链接:\n" + "\n".join(link_list)) async def setup(bot): await bot.add_cog(ChannelLinkCog(bot))
效果说明
部署后,用户在Discord中输入/channellink时,会自动弹出三个子命令选项:initiate、terminate、list,选择对应子命令后,会加载该操作专属的参数输入框,完全满足你的需求。
内容的提问来源于stack exchange,提问作者Kyrzhen
相关产品推荐
相关产品推荐

