You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Discord.js开发斜杠命令发送嵌入引用报错:期望对象却收到字符串

问题排查与解决方案:Discord.js斜杠命令「deep-quote」无响应及参数错误

一、Discord.MessageEmbed is not a constructor 错误说明

你使用的是Discord.js v14+版本,该版本已废弃MessageEmbed,统一使用EmbedBuilder,因此无需再尝试MessageEmbed,换回EmbedBuilder是正确方向。

二、核心错误「expected an object and received string instead」排查与修复

这个错误的本质是参数类型不匹配,常见触发场景及修复方式:

  • Embed方法参数格式错误:比如setAuthor()在v14中要求传入包含name等属性的对象,若直接传入字符串就会触发错误;
  • 随机索引越界:如果随机生成的索引超出数组长度,会取到undefined,传入Embed方法时触发类型错误;
  • 交互回复格式错误:interaction.reply()必须传入包含embeds数组的对象,不能直接传Embed实例或字符串。

三、修正后的完整示例代码

const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('deep-quote')
        .setDescription('生成随机深度引用'),
    async execute(interaction) {
        // 定义数据源数组
        const quotes = ["引用文本1", "引用文本2", "引用文本3"];
        const authors = ["作者1", "作者2", "作者3"];
        const imageUrls = ["图片链接1", "图片链接2", "图片链接3"];

        // 生成安全的随机索引(避免超出数组长度)
        const maxIndex = Math.min(quotes.length, authors.length, imageUrls.length);
        const randomIndex = Math.floor(Math.random() * maxIndex);
        // 生成1-1000的随机数
        const randomNum = Math.floor(Math.random() * 1000) + 1;

        // 构建Embed(注意参数格式)
        const quoteEmbed = new EmbedBuilder()
            .setColor('#0099ff')
            .setTitle(`随机引用 #${randomNum}`)
            .setDescription(quotes[randomIndex])
            .setAuthor({ name: authors[randomIndex] }) // 此处必须传对象,不能直接传字符串
            .setImage(imageUrls[randomIndex])
            .setTimestamp();

        // 正确回复交互
        await interaction.reply({ embeds: [quoteEmbed] });
    },
};

四、关键修正点

  1. setAuthor()参数:必须传入对象(如{ name: '作者名' }),而非直接传字符串,这是触发「expected an object and received string instead」的最常见原因;
  2. 随机索引安全处理:用Math.min()确保索引不会超出任意一个数组的有效范围,避免取到undefined;
  3. 交互回复格式:interaction.reply()的参数必须是包含embeds数组的对象,数组内放Embed实例。

内容的提问来源于stack exchange,提问作者Anguished Coney

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 08:05:23