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],
});
}
});
Related
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] });
}
});
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?
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)
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);
I'm trying to make a draft bot that takes the player amount from an interaction in my draftSize.js file and uses that value in my join.js file as a maximum value for my MessageComponentCollector.
Here is draftSize.js
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageActionRow, MessageButton } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('size')
.setDescription('Sets the size of total players in your draft.')
.addIntegerOption(option =>
option.setName('players')
.setDescription('Amount of players participating in the draft.')
.setRequired(true)),
async execute(interaction) {
let playerSize = interaction.options.getInteger('players');
await interaction.reply({ content: `You\'ve selected a ${playerSize} player draft. \n Next, type: ` + "```" + '/captains {#FirstCaptain} {#SecondCaptain}' + "```"});
console.log("test " + playerSize)
},
};
And here is join.js:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageActionRow, MessageButton, Message } = require('discord.js');
const { playerSize } = require('./draftSize');
module.exports = {
data: new SlashCommandBuilder()
.setName('join')
.setDescription('Allow players to join your draft.'),
async execute(interaction, channel) {
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('joinButton')
.setLabel('Join')
.setStyle('SUCCESS'),
);
await interaction.reply({ content: `To join the draft, click the button below. Once the specified player amount has joined, the draft will begin!`, components: [row] });
const filter = i => {
return i.customId === 'joinButton'
};
const playerList = []
const collectChannel = interaction.channel;
const collector = collectChannel.createMessageComponentCollector({
filter,
max: playerSize,
time: 1000 * 30
})
collector.on('collect', (i = MessageComponentInteraction) => {
i.reply({
content: 'you clicked a button',
ephemeral: true
})
console.log(playerSize)
})
collector.on('end', (collection) => {
collection.forEach((click) => {
playerList.push(click.user.username)
})
collectChannel.send({ content: 'testing'})
console.log(playerList);
})
},
};
In my draftSize.js I get my playerSize value, but whenever I try to import the value into my join.js file to use as my collectors max value it always returns undefined.
Sorry if any of this was unclear. Let me know if you need any clarification.
Thanks!