MessageEmbed field values must be non-empty strings gamedig problem - javascript

Hello i have a problem and its
its if (typeof data !== 'string') throw new error(errorMessage); RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values must be non-empty strings.
i trying on players to put the amount of players that the minecraft server has like:
Players Online: 79 Players
my code its:
let state = null;
let jugadores = 0;
setInterval(() => {
Gamedig.query({
type: 'minecraft',
host: 'mc.latinplay.net',
port: '25565'
})
.then((updatedState) => {
state = updatedState;
players = state.players.length;
});
}, 6000);
module.exports = new Command({
name: cmdconfig.EstadoCommand,
description: cmdconfig.EstadoCommandDesc,
async run(interaction) {
const LatinStatus = new Discord.MessageEmbed()
.setColor('RANDOM')
.addField('**Players:**', 'players')
.addField('**Status**', "**Online💚**", true);
interaction.reply({
embeds: [LatinEstado],
});
}
},
);

Modify your code from your recent:
let state = null;
let jugadores = 0;
setInterval(() => {
Gamedig.query({
type: 'minecraft',
host: 'mc.latinplay.net',
port: '25565'
})
.then((updatedState) => {
state = updatedState;
players = state.players.length || "0"; //adding || operator so no error will occure
});
}, 6000);
module.exports = new Command({
name: cmdconfig.EstadoCommand,
description: cmdconfig.EstadoCommandDesc,
async run(interaction) {
const LatinStatus = new Discord.MessageEmbed()
.setColor('RANDOM')
.addField('**Players:**', 'players')
.addField('**Status**', "**Online💚**", true);
interaction.reply({
embeds: [LatinEstado],
});
}
},
);
Ive seen alot of errors in here, you can also use an operator called or in operator || to prevent error when players reached on 0 members.
module.exports = new Command({
name: cmdconfig.EstadoCommand,
description: cmdconfig.EstadoCommandDesc,
async run(interaction) {
let state = null;
let jugadores = 0; //I also don't understand what is these for.
setInterval(() => {
Gamedig.query({
type: 'minecraft',
host: 'mc.latinplay.net',
port: '25565'
})
.then((updatedState) => {
state = updatedState;
players = state.players.length;
const LatinStatus = new Discord.MessageEmbed()
.setColor('RANDOM')
.addField('**Players:**', `${players}`) //also it must be `${players}`
.addField('**Status**', "**Online💚**", true);
interaction.reply({
embeds: [LatinEstado],
});
});
}, 6000);
}
},
);
EDIT:
I tried your code and caught an error such as Error: Failed all 1 attempts
so you can use .catch function
setInterval(() => {
Gamedig.query({
type: 'minecraft',
host: 'mc.latinplay.net',
port: '25565'
}).catch((err) => {
console.log() //or
console.log(err)
})
.then((updatedState) => {
state = updatedState;
players = state.players.length;
const LatinStatus = new Discord.MessageEmbed()
.setColor('RANDOM')
.addField('**Players:**', `${players || "0"}`) //also it must be `${players}`
.addField('**Status**', "**Online💚**", true);
interaction.reply({
embeds: [LatinEstado],
});
});
}, 6000);

Related

Banned and kicked logs

I made a ban and kick script and it's working, but when a user gets a ban, the bot sends a ban and a kick message (even if the user gets a ban). I want it to send only the ban message when the user receives the ban, and the kick message only when the user receives a kick.
client.on(Events.GuildBanRemove, async (ban) => {
const fetchedLogs = await ban.guild.fetchAuditLogs({
limit: 1,
type: AuditLogEvent.MemberBanRemove,
});
const unbanLog = fetchedLogs.entries.first();
const { executor, target } = unbanLog;
if (target.id === ban.user.id) {
const channel2 = client.channels.cache.get("1026979529387950132");
const embed2 = new Discord.EmbedBuilder()
.setColor("#10fee4")
.setThumbnail(`${client.user.displayAvatarURL({ size: 2048 })}`)
.setTitle(`Log | Usuario Desbanido.`)
.setDescription(`**Informações do usuario:**\n > Membro:${ban.user}\n > ID:\`${ban.user.id}\`\n\n**Informações do unban**:\n > Desbanido por: ${executor}\n> ID:\`${executor.id}\``)
.setFooter({ text: `© ${client.user.username} 2023` })
.setTimestamp(new Date());
channel2.send({ embeds: [embed2] });
}
});
client.on(Events.GuildMemberRemove, async (member) => {
const fetchedLogs2 = await member.guild.fetchAuditLogs({
limit: 1,
type: AuditLogEvent.MemberKick,
});
const kickLog = fetchedLogs2.entries.first();
const { executor, target } = kickLog;
if (target.id === member.id) {
const channel3 = client.channels.cache.get("1026979529387950132");
const embed3 = new Discord.EmbedBuilder()
.setColor("#10fee4")
.setThumbnail(`${client.user.displayAvatarURL({ size: 2048 })}`)
.setTitle(`Log | Usuario Expulso.`)
.setDescription(`**Informações do usuario:**\n > Membro:${member.user}\n > ID:\`${member.user.id}\`\n\n**Informações da expulsão:**\n > Expulso por: ${executor}\n> ID:\`${executor.id}\``)
.setFooter({ text: `© ${client.user.username} 2023` })
.setTimestamp(new Date());
channel3.send({ embeds: [embed3] });
}
});

