Cannot send an empty message form like {embeds:[embed]} - javascript

I wrote a new command when my bot ran on my pc and not a server.
While the bot ran on my pc the command worked very well, but after I put my bot into a server
the command stopped working and I always get an error message:
DiscordAPIError: Cannot send an empty message
The code:
const Discord = require("discord.js");
const recon = require('reconlx');
const rpages = recon.ReactionPages
const moment = require('moment');
const fs = require('fs');
module.exports = class HelpCommand extends BaseCommand {
constructor() {
super('help', 'moderation', []);
}
async run(client, message, args) {
const y = moment().format('YYYY-MM-DD HH:mm:ss')
const sayEmbed1 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed2 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed3 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed5 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed4 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed6 = new Discord.MessageEmbed()
.setTitle(`example`)
.setDescription("[A készítőm Weboldala](https://istvannemeth1245.wixsite.com/inde/)\n\n")
try {
await
message.delete();
const pages = [{ embed: sayEmbed1 }, { embed: sayEmbed2 }, { embed: sayEmbed3 }, { embed: sayEmbed4 }, { embed: sayEmbed5 }, { embed: sayEmbed6 }];
const emojis = ['◀️', '▶️'];
const textPageChange = true;
rpages(message, pages, textPageChange, emojis);
} catch (err) {
console.log(err);
message.channel.send('Nem tudom ki írni az üzenetet');
}
const contetn = `\n[${y}] - ${message.author.username} használta a help parancsot. `;
fs.appendFile('log.txt', contetn, err => {
if (err) {
console.err;
return;
}
})
}
}
Full error message:
throw new DiscordAPIError(request.path, data, request.method, res.status);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/container/Lee-Goldway/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async RequestHandler.push (/home/container/Lee-Goldway/node_modules/discord.js/src/rest/RequestHandler.js:39:14) {
method: 'post',
path: '/channels/833629858210250813/messages',
code: 50006,
httpStatus: 400
}

A couple of things. Are you sure that this reconlx package is compatible with your discord.js version? It's always a good idea to post your discord.js version when you have a problem with libraries.
If you're using reconlx v1, you can see in their old documentation that in ReactionPages the second parameter takes an array of embeds. If you check the source code, you can see that it tries to send the first item of pages as an embed, like this: message.channel.send({ embeds: [pages[0]] }).
It means that with your code embeds is an array where the first item is an object that has an embed key with the sayEmbed1 embed, while discord.js accepts an array of MessageEmbeds.
I would try to pass down an array of embeds like this:
const pages = [
sayEmbed1,
sayEmbed2,
sayEmbed3,
sayEmbed4,
sayEmbed5,
sayEmbed6,
];
PS: ki írni is incorrect. When the verb particle precedes the verb, they are written as one word. So, it should be kiírni. :)

In the code provided, there appears to be no code that references "{embeds:[embed]}".
However, assuming the error is coming from this line:
message.channel.send('Nem tudom ki írni az üzenetet');
Referring to the official documentation, you can provide an object.
For example:
message.channel.send({ content: 'Nem tudom ki írni az üzenetet' });

Related

Discord.js Invalid Form Body [duplicate]

