如何在discord.py中获取斜杠命令option后的输入内容
解决方案
斜杠命令的选项值无需手动解析原始命令字符串,Discord生态的主流开发框架都已经封装了对应取值接口,直接调用即可获取到完整的选项文本,以下是两种常用框架的实现示例:
1. discord.py(v2.x 版本)
注册命令时提前声明对应字符串类型的选项,框架会自动完成参数注入:
import discord from discord import app_commands intents = discord.Intents.default() client = discord.Client(intents=intents) tree = app_commands.CommandTree(client) # 定义斜杠命令,声明name为必填字符串选项 @tree.command(name="userinfo", description="查询用户信息") @app_commands.describe(name="要查询的用户名") async def userinfo(interaction: discord.Interaction, name: str): # 直接获取name参数值,调用lower方法转全小写 processed_name = name.lower() await interaction.response.send_message(processed_name)
2. discord.js(v14+ 版本)
注册命令时先配置对应字符串选项,触发时通过options接口取值即可:
const { SlashCommandBuilder, Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); // 定义斜杠命令配置 const userinfoCommand = new SlashCommandBuilder() .setName('userinfo') .setDescription('查询用户信息') .addStringOption(option => option.setName('name') .setDescription('要查询的用户名') .setRequired(true)); // 监听命令触发事件 client.on('interactionCreate', async interaction => { if (!interaction.isChatInputCommand()) return; if (interaction.commandName === 'userinfo') { // 直接获取name选项的完整字符串值 const name = interaction.options.getString('name'); // 转全小写处理 const processedName = name.toLowerCase(); await interaction.reply(processedName); } });
注意:不要手动拆分原始命令文本提取选项内容,Discord已经完成了所有参数的解析工作,直接调用框架提供的接口取值即可避免空格、特殊字符等场景的解析异常。
内容的提问来源于stack exchange,提问作者Hatsune Miku
相关产品推荐
相关产品推荐