Discord.js: TypeError: Cannot read properties of undefined (reading 'hello')

I am creating a Discord command handler using discord.js version 14.4.0 but I keep getting this error, here is my code:
const settings = require(`${process.cwd()}/config/settings.json`);
const ee = require(`${process.cwd()}/config/embed.json`);
const colors = require("colors");
const Discord = require("discord.js");
module.exports = {
name: "hello",
description: "say hello!",
cooldown: settings.cooldown,
memberpermissions: [],
requiredroles: [],
alloweduserids: [],
type: Discord.ApplicationCommandType.ChatInput,
options: [],
run: async (client, interaction) => {
try {
interaction.reply({ content: `${client.word.hello}` });
} catch (error) {
console.log(colors.red(error));
let somethingWrong = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| Something wrong!")
.setDescription(`❌| Sorry, I failed setting up...!`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [somethingWrong], ephemeral: true });
}
}
};
The error I get when running that command:
interaction.reply({ content: `${client.word.hello}` });
and this my index.js file:
const lang_db = require("./dataBases/db");
const dotenv = require("dotenv"); dotenv.config();
const colors = require("colors");
const fs = require("fs");
const Discord = require("discord.js");
const client = new Discord.Client({
intents: [32767],
partials: [
Discord.Partials.GuildScheduledEvent,
Discord.Partials.ThreadMember,
Discord.Partials.GuildMember,
Discord.Partials.Reaction,
Discord.Partials.Channel,
Discord.Partials.Message,
Discord.Partials.User,
],
});
client.slashCommands = new Discord.Collection();
module.exports = client;
fs.readdirSync("./handlers").forEach((handler) => {
require(`./handlers/${handler}`)(client);
});
client.on("interactionCreate", async (interaction) => {
let lang = await lang_db.get(`language_${interaction.guild.id}`);
if(lang == null) {
lang = "en";
} else if(lang == "ar") {
lang = "ar"
}
let word = require(`./languages/${lang}.json`);
client.word = word;
});
client.login(process.env.TOKEN).catch((error) => {
console.log(colors.red(error));
});
TypeError: Cannot read properties of undefined (reading 'hello')
handlers/slashCommand.js
const colors = require("colors");
const fs = require("fs");
const AsciiTable = require("ascii-table");
const table = new AsciiTable().setHeading("Slash Commands", "Stats").setBorder("|", "=", "0", "0");
const { Routes } = require("discord-api-types/v9");
const { REST } = require("#discordjs/rest");
const Discord = require("discord.js");
const APPLICATION_ID = process.env.APPLICATION_ID;
const TOKEN = process.env.TOKEN;
const rest = new REST({ version: "10" }).setToken(TOKEN);
module.exports = (client) => {
const slashCommands = [];
fs.readdirSync("./slashCommands/").forEach(async (dir) => {
const files = fs.readdirSync(`./slashCommands/${dir}/`).filter((file) => file.endsWith(".js"));
for (const file of files) {
const slashCommand = require(`../slashCommands/${dir}/${file}`);
slashCommands.push({
name: slashCommand.name,
description: slashCommand.description,
type: slashCommand.type,
options: slashCommand.options ? slashCommand.options : null,
default_permission: slashCommand.default_permission ? slashCommand.default_permission : null,
default_member_permissions: slashCommand.default_member_permissions ? Discord.PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null,
});
if (slashCommand.name) {
client.slashCommands.set(slashCommand.name, slashCommand);
table.addRow(file.split(".js")[0], "✅");
} else {
table.addRow(file.split(".js")[0], "⛔");
}
}
});
console.log(colors.green(table.toString()));
(async () => {
try {
const data = await rest.put(process.env.GUILD_ID ? Routes.applicationGuildCommands(APPLICATION_ID, process.env.GUILD_ID) : Routes.applicationCommands(APPLICATION_ID), { body: slashCommands });
console.log(colors.green(`Started refreshing ${slashCommands.length} application (/) commands.`));
console.log(colors.green(`Successfully reloaded ${data.length} application (/) commands.`));
} catch (error) {
console.log(colors.red(error));
}
})();
};
events/guid/interactionCreate.js
const ee = require(`${process.cwd()}/config/embed.json`);
const colors = require("colors");
const ms = require("ms");
const Discord = require("discord.js");
const client = require("../..");
const delay = new Discord.Collection();
client.on("interactionCreate", async (interaction) => {
const slashCommand = client.slashCommands.get(interaction.commandName);
if (interaction.type == 4) {
if (slashCommand.autocomplete) {
const choices = [];
await slashCommand.autocomplete(interaction, choices);
}
}
if (!interaction.type == 2) return;
if (!slashCommand)
return client.slashCommands.delete(interaction.commandName);
try {
if (slashCommand.cooldown) {
if (delay.has(`${slashCommand.name}-${interaction.user.id}`)) {
let time = ms(delay.get(`${slashCommand.name}-${interaction.user.id}`) - Date.now(), { long: true }).includes("ms") ? "0 second" : ms(delay.get(`${slashCommand.name}-${interaction.user.id}`) - Date.now(), { long: true });
let timeLeft = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| Please wait **${time}** before reusing the \`${slashCommand.name}\` command!`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [timeLeft], ephemeral: true });
}
}
if (slashCommand.memberpermissions && slashCommand.memberpermissions.length > 0 && !interaction.member.permissions.has(slashCommand.memberpermissions)) {
let memberPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need these Permission(s): \`${slashCommand.memberpermissions}\``)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [memberPerms], ephemeral: true });
}
if (slashCommand.requiredroles && slashCommand.requiredroles.length > 0 && interaction.member.roles.cache.size > 0 && !interaction.member.roles.cache.some(r => slashCommand.requiredroles.includes(r.id))) {
let rolesPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need to have one of the Following Roles: <#&${slashCommand.requiredroles}>`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [rolesPerms], ephemeral: true });
}
if (slashCommand.alloweduserids && slashCommand.alloweduserids.length > 0 && !slashCommand.alloweduserids.includes(interaction.member.id)) {
let userPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need to be one of the Following Users: <#!${slashCommand.alloweduserids}>`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [userPerms], ephemeral: true });
}
await slashCommand.run(client, interaction);
delay.set(`${slashCommand.name}-${interaction.user.id}`, Date.now() + slashCommand.cooldown * 1000);
setTimeout(() => {
delay.delete(`${slashCommand.name}-${interaction.user.id}`);
}, slashCommand.cooldown * 1000);
} catch (error) {
console.log(colors.red(error));
}
});
I don't know why this is happening, please could someone help me?