This question already has an answer here:
why register slash commands with options doesn't work (discord.js)
(1 answer)
Closed 2 months ago.
At the time I am trying to learn how to make a discord bot and I got an error I dont know waht it means or how to fix it. I made a command for welcome messages with a youtube tutorial and now it stopped working.
Error:
DiscordAPIError[50035]: Invalid Form Body
7.options[0].name[APPLICATION_COMMAND_INVALID_NAME]: Command name is invalid
at SequentialHandler.runRequest (C:\Users\hp\OneDrive\Desktop\Manager\node_modules\#discordjs\rest\dist\index.js:659:15)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.queueRequest (C:\Users\hp\OneDrive\Desktop\Manager\node_modules\#discordjs\rest\dist\index.js:458:14)
at async REST.request (C:\Users\hp\OneDrive\Desktop\Manager\node_modules\#discordjs\rest\dist\index.js:902:22)
at async GuildApplicationCommandManager.set (C:\Users\hp\OneDrive\Desktop\Manager\node_modules\discord.js\src\managers\ApplicationCommandManager.js:173:18)
Code:
const {Message, Client, SlashCommandBuilder, PermissionFlagsBits} = require("discord.js");
const welcomeSchema = require("../../Models/Welcome");
const {model, Schema} = require("mongoose");
module.exports = {
name:"setup-welcome",
description:"Set up your welcome message for the discord bot.",
UserPerms:["BanMembers"],
category:"Moderation",
options: [
{
name:"Channel",
description:"Channel for welcome messages.",
type:7,
required:true
},
{
name:"welcome-message",
description:"Enter your welcome message.",
type:3,
reqired:true
},
{
name:"welcome-role",
description:"Enter your welcome role.",
type:8,
required:true
}
],
async execute(interaction) {
const {channel, options} = interaction;
const welcomeChannel = options.getChannel("channel");
const welcomeMessage = options.getString("welcome-message");
const roleId = options.getRole("welcome-role");
if(!interaction.guild.members.me.permissions.has(PermissionFlagsBits.SendMessages)) {
interaction.reply({content: "I don't have permissions for this.", ephemeral: true});
}
welcomeSchema.findOne({Guild: interaction.guild.id}, async (err, data) => {
if(!data) {
const newWelcome = await welcomeSchema.create({
Guild: interaction.guild.id,
Channel: welcomeChannel.id,
Msg: welcomeMessage,
Role: roleId.id
});
}
interaction.reply({content: 'Succesfully created a welcome message', ephemeral: true});
})
}
}
I tried a few things like changing the construction of the bot or change some thing like the command options.
Thanks in advance!
Your Channel argument is invalid, since all names need to be lowercase only. Change it to channel, for example, and it will work.

Discord.JS - I am getting 'Application did not respond' but no errors in console

So I'm not getting any errors in the console with this code but it is causing an error in discord where it just says 'Application did not respond'. I'm just wondering if there is something I am doing wrong. I have tried following the Discord.JS official documentation/guides to get this far.
This is all in a command handler.
My desired outcome is to mention the author of the message.
const { Client, SlashCommandBuilder, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
module.exports = {
data: new SlashCommandBuilder()
.setName('cleanthedecks')
.setDescription('Tells a user to clean the decks'),
async execute(interaction) {
client.on('message', (message) => {
const user = message.author;
await interaction.reply(`${user} Get the decks cleaned immediately with /deckscrub`);
console.log(user);
})
}
}
Ok I figured it out. I can just use the 'interaction' class to get the user and on top of that the username.
So my working code is
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('cleanthedecks')
.setDescription('Tells a user to clean the decks'),
async execute(interaction) {
const user = interaction.user.username;
await interaction.reply(`${user} Get the decks cleaned immediately with /deckscrub`);
console.log(user);
}
}

DiscordAPIError: Cannot send an empty message at RequestHandler.execute

As one of the first bigger js/node projects I decided to make a discord bot using discord.js. Every user is able to add new messages to the repl.it (the website I host the bot on) database and read random ones. The bot is working fine so I wanted to make it reply with embeds because it looks better and that is where the problem is.
I don't get any errors when making the embed but when I try to send it to the chat it says that it can't send an empty message at the RequestHandler.execute. Here is the full error message:
/home/runner/anonymous-message/node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/runner/anonymous-message/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/runner/anonymous-message/node_modules/discord.js/src/rest/RequestHandler.js:51:14) {
method: 'post',
path: '/channels/880447741283692609/messages',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: 0,
message_reference: { message_id: '970404904537567322', fail_if_not_exists: true },
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
And here is the full code:
const Discord = require("discord.js")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
const keepAlive = require("./server.js") //just a webserver that I combine with uptimerobot.com so the bot doesn't go offline
const Database = require("#replit/database")
const db = new Database()
client.login(process.env.TOKEN) //since all replits are public (unless you buy the premium) you can use the environment variables to keep somestuff private
let prefix = "msg "
let channel
let starterMessages = ["a random test message!", "Hello World!", "why is this not working"]
db.get("msgs", messages => {
if (!messages || messages.length < 1) {
db.set("msgs", starterMessages)
}
})
client.on("ready", () => {
console.log("bot is working")
})
client.on("messageCreate", (msg) => {
channel = msg.channel.guild.channels.cache.get(msg.channel.id)
switch (true) {
case msg.content.toLowerCase().startsWith(prefix + "ping"):
channel.send("the bot is working")
break
case msg.content.toLowerCase().startsWith(prefix + "send"):
let exists = false
let tempMsg = msg.content.slice(prefix.length + 5, msg.length)
if (tempMsg.length > 0) {
db.get("msgs").then(messages => {
for (i = 0; i < messages.length; i++) {
if (tempMsg.toLowerCase() === messages[i].toLowerCase()) { exists = true }
}
if (exists === false) {
console.log(tempMsg)
messages.push(tempMsg)
db.set("msgs", messages)
msg.delete() //deletes the message so no one knows who added it
} else {
console.log("message already exists") //all console logs are for debugging purposes
}
});
}
break
case msg.content.toLowerCase().startsWith(prefix + "read"):
db.get("msgs").then(messages => {
let rndMsg = messages[Math.floor(Math.random() * messages.length)] //gets the random message from the database
//Here I make the embed, it doesn't give any errors
let newEmbed = new Discord.MessageEmbed()
.setColor("#" + Math.floor(Math.random() * 16777215).toString(16))
.setTitle("a message from a random stranger:")
.setURL("https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstley")
.addFields({ name: rndMsg, value: `if you want to send one of these for other people to read? Type "${prefix}send [MESSAGE]"` })
.setFooter({ text: `type "${prefix}help" in the chat for more info!` })
msg.channel.send(newEmbed) //and here is the problem. Without this line it runs with no errors
});
break
}
})
keepAlive() //function from the webserver
I couldn't find any answers to this problem on the internet so I'm hoping you can answer it. Thanks in advance!
Since you're using (I assume) discord.js v13, the way to send embeds is this:
msg.channel.send({embeds: [newEmbed]});
That should solve your problem.

Is there a way to get user from mention discordjs v12?

Sorry if there are any typos, but english is not my first language.
Hi, I have a problem when I am trying to get userinfo from a mention. It works perfectly fine when I am doing the command on a non nicknamed user, but when I try on a nicknamed user, it only returns undefined.
Keep in mind that I am using WOKCommands to handle my slash commands, and the error is happening on a slash command.
Here is the code for the command:
const { MessageEmbed } = require('discord.js');
const moment = require('moment');
module.exports = {
slash: true,
testOnly: true,
description: 'En spioneringskommando.',
minArgs: 1,
expectedArgs: '<Mention>',
callback: ({ args, client, interaction }) => {
const userId = args[0].toString().replace(/[\\<>##&!]/g, "");
const guild = client.guilds.cache.get(interaction.guild_id);
const member = guild.members.cache.get(userId);
const embed = new MessageEmbed()
.setTitle("Spioneringsprogram v1.0")
.setDescription(`Bruker: ${member.user.username}`)
.setColor("RANDOM")
.addField("Kallenavn:", `${member.nickname ? `${member.nickname}` : 'Ingen'}`, false)
.addField("Ble medlem av discord:", `${moment.utc(member.user.createdAt).format('DD/MM/YY')}`, false)
.addField("Ble medlem av discord serveren:", `${moment.utc(member.joinedAt).format('DD/MM/YY')}`, false)
.setFooter(`ID: ${member.user.id}`)
.setTimestamp();
return embed;
}
}
And here is my index.js file:
require('dotenv').config();
const Discord = require("discord.js");
const WOKCommands = require('wokcommands');
const client = new Discord.Client();
const guildId = 'censored'
client.on('ready', () => {
console.log("Bot is ready!");
new WOKCommands(client, {
commandsDir: 'commands',
testServers: [guildId],
showWarns: false
});
});
Thanks for any help I can get.
since you got the command as a slash command ("slashCommand:true")
You should be using "interaction."
examples:
(interaction.user.username) // The username of the interaction's user
(interaction.user.id) // The id of the interaction's user
(interaction.user.avatarURL)// The avatar's url of the interaction's user
But you seem to be new to wokcommands, and slash commands at general, so contact me at: Glowy#8213
And i'll help you out

Bot has roblem with sending/editing embed messages

So i already asked around here and there but i dont find out how to fix eroor: ReferenceError: send is not defined In the non embed version everything works fine but here it just won't.
module.exports = {
name: 'lat2',
description: 'Let the Bot display latency/Response Time and API latency/"Remote Response time"',
execute(message, args) {
const Discord = require('discord.js');
let Embed1 = new Discord.MessageEmbed()
.setColor(0x0099ff)
.setDescription("Pinging...")
let Embed2 = new Discord.MessageEmbed()
.setColor(0x0099ff)
.setTitle("Latencies")
.setDescription(`Latency/Response Time: ${send.createdTimestamp - message.createdTimestamp}ms\nAPI latency/"Remote Response time": ${Math.round(message.client.ws.ping)}ms`)
msg.channel.send(Embed1).then(msg => {
msg.edit(Embed2);
});
}
};
The problem isn't sending the message, it's complaining about the ${send.createdTimestamp}, because you didn't define "send" anywhere there.
Try replacing it with message.createdAt
To still get the Latency, try this:
module.exports = {
name: 'lat2',
description: 'Let the Bot display latency/Response Time and API latency/"Remote Response time"',
execute(message, args) {
const Discord = require('discord.js');
let Embed1 = new Discord.MessageEmbed()
.setColor(0x0099ff)
.setDescription("Pinging...")
msg.channel.send(Embed1).then(m => {
let Embed2 = new Discord.MessageEmbed()
.setColor(0x0099ff)
.setTitle("Latencies")
.setDescription(`Latency/Response Time: ${m.createdTimestamp - message.createdTimestamp}ms\nAPI latency/"Remote Response time": ${Math.round(message.client.ws.ping)}ms`)
m.edit(Embed2);
});
}
};

Categories