Discord.js UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message - javascript

Ok, so I just started working on a discord bot and implemented a command handler, and I immediately ran into some problems.
const Discord = require("discord.js");
module.exports = {
name: "kick",
description: "Kicks the mentioned user",
execute(message, args) {
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
try {
const kickEmbed = new Discord.RichEmbed()
.setTitle("You were Kicked")
.setDescription("You were kicked from Bot Testing Server.");
user.send({ kickEmbed }).then(() => {
member.kick();
});
} catch (err) {
console.log("failed to kick user");
}
}
}
};
when i execute the kick command in my server, I get the following error
UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message
I can't seem to find anything wrong with the code so, where's the error

When sending an embed that uses the Discord Rich Embed builder you don't need to use the curly brackets.
Instead of user.send({ kickEmbed }) you should do user.send(kickEmbed). I ran into that issue before and it helped in my case.

Related

Node.js - Discord.js v14 - fetching a channel returns undefined / does not work

Attempting to define channel with this code will return undefined.
const { Events, InteractionType, Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
],
})
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if(interaction.type == InteractionType.ApplicationCommand){
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
}
else if(interaction.isAutocomplete()){
const command = interaction.client.commands.get(interaction.commandName);
if(!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try{
await command.autocomplete(interaction);
} catch(error) {
console.error(error);
}
}
else if(interaction.isButton()){
console.log(client.channels);
const channel = await client.channels.fetch('1074044721535656016 ');
console.log(client.channels);
console.log(channel);
}
},
};
const channel = await client.channels.fetch('1074044721535656016 '); Is the main line here.
At the bottom and top of the code is where the important stuff for this question is. I believe I am not properly using the fetch method.
As evidenced by console.log(client.channels); I'm trying to look at the channels cache, but for some reason the channel isn't there, hence I'm using fetch() instead of cache.get().
Thank you for the help!
Other info:
Running npm list shows:
discord.js#14.7.1, dotenv#16.0.3
Node.js v19.6.0
How I got my channel id
Error Message:
ChannelManager {} //<--- this is from the first console.log
node:events:491
throw er; // Unhandled 'error' event
^
Error: Expected token to be set for this request, but none was present
Is the problem because the channel is undefined or because it hasn't resolved yet?
Check your channel ID it may be formatted like:
guild id / channel id
Use interaction.client instead of making a new client object. The interaction already has its own client object with the related properties.

"DiscordAPIError[40060]: Interaction has already been acknowledged." Throws this when ever i run a command on discord [duplicate]

I am creating a bot using guide by Discord.js, however after like 3 or sometimes 3 commands the bot stops working and i get
discord message
i have tried to restart it many times but after sometime it just stop working again and again
const fs = require('node:fs');
const path = require('node:path')
const { Client, Events, GatewayIntentBits, Collection ,ActionRowBuilder,EmbedBuilder, StringSelectMenuBuilder } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();
const commandsPath = path.join(__dirname,'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath,file);
const command = require(filePath);
if('data' in command && 'execute' in command){
client.commands.set(command.data.name,command);
}else{
console.log(`[WARNING] The command at ${filePath} is missing`);
}
}
client.once(Events.ClientReady, () => {
console.log('Ready!');
})
//menu
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'ping') {
const row = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('select')
.setPlaceholder('Nothing selected')
);
const embed = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('pong')
.setDescription('Some description here')
.setImage('https://media.istockphoto.com/id/1310339617/vector/ping-pong-balls-isolated-vector-illustration.jpg?s=612x612&w=0&k=20&c=sHlz5sbJrymDo7vfTQIuaj4lbmwlvAhVE7Uk_631ZA8=')
await interaction.reply({ content: 'Pong!', ephemeral: true, embeds: [embed]});
}
});
//======================================================================================================================
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand ||
interaction.isButton() ||
interaction.isModalSubmit()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found`)
return;
}
try {
await command.execute(interaction);
}catch(error){
console.error(error);
await interaction.reply({content: 'There was an error while executing this command!', ephemeral: true});
}
console.log(interaction);
});
client.login(token);
Error i get in terminal
I wanted this bot to continue to execute commands as long as it's up and running
This is a common error in Discord.JS that occurs when you already replied to an interaction and you attempt to reply again.
From the discord.js discord server:
You have already replied to the interaction.
• Use .followUp() to send a new message
• If you deferred reply it's better to use .editReply()
• Responding to slash commands / buttons / select menus
To fix this error, you can use .followUp() to send another message to the channel or .editReply() to edit the reply as shown above.
You can see the documentation on a command interaction here
Yes the problem is that you cant reply to a slash command more then once in discords api so instead you should use
interaction.channel.send()
or
interaction.editReply()

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.

Unable to get a channel in discord.js

So, I have been making a suggestions command in discord.js and I keep getting the following error:
Cannot read property 'channels' of undefined
Here is my code, I have tried changing it in many ways but it doesn't work.
module.exports = {
name: "suggestion",
aliases: ['suggest', 'suggestion'],
permissions: [],
description: "suggetion command",
execute(message, args, cmd, client, discord) {
let channel = message.guild.channels.cache.get("865868649839460353");
if (!channel)
return message.reply('A suggestions channel does not exist! Please create one or contact a server administrator.')
.then(message => {
message.delete(6000)
})
.catch(error => {
console.error;
});
}
}
1st idea: The channel you're executing in is not a guild.
By fixing this, you can do:
if(!message.guild){
return
}
2nd idea: You may have specify the wrong channel in the wrong server. Do the following:
let guild = client.guilds.cache.get(`YourGuildId`)
let channel = guild.channels.cache.get(`ChannelId`)
or
let guild = client.guilds.cache.get(`${message.guild.id}`)
let channel = guild.channels.cache.get(`ChannelId`)
I hope these idea helped you! <3

Snipe command returning something I haven't seen before?

so I have a snipe command that works, but after a few uses it returns this? Not sure exactly what's going on, haven't seen it before in any of my bots to my knowledge
(node:2994) UnhandledPromiseRejectionWarning: AbortError: The user aborted a request.
The scripts look like this, however to my eyes they're just a standard database snipe command -
messageDelete event in index.js -
client.on('messageDelete', async (message) => {
db.set(`snipe.content`, message.content);
db.set(`snipe.authorName`, message.author.tag);
db.set(`snipe.authorIcon`, message.author.displayAvatarURL({ format: 'png', dynamic: true }));
});
snipe.js -
const Discord = require('discord.js');
const db = require('quick.db');
module.exports = {
name: 'snipe',
description: 'snipe the last deleted message',
execute (client, message, args) {
let content = db.get(`snipe.content`);
let authorIcon = db.get(`snipe.authorIcon`);
let authorName = db.get(`snipe.authorName`);
const snipeEmbed = new Discord.MessageEmbed()
.setColor('RANDOM')
.setAuthor(authorName, authorIcon)
.setDescription(content)
.setTimestamp()
message.channel.send(snipeEmbed)
}
}
(node:2994) UnhandledPromiseRejectionWarning: AbortError: The user aborted a request.
This error is usually triggered when the bot can not connet to discord or database api.
P.S: I suggest add a snipe.channel property to avoid full client sniping.

Categories