Message embed field values must be non-empty strings - discord.js

https://pastebin.com/FWYFSdfD
const Discord = require('discord.js')
module.exports = {
name: 'warn',
description: 'warn a member',
async execute(message, args){
edited = message.content.slice(5);
const guildID = message.guild.Discord
const UserId = message.member.Discord
const Reason = args.splice(1).join('')
let User = message.mentions.users.first()
if(message.member.permissions.has('KICK_MEMBERS')){
try{
member = await message.guild.members.find(message.mentions.users.first())
}catch(err){
const warnEmbed = new Discord.MessageEmbed()
.setTitle("**Warn**")
.setColor("#FF0000")
.addField('text', 'value')
.addField("User:", User, true)
.addField("Reason:", Reason, true)
.setThumbnail("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRGagFW_bh2AfgI1BqAis81CXVg37j8_MKtwg&usqp=CAU")
.setTimestamp()
}
try{
User.send(warnEmbed)
message.channel.send(warnEmbed)
}
catch(err){
return(message.reply('You must format the command <#mention> <reason>'))
}
}
else{
message.channel.send('only staff can use this command')
}
}
}
This is the warn code. But when I try to use it, I get an error saying MessageEmbed field values must be non-empty strings. And how many words do I need to write to send this.

Related

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

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

Discord.js v12 How to get total number on reactions from fetched embed

So i've been trying to count the reactions statistic after it was accepted or rejected, i'd try to find a solution but i can't here's my code
module.exports = {
name: 'accept-suggestion',
cooldown: 3,
description: 'Accept a sugegstion',
permissions: 'MANAGE_ROLES',
usage: '[suggestion id] [reason]',
async run(client, message, args, cmd, Discord){
message.delete()
const messageID = args[0];
const acceptMsg = args.slice(1).join(" ");
if(!messageID) return message.reply('Please specify a suggestion Id!').then(msg => {
msg.delete({ timeout: 3000 })
})
if(!acceptMsg) return message.reply('Please specify a reason!').then(msg => {
msg.delete({ timeout: 3000})
})
try {
const suggestionChannel = message.guild.channels.cache.get(
'SuggestionChannel_ID'
);
const moderator = message.author.tag
const suggestedEmbed = await suggestionChannel.messages.fetch(messageID);
console.log(suggestedEmbed)
const data = suggestedEmbed.embeds[0];
const dataStats = suggestedEmbed[0];
let upVote = dataStats.reactions.cache.get('✅').count;
let downVote = dataStats.reactions.cache.get('❌').count;
const acceptEmbed = new Discord.MessageEmbed()
.setTitle("Suggestion (Accepted)")
.setColor('#1dc44a')
.setAuthor(data.author.name, data.author.iconURL)
.setDescription(data.description)
.addFields(
{name: `Accepted by ${moderator}`, value: ` > ${acceptMsg}`},
{name: 'Statistic', value: `${upVote}\n${downVote}`}
)
.setFooter(`${data.author.name}'s suggestion`, data.author.iconURL)
suggestedEmbed.edit(acceptEmbed).then(msg => msg.reactions.removeAll())
const user = await client.users.cache.find(
(u) => u.tag === data.author.name
);
user.send("Your suggestion has been accepted!")
} catch(err) {
console.log(err)
}
}
}
you maybe wondering why i put .reactions after dataStats, i put it because i thought it would work by seeing the output off the suggestedEmbed(the output: https://pastebin.com/yEhDecur) i hope someone could fix this :)
Running the fetch() method with a id parameter only returns a single Message so accessing it like a array/collection won't work
const dataStats = suggestedEmbed[0];
this needs to change to
const dataStats = suggestedEmbed;
https://discord.js.org/#/docs/discord.js/stable/class/MessageManager?scrollTo=fetch

How to check if a user is in a guild

Guys I am currently working on a quick.db leaderboard command but it returns the global leaderboard but I want it to return only the Names Of The User Which are in the message.guild.
My current lb code is this
const Discord = require('discord.js')
const db = require('quick.db')
module.exports.run = async (bot, message, args) => {
const ic = '<:mon:834428547064922142>'
let money = db.fetchAll(message.guild.id).filter(data => data.ID.startsWith(`mon_`)).sort((a, b) => (b.data-a.data))
money.length = 25;
var finalLb = "";
for (var i in money) {
finalLb += `**${money.indexOf(money[i])+1}. ${(await bot.users.fetch(money[i].ID.split('_')[1])).username ? (await bot.users.fetch(money[i].ID.split('_')[1])).username : "Unknown User#0000"}** : ${ic} ${parseInt(JSON.stringify(money[i].data))}\n`;
}
const embed = new Discord.MessageEmbed()
.setAuthor(`Leaderboard`, message.guild.iconURL())
.setColor("RANDOM")
.setDescription(finalLb)
.setFooter(bot.user.tag, bot.user.displayAvatarURL())
.setTimestamp()
message.channel.send(embed);
}
module.exports.help = {
name:"rich",
aliases: [""]
}
Try adding this in your code
if(guild.members.cache.has("The UserID")){
//Add the user in leaderboard
//finalLb += `**${money. .........your code
}
const member = message.guild.members.cache.get('user id');
if(!member){
// what to do if member is not provided
}
}

user.ban is Not a function?

I was trying to make a ban command where you can ban a user with a reason.
Turns out user.ban is not a function in Discord.js V12 even though it should be.
Here is my code.
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'ban',
description: 'Bans a user.',
category: 'Moderation',
usage: '^ban <user> <reason>',
run: async (bot, message, args) => {
if (!message.member.hasPermission('BAN_MEMBERS')) {
return message.channel.send('You do not have permission to do this! ❌');
}
if (!message.guild.me.hasPermission('BAN_MEMBERS')) {
return message.channel.send('I do not have permission to do this! ❌');
}
const user = message.mentions.users.first();
if (!user) {
return message.channel.send('User was not specified. ❌');
}
if (user.id === message.author.id) {
return message.channel.send('You cannot ban yourself! ❌');
}
let reason = message.content
.split(' ')
.slice(2)
.join(' ');
if (!reason) {
reason = 'No reason provided.';
}
let Embed = new MessageEmbed()
.setTitle(`Justice! | Ban Action`)
.setDescription(`Banned \`${user}\` - Tag: \`${user.discriminator}\``)
.setColor('ORANGE')
.setThumbnail(user.avatarURL)
.addField('Banned by', `\`${message.author.username}\``)
.addField(`Reason?`, `\`${reason}\``)
.setTimestamp();
message.channel.send(Embed);
user.ban(reason);
},
};
Is there a way to fix this?
You're getting a User instead of a GuildMember. A User represents a person on discord, while a GuildMember represents a member of a server. You can get a GuildMember instead of a User by using mentions.members instead of mentions.users ex:
const user = message.mentions.members.first()

Resources