I'm writing a simple discord bot that just spews out a randomly selected response from a list but I keep running into the same Discord API error.
Here's my code.
client.on('messageCreate', message => {
const responses = [['Yehaw', 'Yehaw!!', 'Yahee', 'Cowboy shit']];
let randomNumber = Math.floor(Math.random() * Math.floor(responses.length));
let randomMessage = responses[randomNumber];
if (message.author.bot) return;
if (message.content.includes ('Yehaw'))
message.channel.send(randomMessage);
});
Here's my error message
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (C:\Users\User\Desktop\DiscordBot\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\User\Desktop\DiscordBot\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async TextChannel.send (C:\Users\User\Desktop\DiscordBot\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:176:15) {
method: 'post', path: '/channels/976509969199407185/messages', code: 50006, httpStatus: 400,
I've tried a few variations on the message selection method but they all throw the same error
CodePudding user response:
The reason why you are getting this error is because you are trying to send an array instead of text. If you look closely at your code, you will notice that the actual responses array is inside another array, so when you randomly pick one, it will always be the full array instead of one of the responses in it. So randomMessage
will always be this array => ["Yehaw", "Yehaw!!", "Yahee", "Cowboy shit"]
. discord.js
cannot send arrays as text which is why you are getting this error. So all you have to do is remove the extra square brackets so your final code might look something like this:
client.on("messageCreate", (message) => {
const responses = ["Yehaw", "Yehaw!!", "Yahee", "Cowboy shit"];
let randomNumber = Math.floor(Math.random() * Math.floor(responses.length));
let randomMessage = responses[randomNumber];
if (message.author.bot) return;
if (message.content.includes("Yehaw")) message.channel.send(randomMessage);
});