Send embed commands with command handler - discord.js

So I'm building a bot with discord.js, but I'm having trouble sending commands that include embed. I can send text commands easily, such as purge, ping, time and so on, but having trouble with embeds.
This is my index.js file
const keepAlive = require('./server');
const Discord = require('discord.js');
const client = new Discord.Client();
var { readdirSync } = require('fs');
client.config = require('./config.js');
client.commands = new Discord.Collection();
for(const file of readdirSync('./commands/')) {
if(!file.endsWith(".js")) return;
var fileName = file.substring(0, file.length - 3);
var fileContents = require(`./commands/${file}`);
client.commands.set(fileName, fileContents);
}
for(const file of readdirSync('./events/')) {
if(!file.endsWith(".js")) return;
var fileName = file.substring(0, file.length - 3);
var fileContents = require(`./events/${file}`);
client.on(fileName, fileContents.bind(null, client));
delete require.cache[require.resolve(`./events/${file}`)];
}
client.login(client.config.token)
.then(() => {
if(!client.user.bot) { console.log("[JPBTips] Don't self bot idot"); return process.exit() };
console.log(`Client logged in as ${client.user.tag}`);
})
.catch((err) => {
console.error("Error while logging in: " + err);
if(err.toString().match(/incorrect login details/gi)) console.log("Make sure to change up your config!");
});
keepAlive();
And then this is my message.js code:
module.exports = (client, message) => {
if(!message.content.startsWith(client.config.prefix)) return;
if(message.author.bot) return;
const args = message.content.slice(client.config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase()
var cmd = client.commands.get(command);
if(!cmd) return;
cmd(client, message, args);
}

You should take a look at the docs for the embedBuilder
If you are using discord.js v14 you should use const { EmbedBuilder } = require('discord.js');
and if you are using discord.js v13 use const { EmbedBuilder } = require('#discordjs/builders');
That means your command file (located in your commands folder) should look something like this:
const { EmbedBuilder } = require('discord.js'); //depending on your discord.js version (this example is for v14)
exports.run = (client, message) => {
const exampleEmbed = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('Some title')
.setURL('https://discord.js.org/')
.setAuthor({ name: 'Some name', iconURL: 'https://i.imgur.com/AfFp7pu.png', url: 'https://discord.js.org' })
.setDescription('Some description here')
.setThumbnail('https://i.imgur.com/AfFp7pu.png')
.addFields(
{ name: 'Regular field title', value: 'Some value here' },
{ name: '\u200B', value: '\u200B' },
{ name: 'Inline field title', value: 'Some value here', inline: true },
{ name: 'Inline field title', value: 'Some value here', inline: true },
)
.addFields({ name: 'Inline field title', value: 'Some value here', inline: true })
.setImage('https://i.imgur.com/AfFp7pu.png')
.setTimestamp()
.setFooter({ text: 'Some footer text here', iconURL: 'https://i.imgur.com/AfFp7pu.png' });
message.reply({ embeds: [exampleEmbed] });
}
And in your message.js file you have to replace cmd(client, message, args) with cmd.run(client, message, args);
Please let me know if this works out for you and have a great vacation

can you show the file where you're trying to reply with an embed ?
Maybe the problem (without seeing your code) is:
You're writing: message.reply(embed);
But since V13 it's: message.reply({ embeds: [embed] });

Related

how to fix cannot read properties of undefined (reading 'push') in mongodb with djs

const { Client, CommandInteraction, EmbedBuilder, Permissions, ApplicationCommandType } = require("discord.js");
const { Formatters } = require('discord.js');
const blacklistedWords = require("../../Collection/index.js");
const Schema = require('../../models/blacklist.js')
module.exports = {
name: "blacklist_add",
description: "add a word to blacklist so that the members of the server cannot use the word",
userPerms: ['Administrator'],
type: ApplicationCommandType.ChatInput,
options: [{
name: 'word',
description: 'word to be added to the blacklist',
type: 3,
required: true
}],
/**
*
* #param {Client} client
* #param {CommandInteraction} interaction
* #param {String[]} args
*/
run: async (client, interaction, args) => {
const sword = interaction.options.getString('word');
console.log(sword)
const word = sword.toLowerCase();
const guild = { Guild: interaction.guild.id }
Schema.findOne(guild, async(err, data) => {
if(data) {
if(data.Words.includes(word)) return interaction.followUp(`The word already exists in the blacklist did you mean to remove it if so please use /blacklist-remove ${word} to remove the word from blacklist`)
data.Words.push(word)
data.save();
blacklistedWords.get(interaction.guild.id).push(word);
}else {
new Schema({
Guild: interaction.guild.id,
Words: word
}).save();
blacklistedWords.set(interaction.guild.id, [ word ])
}
const embed = new EmbedBuilder()
.setTitle('<:donetick:951395881607893062> Blacklist system')
.setColor('GREEN')
.setDescription('Word added- A new word has been added to the blacklist')
.addField('Word', `${word}`, false)
.addField('How do I remove the word from the blacklist?', `/blacklist-remove ${word}`, false)
interaction.reply({ embeds: [embed] })
});
},
};
this is the code but it used to work with djs v13 idk now why is it giving this error
the error image in console
can you please help I am new to djs v14 so I think that is an error caused by upgrading to v14 correct me if wrong

How should i make Embed edit reply buttons in discord.js v13 i have to make forword home and backword buttons with embed reply

How should I add buttons who can edit embed reply like: β¬…οΈπŸ βž‘οΈ when I press ➑️ then it update the embed and shows me the next page like that and when I press 🏠 button it shoud let me on home page
const { Client, CommandInteraction, MessageEmbed, MessageActionRow, MessageButton, MessageAttachment, MessageCollector, MessageSelectMenu } = require('discord.js');
const ee = require("../../config/embed.json")
const em = require("../../config/emojis.json")
module.exports = {
name: 'help',
description:'shows help commands',
userperm: [],
botperm: [],
ownerOnly: false,
/**
#param {Client} client
#param {CommandInteraction} interaction
#param {String[]} args
*/
run: async (client, interaction, args) => {
const serverinvite = `https://discord.gg/euf5mqAMmM`;
const inviteUrl = `https://discord.com/api/oauth2/authorize?client_id=${client.user.id}&permissions=8&scope=bot%20applications.commands`;
const embed = new MessageEmbed()
.setTitle('Suggetions Commands')
.setDescription(`This bot is totally in slash so try the commands in slash only`)
.setColor('RANDOM')
.setTimestamp()
.addFields(
{ name: 'Suggetion Commands', value: '`suggetion set` , `suggest` , `suggetion reset`' },
{ name: 'Utilities Commands', value: '`/poll`' },
{ name: 'Info Commands', value: '`help` , `invite` , `vote` , `ping`', inline: true },
)
.setThumbnail(client.user.displayAvatarURL())
.setFooter({ text: client.user.tag , gif: 'https://media.discordapp.net/attachments/1004409670556979232/1004919770220601544/standard_7.gif'})
.setImage('https://media.discordapp.net/attachments/1017764767244505190/1017793760937123971/standard_10.gif')
const actionRow = new MessageActionRow()
.addComponents([
new MessageButton()
.setLabel('Invite')
.setURL(inviteUrl)
.setStyle("LINK")
])
.addComponents([
new MessageButton()
.setLabel('Support server')
.setURL(serverinvite)
.setStyle("LINK")
])
interaction.followUp({ embeds: [embed], components: [actionRow] })
}
}

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

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}!`);
});
})
}
}

How to send Server Region in Embed Discord JS v13?

I have a Server Info command which worked in v12 but I updated to v13. In v12 when I send the Command it Responds with the correct region but in v13 when I send the command, responds at server region with undefined, help!
This is server info command:
const Discord = require('discord.js');
module.exports = {
name: "serverinfo",
aliases: ["si"],
description: "Shows all Info about the Server!",
execute: async (message, args, client) => {
let region;
switch (message.guild.region) {
case "europe":
region = 'πŸ‡ͺπŸ‡Ί europe';
break;
case "russia":
region = 'πŸ‡·πŸ‡Ί russia';
break;
case "us-east":
region = 'πŸ‡ΊπŸ‡Έ us-east'
break;
case "us-west":
region = 'πŸ‡ΊπŸ‡Έ us-west';
break;
case "us-south":
region = 'πŸ‡ΊπŸ‡Έ us-south'
break;
case "us-central":
region = 'πŸ‡ΊπŸ‡Έ us-central'
break;
}
const embed = new Discord.MessageEmbed()
.setThumbnail(message.guild.iconURL({dynamic : true}))
.setColor('#dd6fb9')
.setTitle(`**Bot Command**`)
.setFooter("#" + message.author.tag, message.author.displayAvatarURL({dynamic : true}))
.addFields(
{
name: `Region: `,
value: `${region}`,
inline: true
}
await message.channel.send( { embeds: [embed] }).then(setTimeout(() => message.delete())).then(msg =>{
setTimeout(() => msg.delete(), 120000)});
},
};
A guild no longer has the attribute region. You can however get the preferredLocale of the server:
const Discord = require('discord.js');
module.exports = {
name: "serverinfo",
aliases: ["si"],
description: "Shows all Info about the Server!",
execute: async (message, args, client) => {
const embed = new Discord.MessageEmbed()
.setThumbnail(message.guild.iconURL({dynamic : true}))
.setColor('#dd6fb9')
.setTitle(`**Bot Command**`)
.setFooter("#" + message.author.tag, message.author.displayAvatarURL({dynamic : true}))
.addFields(
{
name: `Region: `,
value: `${message.guild.preferredLocale}`,
inline: true
}
await message.channel.send( { embeds: [embed] }).then(setTimeout(() => message.delete())).then(msg =>{
setTimeout(() => msg.delete(), 120000)});
},
};

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