如何在Discord.js中定义并引用stringOption参数的输入文本?
问题解决:Discord.js 获取斜杠命令字符串参数并回复
你的代码存在两处关键问题,导致无法正确获取并回复用户输入的文本:
- 字符串参数获取方式错误:
interaction.getOption('text')针对字符串类型的选项,直接返回的就是用户输入的字符串内容,不需要额外访问.content属性。 - 回复方法使用错误:
interaction.editReply用于编辑已发送的机器人回复,你需要的是首次发送回复,应该使用interaction.reply。
另外,toString(Text) 属于多余操作,因为获取到的参数本身就是字符串类型。
修正后的代码如下:
module.exports = { data: new SlashCommandBuilder() .setName('tsay') .setDescription('Replies with the text that was entered (General)') .addStringOption(option => option.setName('text') .setDescription('Text to be copied') .setRequired(true)), async execute(interaction, client) { // 直接获取用户输入的字符串参数 const userInputText = interaction.getOption('text'); // 发送回复 await interaction.reply({ content: userInputText }); } }
简单说明:
interaction.getOption('text')会直接返回用户在text参数中输入的内容。interaction.reply()是机器人响应斜杠命令发送首次回复的标准方法。
内容的提问来源于stack exchange,提问作者Goobster
相关产品推荐
相关产品推荐

