使用discord.js获取斜杠命令参数时触发TypeError报错求助
解决discord.js斜杠命令参数获取报错
TypeError: Cannot read properties of undefined (reading 'get') 你的报错根源是属性名拼写错误:在获取damage和breeze参数时,你写了interaction.option.get(),但discord.js中正确的属性是复数形式的interaction.options(漏写了末尾的s)。因为interaction.option不存在,所以调用get方法时会触发Cannot read properties of undefined错误。
另外还有两处细节需要修正:
interaction.options.get()返回的是完整的选项对象,直接赋值的话拿到的不是参数的实际值,需要通过.value属性提取。interaction.reply的content只接受字符串,不能直接传入对象,需要把参数值拼接成可读的字符串返回。
修正后的完整代码:
const { SlashCommandBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('manacost') .setDescription('计算灵魂召唤所需的 mana 消耗') .addStringOption(option => option.setName('health') .setDescription('你的灵魂生命值,支持用k代表1000') .setRequired(true)) .addStringOption(option => option.setName('damage') .setDescription('你的灵魂伤害值,支持用k代表1000') .setRequired(true)) .addIntegerOption(option => option.setName('breeze') .setDescription('你的微风数值(0-80)') .setRequired(false)), async execute(interaction) { if (!interaction.isChatInputCommand()) return; // 修正拼写错误,提取参数实际值 const hp = interaction.options.get('health').value; const dmg = interaction.options.get('damage').value; // 可选参数用可选链避免报错,设置默认值0 const breeze = interaction.options.get('breeze')?.value || 0; console.log({ hp, dmg, breeze }); // 拼接成字符串回复 await interaction.reply(`生命值:${hp},伤害值:${dmg},微风:${breeze}`); }, }
额外提示:
- 对于可选参数,必须判断是否存在(用
?.或条件语句),否则当用户未提供该参数时,get()会返回null,调用.value会触发新的错误。 - 如果需要保留选项对象的其他信息(比如参数类型),可以去掉
.value,但回复时需要将对象转换为字符串(比如用JSON.stringify())。
内容的提问来源于stack exchange,提问作者Aldoraz
相关产品推荐
相关产品推荐