Discord Embed Command Cooldown

im trying to create a cooldown for my status command, because they spam a lot on the server the status command and i want a cooldown like 5m and that send a message like, "you need to wait 5m more to use this command im really newbie to javascript, so if anyone can help me
Here its my entire command:
const Discord = require("discord.js");
const yaml = require("js-yaml");
const supportbot = yaml.load(
fs.readFileSync("./Configs/supportbot.yml", "utf8")
);
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const Command = require("../Structures/Command.js");
const { timeStamp } = require("console");
var request = require('request');
const Gamedig = require('gamedig');
let state = null;
setInterval(() => {
Gamedig.query({
type: 'minecraft',
host: 'mc.latinplay.net',
port: '25565'
})
.then((updatedState) => {
state = updatedState;
players = state.players.length;
}).catch((error) => {
console.log("Server is offline");
});
}, 6000);
module.exports = new Command({
name: cmdconfig.EstadoCommand,
description: cmdconfig.EstadoCommandDesc,
async run(interaction) {
const LatinEstado = new Discord.MessageEmbed()
.setColor('RANDOM')
.setTitle('𝐋𝐚𝐭𝐢𝐧𝐏𝐥𝐚𝐲 𝐍𝐞𝐭𝐰𝐨𝐫𝐤 **Estado del Servidor**')
.setURL("https://store.latinplay.net/")
.addField('**Jugadores en linea:**', `${players || "0"}`)
.addField('**Estado Actual:**', "**En Linea💚**", true)
.setThumbnail('https://media0.giphy.com/media/5RQ6coK6GVXGfPPq69/giphy.gif?cid=790b76115867f0dba05d9cf2aceb80efed5b0e494387e3b2&rid=giphy.gif&ct=g')
.setFooter({ text: 'LatinBot | Version 1.0 ', iconURL: 'https://cdn.discordapp.com/attachments/953043417234026547/988805760458821642/Diseno_sin_titulo.png' });
interaction.reply({
embeds: [LatinEstado],
});
}
},
);```
Just store last command run time in a map.
const cooldown={}; // Add this
...
module.exports = new Command({
name: cmdconfig.EstadoCommand,
description: cmdconfig.EstadoCommandDesc,
async run(interaction) {
//
if (interaction.user.id in cooldown && cooldown[interaction.user.id] - Date.now() > 0) // in cool down
return interaction.reply("In cooldown! Please wait 5 min!");
cooldown[interaction.user.id] = Date.now() + 300000; // 5 min in ms.
//
const LatinEstado = new Discord.MessageEmbed()
.setColor('RANDOM')
.setTitle('𝐋𝐚𝐭𝐢𝐧𝐏𝐥𝐚𝐲 𝐍𝐞𝐭𝐰𝐨𝐫𝐤 **Estado del Servidor**')
.setURL("https://store.latinplay.net/")
.addField('**Jugadores en linea:**', `${players || "0"}`)
.addField('**Estado Actual:**', "**En Linea💚**", true)
.setThumbnail('https://media0.giphy.com/media/5RQ6coK6GVXGfPPq69/giphy.gif?cid=790b76115867f0dba05d9cf2aceb80efed5b0e494387e3b2&rid=giphy.gif&ct=g')
.setFooter({
text: 'LatinBot | Version 1.0 ',
iconURL: 'https://cdn.discordapp.com/attachments/953043417234026547/988805760458821642/Diseno_sin_titulo.png'
});
interaction.reply({
embeds: [LatinEstado],
});
}
});

Discord.js V13 player.getQueue() returns undefined even tho a queue exists

I'm creating a discord bot with queue system. A queue is created in play.js file. The queue is then fetched in skip.js using player.getQueue() method to be able to skip songs. However, it returns undefined meaning no queue was found.
I know for a fact a queue exist because I logged it in the console but somehow this methode can't find it.
play.js Code :
const { SlashCommandBuilder } = require('#discordjs/builders');
const { Player, QueryType } = require('discord-player');
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('plays music')
.addStringOption(option => option
.setName("song")
.setDescription("what to play")
.setRequired(true)),
async execute(interaction, Discord) {
const voice_channel = interaction.member.voice.channel;
const bot_channel = interaction.guild.me.voice.channel;
if (!voice_channel) {
await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setDescription('You need to be in a voice channel to play music!')],
ephemeral: true
});
}
if (bot_channel && bot_channel.id != voice_channel.id) {
await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setDescription(`I'm already connected on ${bot_channel.toString()}`)],
ephemeral: true
});
}
const song = interaction.options.getString("song");
const player = new Player(interaction.client);
const searchResult = await player.search(song, {
requestedBy: interaction.user,
searchEngine: QueryType.AUTO
}).catch(() => { });
if (!searchResult || !searchResult.tracks.length) {
return interaction.reply({ content: 'No music found!', ephemeral: true });
}
const queue = player.createQueue(interaction.guild);
queue.options.initialVolume = 50;
queue.options.leaveOnEmptyCooldown = 5000;
try {
if (!queue.connection) await queue.connect(voice_channel);
} catch {
void player.deleteQueue(interaction.guildId);
return void interaction.reply({ content: "Could not join your voice channel!", ephemeral: true });
}
searchResult.playlist ? queue.addTracks(searchResult.tracks) : queue.addTrack(searchResult.tracks[0]);
if (!queue.playing) {
await queue.play().then(queue.playing = true);
// console.log(queue);
}
const row = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageButton()
.setCustomId('pause')
.setLabel('⏸')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('resume')
.setLabel('▶')
.setStyle('PRIMARY'),
);
const play_embed = await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setTitle(`${queue.nowPlaying().title}`)
.setURL(`${queue.nowPlaying().url}`)
.setThumbnail(`${queue.nowPlaying().thumbnail}`)
.setAuthor({ name: ` | Now Playing`, iconURL: `https://imgur.com/krzRxsN.png` })
.addField('Duration :', `\`${queue.nowPlaying().duration}\``, true)
.addField('Author :', `\`${queue.nowPlaying().author}\``, true)
.setTimestamp()
.setFooter({ text: `Requested By ${interaction.user.username}`, iconURL: `${interaction.user.displayAvatarURL()}` })
],
// components: [row]
});
}
}
skip.js Code :
const { SlashCommandBuilder } = require('#discordjs/builders');
const { Player, QueryType } = require('discord-player');
module.exports = {
data: new SlashCommandBuilder()
.setName('skip')
.setDescription('skips to the next music in queue'),
async execute(interaction, Discord) {
await interaction.deferReply();
const player = new Player(interaction.client);
console.log(player.queues);
const queue = player.getQueue(interaction.guildId);
// console.log(queue);
if (!queue || !queue.playing) return void interaction.followUp({ content: "❌ | No music is being played!" });
const currentTrack = queue.current;
const success = queue.skip();
return void interaction.followUp({
content: success ? `✅ | Skipped **${currentTrack}**!` : "❌ | Something went wrong!"
});
}
}
In index.js ,
client.player = new Player(client);
In execute function, pass client as an argument.
execute({interaction, client})
In skip.js, While getting the queue, Try this--
const queue = await client.player.getQueue(interaction.guildId)

