如何获取Discord.js中字符串选项传入的问题内容?
修正Discord.js 8ball命令Embed显示用户问题的代码问题
你的代码有两个关键错误导致无法实现需求:
- 没有正确获取用户通过
question选项输入的内容,question变量未定义 - 错误调用
interaction.reply(question)来拼接字符串,这个方法是用来发送回复的,不能用来获取内容,还会导致后续重复回复报错
修正步骤:
- 先从交互选项中提取用户输入的问题,用
interaction.options.getString('question')获取并赋值给变量 - 在Embed的
setAuthor中直接使用这个变量拼接文本 - 移除不需要的
Embed导入(代码里没用到) - 颜色值建议加上
#前缀,符合标准十六进制颜色格式
修正后的完整代码:
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('8ball') .setDescription('Answers any question, given that it has a yes or no answer') .addStringOption(option => option.setName('question') .setDescription('Write the yes or no question you want the answer to.') .setRequired(true)), async execute(interaction) { // 获取用户输入的问题 const userQuestion = interaction.options.getString('question'); const embed = new EmbedBuilder() .setColor('#2f3136') .setAuthor({ name: `${interaction.user.tag} Asks ${userQuestion}`}); await interaction.reply({ embeds: [embed] }); }, };
修改后,机器人回复的Embed作者栏会正确显示[用户名#标签] Asks [用户输入的问题],完全符合你的需求。
内容的提问来源于stack exchange,提问作者toucan cookie
相关产品推荐
相关产品推荐

