DiscordAPIError: Cannot send an empty message (discord.js v13) - discord.js

I am coding a bot with the below command and it throws an error, but i don't know where is the error
i tried my best
const Discord = require("discord.js");
const client = new Discord.Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if(!reason) reason = "No reason given."
if(!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if(!member) return message.channel.send("❌ You didn't mention a member!")
if(member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then (() => {
const embed = new Discord.MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
embed.setFooter(`Requested by ${message.author.username}`)
message.channel.send(embed)
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(error => {
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
If I have made a mistake, please help me out
Sorry I don't speak English well

Try the below code out, I made notes along the way to explain as well as improved a small bit of code. I assume this is a collection of 2 separate files which is why they are separated. If they aren't 2 separate files, you do not need the top section, just the bottom.
const {
Client,
Intents,
MessageEmbed
} = require("discord.js");
const client = new Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
const {
MessageEmbed,
Permissions
} = require("discord.js");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if (!reason) reason = "No reason given."
if (!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if (!member) return message.channel.send("❌ You didn't mention a member!")
if (member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then(() => {
const embed = new MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
.setFooter({
text: `Requested by ${message.author.username}`
})
// author and footer are now structured like this
// .setAuthor({
// name: 'Some name',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// url: 'https://discord.js.org',
// })
// .setFooter({
// text: 'Some footer text here',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// })
message.channel.send({
embeds: [embed]
}) //embeds must be sent as an object and this was the actual line that was causing the error.
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(() => { // if error is not used, it is not required to be stated
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}

Related

discord interaction.deferUpdate() is not a function

I'm creating a message with buttons as reaction roles but do the reaction role handling in another file so it stays loaded after a reset but it either says "interaction.deferUpdate() is not a function, or in discord it says "this interaction failed" but it gave/removed the role
my code for creating the message:
const { ApplicationCommandType, ActionRowBuilder, ButtonBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
name: 'role',
description: "reactionroles",
cooldown: 3000,
userPerms: ['Administrator'],
botPerms: ['Administrator'],
run: async (client, message, args) => {
const getButtons = (toggle = false, choice) => {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel('member')
.setCustomId('member')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
new ButtonBuilder()
.setLabel('member2')
.setCustomId('member2')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
);
return row;
}
const embed = new EmbedBuilder()
.setTitle('Wähle eine rolle')
.setDescription('Wähle die rolle, die du gern haben möchtest')
.setColor('Aqua')
message.channel.send({ embeds: [embed], components: [getButtons()] })
.then((m) => {
const collector = m.createMessageComponentCollector();
collector.on('collect', async (i) => {
if (!i.isButton()) return;
await i.deferUpdate();
});
});
}
};
code for the reaction role:
const fs = require('fs');
const chalk = require('chalk')
var AsciiTable = require('ascii-table')
var table = new AsciiTable()
const discord = require("discord.js");
table.setHeading('Events', 'Stats').setBorder('|', '=', "0", "0")
module.exports = (client) => {
client.ws.on("INTERACTION_CREATE", async (i) => {
let guild = client.guilds.cache.get('934096845762879508');
let member = await guild.members.fetch(i.member.user.id)
let role = guild.roles.cache.find(role => role.name === i.data.custom_id);
if (!member.roles.cache.has(role.id)) {
member.roles.add(role);
} else {
member.roles.remove(role);
}
return i.deferUpdate()
})
};
The client.ws events give raw data (not discord.js objects), so the .deferUpdate() method doesn't exist there. You should be using client.on("interactionCreate")
client.on("interactionCreate", async (i) => {
// ...
return i.deferUpdate()
})

ServerInfo DiscordJS Issue

My issue here is when I execute the command the owner is only undefined instead of the actual owner of the server. How can I fix this issue?
module.exports.run = async (client, message, args) => {
const { MessageEmbed } = require('discord.js');
message.delete();
const guild = message.guild;
const Emojis = guild.emojis.cache.size || "No Emoji!";
const Roles = guild.roles.cache.size || "No Roles!";
const Members = guild.memberCount;
const Humans = guild.members.cache.filter(member => !member.user.bot).size;
const Bots = guild.members.cache.filter(member => member.user.bot).size;
const owner = guild.owner.user.tag
const embed = new MessageEmbed()
.setTitle(guild.name + " Information!")
.setColor("2F3136")
.setThumbnail(guild.iconURL())
.addField(`Name`, `${guild.name}`, true)
.addField(`Owner`, `${owner}`, true)
.addField(`ID`, `${guild.id}`, true)
.addField(`Roles Count`, `${Roles}`, true)
.addField(`Emojis Count`, `${Emojis}`, true)
.addField(`Members Count`, `${Members}`, true)
.addField(`Humans Count`, `${Humans}`, true)
.addField(`Bots Count`, `${Bots}`, true)
.addField(`Server Created At`, guild.createdAt.toDateString())
.setFooter(`Requested by ${message.author.username}`)
.setTimestamp();
message.channel.send({ embeds: [embed] });
}
module.exports.config = {
name: "serverinfo",
aliases: [""]
}
I'm pretty sure that there isn't an owner property in a Guild. To get the owner you have two methods:
Method 1 is using the .fetchOwner() method of a Guild
const owner = await message.guild.fetchOwner().user.tag
Method 2 is getting the owner id and then fetching the user from guild.members:
const owner = message.guild.members.cache.get(message.guild.ownerId)
You can choose which method is better for you

Cannot work out why i cannot find member name and name channel

using the code below i keep getting errors saying cannot find name 'member' and name 'channel' any help would be lovely also if you see any other issues thanks :)
import DiscordJS, { Guild, Intents, Message, GuildMember } from 'discord.js'
import dotenv from 'dotenv'
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.GUILD_MEMBERS
]
})
client.on('ready', ()=>{
console.log('Santa is coming')
const CF = Boolean(member.guild.channels.cache.find(channel => channel.name === 'welcome'))
if (CF == true){
console.log('Found it!')
}
})
client.on('messageCreate', (message) =>{
if (message.content == 'santa?'){
message.react('🎅')
message.reply({
content: "HO, HO, HO, I'll be coming soon!"
})
}
})
client.login(process.env.TOKEN)
On v13.2.0 :
const CF = Boolean(member.guild.channels.cache.find(channel => channel.name === 'welcome'))
Here you put member which you didn't define yet.
Use client.channels.fetch instead
const CF = Boolean(client.channels.fetch(<id of the channel>))

Discord.js V13 Adding role when using a slash command

I am trying to code a bot that when you use a certain slash command, it gives you a role. I have looked for a solution but haven't been able to find one. Nothing is seeming to work for me, i keep getting errors about the code, like "message not found, did you mean Message"
This is my first time trying to code a bot so if its a dumb issue, please bear with me.
Here is my code:
import DiscordJS, { Intents, Message, Role } from 'discord.js'
import dotenv from 'dotenv'
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
],
})
// Slash Commands
//ping pong command
client.on('ready', () => {
console.log('BOT ONLINE')
//bot test server
const guildId = '868857440089804870'
const guild = client.guilds.cache.get(guildId)
const role = client.guilds.cache.find(r => r.name == "Test Role to
give")
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application?.commands
}
commands?.create({
name: 'ping',
description: 'says pong'
})
commands?.create({
name: "serverip",
description: 'Gives user the server IP'
})
commands?.create({
name: "giverole",
description: 'Gives user the role'
})
})
client.on('interactionCreate', async (interaction) => {
if(!interaction.isCommand()) {
return
}
const { commandName, options } = interaction
//This is the role id that i want to give
const role = '884231659552116776'
//these are the users that i want to give the role to
const sniper = '725867136232456302'
const josh = '311981346161426433'
if (commandName === 'ping') {
interaction.reply({
content: 'pong',
ephemeral: true,
})
} else if (commandName === 'serverip') {
interaction.reply({
content: 'thisisserverip.lol',
ephemeral: true,
})
} else if (commandName === 'giverole') {
interaction.reply({
content: 'Role given',
ephemeral: true,
})
}
})
client.login(process.env.test)
You can just simply retrieve the Interaction#Member and add the role to them using GuildMemberRoleManager#add method!
const role = client.guilds.cache.find(r => r.name == "Test Role to
give");
await interaction.member.roles.add(role); // and you're all set! welcome to stackoverflow 😄
if (commandName === 'giverole') {
const role = client.guilds.cache.find(r => r.name == "Ahmed1Dev")
await user.roles.add(role)
message.channel.send("Done Added Role For You") // Fixed By Ahmed1Dev
}

im trying to make a simple discord.js bot

i am trying to make it so as soon as you type: mememe it will react with: your nickname is now:
my current code is
const Discord = require("discord.js");
const client = new discord.client();
client.login(process.env.SECRET);
const embed = new Discord.MessageEmbed()
.setTitle("This is Embed Title")
.setDiscription("this is embed discription")
.setColor("RANDOM")
.SetFooter("This is Embed Footer");
const nicknames = ["dumbass", "idiot", "op", "man", "power", "docter"];
client.on("ready", () => {
client.user.setPresence({ activity: { name: "brave" }, status: "invisible" });
});
client.on("message", (message) => {
if (message.content === "ding") {
message.channel.send === "dong";
}
if (message.content === "embed") {
message.channel.send(embed);
}
});
if (message.content("mememe")) {
const index = Math.floor(Math.random() * nicknames.length);
message.channel.send(nicknames[index]);
}
but i dont know why it does not work it says as a error: Parsing error: Unexpected token
that is all and idk how to fix that
Edit : you guys were useless
I first want to say: Please fix your indents (I did it for you below here.
const Discord = require("discord.js")
const client = new Discord.Client()
client.login(process.env.SECRET)
// const embed = new Discord.MessageEmbed()
// .setTitle("This is Embed Title")
// .setDiscription("this is embed discription")
// .setColor("RANDOM")
// .SetFooter("This is Embed Footer");
const nicknames = ["dumbass", "idiot" , "op" , "man" , "power" , "docter"]
client.on("ready" , () => {
client.user.setPresence({ activity: { name: "brave"}, status: "invisible"})
})
client.on("message" , message => {
if(message.content === ("ding")) {
message.channel.send === ("dong")
}
if(message.content === ("embed")) {
message.channel.send(embed)
}
if(message.content === ("mememe")) {
const index = Math.floor(Math.random() * nicknames.length);
message.channel.send(nicknames[index])
}
})
The issue was you were calling the mememe command wrong. Above you used messega.content === "..."
In the mememe command you used message.content("mememe"). This does not work. Changes it (or copying the code above should fix the issue. Maybe an idea for you. You could add a feature where it changes the Users Nickname instead of sending a random one.

Resources