Embed报错:setTitle无法读取null属性,求discord.js嵌入消息修复
修复Discord.js中Embed构建的"setTitle cannot read property null"错误
问题说明
执行/embed命令时终端抛出错误:Embed error setTitle cannot read property null,代码逻辑看似正确但无法运行,需要修复Embed模块代码以正常工作并复用UI。
错误原因
- 链式调用被打断:代码中
const user = interaction.options.getUser('target')这行插入在EmbedBuilder实例创建和链式方法调用之间,导致后续的.setTitle()等方法被调用在getUser('target')的返回值上,而非Embed实例。 - 无效参数调用:当前
/embed命令并未定义target用户选项,interaction.options.getUser('target')会返回null,后续调用.setTitle()自然触发"无法读取null的属性"错误。
修复后的代码
const {SlashCommandBuilder, EmbedBuilder} = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName("embed") .setDescription("Returns an Embed"), async execute(interaction, client){ // 修复链式调用,移除无效的target参数获取 const embed = new EmbedBuilder() .setTitle('This is totally an embed') .setDescription('This might Work ? Maybe') .setColor(0x18e1ee) .setImage(client.user.displayAvatarURL()) .setThumbnail(client.user.displayAvatarURL()) .setTimestamp(Date.now()) .setAuthor({ url: `https://ww4.gogoanimes.org/`, iconURL: interaction.user.displayAvatarURL(), name: interaction.user.tag }) .setFooter({ iconURL: client.user.displayAvatarURL(), text: client.user.tag }) .setURL('https://discord.gg/kMb9XZAq') .addFields([ { name: 'Field 1', value: 'Field value 1', inline: true }, { name: `Field 2`, value: `Field value 2`, inline: true } ]); await interaction.reply({embeds: [embed]}) }, }
额外说明(若需要target参数)
如果你的命令确实需要获取目标用户,需在SlashCommandBuilder中添加对应选项,同时正确处理可能的null情况:
data: new SlashCommandBuilder() .setName("embed") .setDescription("Returns an Embed") // 添加target用户选项 .addUserOption(option => option.setName('target') .setDescription('目标用户') .setRequired(false) // 设为false表示可选 ), async execute(interaction, client){ // 移到Embed构建代码外,避免打断链式调用 const user = interaction.options.getUser('target'); const embed = new EmbedBuilder() .setTitle('This is totally an embed') // 可根据user是否存在添加内容 .setDescription(user ? `目标用户:${user.tag}` : 'This might Work ? Maybe') // ...其他Embed配置 await interaction.reply({embeds: [embed]}) }
内容的提问来源于stack exchange,提问作者Tarun Kumar
相关产品推荐
相关产品推荐