Export variable to other files discordjs

I changed my command handler and am no longer exporting anything from profileData (used to be command handler file). The file is checking for their profile and holding the data in profileData, or if they don't have on then create one for them. I want to export the profileData to be used in other files instead of querying in every single command. How can I achieve this. I have tried putting module.exports and exports.profileData = profileData all over the place and nothing works im just lost on how to do this. Any help would be appreciated.
profileData-
const profileModel = require("../../models/profileSchema");
module.exports = (client) => {
client.on("message", async (message) => {
const prefix = 's!'
if (!message.content.startsWith(prefix) || message.author.bot) return;
try {
const profileData = await profileModel.findOne({ userID: message.author.id });
if (!profileData) {
let profile = await profileModel.create({
userID: message.author.id,
serverID: message.guild.id,
coins: 10,
bank: 0,
});
profile.save();
}
} catch (err) {
console.log(err);
}
})
}
module.exports.config = {
displayName: 'Profile Data',
dbName: 'PROFILEDATA',
loadDBFirst: true
}
balance-
const { MessageEmbed } = require("discord.js");
const { profileData } = require("../../Features/client/profileData");
module.exports = {
name: "balance",
aliases: ["bal"],
category: "Economy",
cooldown: "20s",
permissions: ["ADMINISTRATOR"],
maxArgs: 0,
description: "Check your wallet and bank balance!",
execute: async ({ message, client }) => {
let balPlaceholder = "'s balance";
const BalEmbed = new MessageEmbed()
.setColor("#0bbffc")
.setAuthor("Saoul 2")
.setTitle(`${message.author.username}${balPlaceholder}`)
.addFields(
{ name: "💸 Wallet:", value: `${profileData.coins}`, inline: true },
{ name: "🏦 Bank:", value: `${profileData.bank}`, inline: true }
)
.setTimestamp()
.setFooter(
`Command Requested By ${message.author.tag}`,
client.user.displayAvatarURL()
);
message.channel.send(BalEmbed);
},
};
If I understand you correctly: you want to export the profileData, and if none can be found, create a new profile and use that. The following snippet might solve your problem.
const profileModel = require("../../models/profileSchema");
let data = getData(client);
exports.data = data;
async function getData(client) {
client.on("message", async(message) => {
const prefix = 's!'
if (!message.content.startsWith(prefix) || message.author.bot) return;
try {
const profileData = await profileModel.findOne({
userID: message.author.id
});
if (!profileData) {
let profile = await profileModel.create({
userID: message.author.id,
serverID: message.guild.id,
coins: 10,
bank: 0,
});
profile.save();
return profile;
} else {
return profileData;
}
} catch (err) {
console.log(err);
}
})
}
module.exports.config = {
displayName: 'Profile Data',
dbName: 'PROFILEDATA',
loadDBFirst: true
}
This is all I needed to get the function to run when a message is sent through the command handler.
module.exports = {
getData: async (message) => {
try {

Categories