DiscordAPIError: Cannot send an empty message on MessageEmbed

Viewed 25

The yesno API works independently as intended but when I try to include it in my main index file, it throws an error.

[FATAL] Possibly Unhandled Rejection at: Promise Promise { DiscordAPIError: Cannot send an empty message at RequestHandler.execute (Z:\Discordbot\node_modules\discord.js\src\rest\RequestHandler.js:298:13) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async RequestHandler.push (Z:\Discordbot\node_modules\discord.js\src\rest\RequestHandler.js:50:14) at async TextChannel.send (Z:\Discordbot\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:171:15) { method: 'post', path: '/channels/999743514390839296/messages', code: 50006, httpStatus: 400, requestData: { json: [Object], files: [] }

Main code: Index.js

Including

let client = new Discord.Client(); #throws missing client intent error else the above errors.

let Discord = require("discord.js");
let axios = require("axios");
const {
    Client,
    Intents
} = require('discord.js');
const {
    bot_token,
    status
} = require('./misc/config.json');
const client = new Client({
    intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGE_TYPING, Intents.FLAGS.GUILD_MESSAGES]
});
const required = {
    prefix: ".ask",
    API: "https://yesno.wtf/api",
    embedColor: {
        yes: "#66bb6a",
        no: "#ef5350",
        maybe: "#26c6da"
    },
    answers: {
        yes: "Yep ✅",
        no: "No ",
        maybe: "Maybe"
    },

};

const { prefix, API, embedColor, answers } = required;

client.util = require('./util');

client.on('warn', err => console.warn('[WARNING]', err));

client.on('error', err => console.error('[ERROR]', err));

client.on('disconnect', () => {
    console.warn('Disconnected!')
    process.exit(0);
});

client.on('uncaughtException', (err) => {
    console.log('Uncaught Exception: ' + err)
    process.exit(1)
});

client.on('messageCreate', (msg) => {
    if (msg.author.bot) return;
    if (msg.guild) {
        if (msg.content.startsWith(`<@${msg.client.user.id}>`) || msg.content.startsWith(`<@!${msg.client.user.id}>`) || msg.content.toLowerCase().startsWith('heybot')) {
            client.util.handleTalk(msg);
        }
    }
});

client.on('ready', () => {
    client.util.handleStatus(client, status);
    console.log('[Bot] Ready');
});

process.on('unhandledRejection', (reason, promise) => {
    console.log('[FATAL] Possibly Unhandled Rejection at: Promise ', promise, ' reason: ', reason.message);
});

client.on("messageCreate", (message) => {
    if (message.content.startsWith(`${prefix} `)) {
        const question = message.content.substr(prefix.length + 1);

        let embedError = new Discord.MessageEmbed()
            .setFooter(`Sorry, ${message.author.tag}`)
            .setTimestamp()
            .setDescription("An error occurred while predicting your future!");

        axios.get(API)
            .then((r) => {
                let embedResponse = new Discord.MessageEmbed()
                    .setFooter(`${question} (${message.author.tag})`)
                    .setTimestamp()
                    .setImage(r.data.image);

                switch (r.data.answer) {
                    default: 
                        message.channel.send({embed: embedError});
                        break;
                    case "yes":
                        embedResponse.setColor(embedColor.yes);
                        embedResponse.setTitle(answers.yes);
                        message.channel.send({ embed: embedResponse });
                        break;
                    case "no":
                        embedResponse.setColor(embedColor.no);
                        embedResponse.setTitle(answers.no);
                        message.channel.send({ embed: embedResponse });
                        break;
                    case "maybe":
                        embedResponse.setColor(embedColor.maybe);
                        embedResponse.setTitle(answers.maybe);
                        message.channel.send({ embed: embedResponse });
                        break;
                }
            })
            .catch((o_O) => {
                console.log(o_O);
                message.channel.send({ embed: embedError })
            });
    }
});

client.login(bot_token);

util.js

const request = require('node-fetch');
const {
    URL,
    URLSearchParams
} = require('url');
const {
    chat
} = require('./misc/config.json');
const mainURL = new URL(chat.url);
const urlOptions = {
    bid: chat.brainID,
    key: chat.key,
    uid: null,
    msg: null
};
const handleStatus = (client, status) => {
    client.user.setStatus(status.state);
    client.user.setActivity(status.name, {
        type: status.type
    });
};

const handleTalk = async (msg) => {
    msg.content = msg.content.replace(/^<@!?[0-9]{1,20}> ?/i, '');
    if (msg.content.length < 2 || (!isNaN(chat.channel) && chat.channel != msg.channel.id)) return;
    msg.channel.sendTyping();
    urlOptions.uid = msg.author.id;
    urlOptions.msg = msg.content;
    mainURL.search = new URLSearchParams(urlOptions).toString();
    try {
        let reply = await request(mainURL);
        if (reply) {
            reply = await reply.json();
            msg.reply({
                content: reply.cnt,
                allowedMentions: {
                    repliedUser: false
                }
            })
        }
    } catch (e) {
        console.log(e.stack);
    }
};

module.exports = {
    handleStatus,
    handleTalk
};

config.json

{
    "bot_token": "",
    "status": {
        "state": "idle",
        "type": "LISTENING",
        "name": "."
    },
    "chat": {
        "url": "http://api.brainshop.ai/get",
        "brainID": "",
        "key": "",
        "channel": "999743514390839296"
    }
}

Edit: Thanks to Dumbass for giving a heads up. This was a source from Discord v11, had to change the following to upgrade it to V13 in addition to the answer below. The discord.js V13 guide example didn't work for me. Kept throwing "EMBED_FOOTER_TEXT" error.

     .setFooter(`Sorry, ${message.author.tag}`)

to

    .setFooter([` Sorry ${message.author.tag}`,].join('\n'))

More about it in this post, refer answer by Leau

1 Answers

When sending an embed, you need to pass an array of EmbedBuilders to the embeds field of the TextChannel.send() options. Ex: message.channel.send({ embeds: [embed] })

Related