Error [ERR_REQUIRE_ESM]: require() of ES Module - javascript

v13, the terminal shows this error:
Error:const ms = require('parse-ms') // npm i parse-ms
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\DELL\OneDrive\Desktop\Discord Bot\node_modules\parse-ms\index.js from C:\Users\DELL\OneDrive\Desktop\Discord Bot\commands\Economy\beg.js not supported.
code:
const db = require('quick.db') // npm i quick.db
const ms = require('parse-ms') // npm i parse-ms
module.exports = {
commands: ['beg'], // You Can Keep Any Name
description: 'Beg For Money', // Optional
callback: (message, args) => {
const user = message.member
const random = (min, max) => {
return Math.floor(Math.random() * (max - min) ) + min
}
const timeout = 60000 // 1 Min In MiliSecond
const amount = Math.floor(Math.random() * 900) + 100 // Min Is 100 And Max Is 1000(100+900)
let names = [ // Find More Names In Description
'Sir Cole Jerkin',
'Kim Kardashian',
'Logan Paul',
'Mr.Clean',
'Ryan Gosling',
'Ariana Grande',
'Default Jonesy',
'Cardi B',
'Dwight Shrute',
'Jesus',
'Taylor Swift',
'Beyoncé',
'Bill Clinton',
'Bob Ross',
'The Rock:',
'The Rock',
'Mike Hoochie',
'Doot Skelly',
'Ayylien',
'Spoopy Skelo'
]
const name = Math.floor(Math.random() * names.length) // To Get Random Name
let options = [
'Success',
'Failed'
]
let begged = random(0, parseInt(options.length))
let final = options[begged]
const begtime = db.fetch(`beg-time_${user.id}`) // Keep `beg-time_${message.guild.id}_${user.id}` If You Want Different In All Servers
if(begtime !== null && timeout - (Date.now() - begtime) > 0) {
const timeleft = ms(timeout - (Date.now() - begtime))
const embed = new MessageEmbed()
.setAuthor(`${user.user.username} Begged`, user.user.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor('RANDOM')
.setDescription(`
Already Begged, Beg Again In **${timeleft.seconds} Seconds**
Default CoolDown Is **1 Minutes**
`)
message.channel.send({embeds: [embed]})
} else {
if(final === 'Success') {
let gave = [
'Donated',
'Gave'
]
const give = Math.floor(Math.random() * gave.length)
db.add(`money_${user.id}`, amount)
const embed1 = new MessageEmbed()
.setAuthor(`${user.user.username} Begged`, user.user.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor('RANDOM')
.setDescription(`
**${names[name]}**: ${gave[give]} **$${amount}** To <#${user.user.id}>
`)
message.channel.send({embeds: [embed1]})
db.set(`beg-time_${user.id}`, Date.now())
} else if(final === 'Failed') {
let notgave = [
`I Don't Have Money`,
`I Am Also Poor`,
`I Already Gave Money To Last Beggar`,
`Stop Begging`,
`Go Away`
]
const notgive = Math.floor(Math.random() * notgave.length)
const embed2 = new MessageEmbed()
.setAuthor(`${user.user.username} Begged`, user.user.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor('RANDOM')
.setDescription(`
**${names[name]}**: ${notgave[notgive]}
`)
message.channel.send({embeds: [embed2]})
db.set(`beg-time_${user.id}`, Date.now())
}
}
}
}```

V3.0 of this package only supports the use of ES modules now which use a different syntax for importing.
You can either switch your current codebase to use ESM or another option is to downgrade the current version of parse-ms to V2.1
Refer to this:
https://github.com/sindresorhus/parse-ms/releases/tag/v3.0.0

Related

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],
});
}
});

bot send msg when someone speaks

I have another question concerning my catch cmd. If I wanted to make it so that it was no longer an activable command but instead had a small chance of triggering when anyone speaks ever, how would I go about that? Would I need to put it in my message.js file? I know if I put it there as is it will trigger every time someone uses a command. However, I don't want it limited to someone using a command and I don't want it to happen every time. I've also heard of putting it in a separate json file and linking it back somehow. Any help is appreciated.
const profileModel = require("../models/profileSchema");
module.exports = {
name: "catch",
description: "users must type catch first to catch the animal",
async execute(client, message, msg, args, cmd, Discord, profileData) {
const prey = [
"rabbit",
"rat",
"bird",
];
const caught = [
"catch",
];
const chosenPrey = prey.sort(() => Math.random() - Math.random()).slice(0, 1);
const whenCaught = caught.sort(() => Math.random() - Math.random()).slice(0, 1);
const filter = ({ content }) => whenCaught.some((caught) => caught.toLowerCase() == content.toLowerCase());
const collector = message.channel.createMessageCollector({ max: 1, filter, time: 15000 });
const earnings = Math.floor(Math.random() * (20 - 5 + 1)) + 5;
collector.on('collect', async (m) => {
if(m.content?.toLowerCase() === 'catch') {
const user = m.author;
const userData = await profileModel.findOne({ userID: user.id });
message.channel.send(`${userData.name} caught the ${chosenPrey}! You gained ${earnings} coins.`);
}
await profileModel.findOneAndUpdate(
{
userID: m.author.id,
},
{
$inc: {
coins: earnings,
},
}
);
});
collector.on('end', (collected, reason) => {
if (reason == "time") {
message.channel.send('Too slow');
}
});
message.channel.send(`Look out, a ${chosenPrey}! Type CATCH before it gets away!`);
}
}
message.js file just in case
const profileModel = require("../../models/profileSchema");
const cooldowns = new Map();
module.exports = async (Discord, client, message) => {
let profileData;
try {
profileData = await profileModel.findOne({ userID: message.author.id });
if(!profileData){
let profile = await profileModel.create({
name: message.member.user.tag,
userID: message.author.id,
serverID: message.guild.id,
coins: 0,
});
profile.save();
}
} catch (err) {
console.log(err);
}
const prefix = '-';
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
if(!command) return;
if(!cooldowns.has(command.name)){
cooldowns.set(command.name, new Discord.Collection());
}
const current_time = Date.now();
const time_stamps = cooldowns.get(command.name);
const cooldown_amount = (command.cooldown) * 1000;
if(time_stamps.has(message.author.id)){
const expiration_time = time_stamps.get(message.author.id) + cooldown_amount;
if(current_time < expiration_time){
const time_left = (expiration_time - current_time) / 1000;
return message.reply(`Slow down there! You have to wait ${time_left.toFixed(0)} seconds before you can perform ${command.name} again.`);
}
}
if(command) command.execute(client, message, args, cmd, Discord, profileData);
}
Yes...that can be possible. In your command handler, create and export a variable with a boolean
Make sure to do this in global scope (outside any function)
let canBeActivated = true;
module.exports.getCanBeActivated = function () { return canBeActivated };
module.exports.setCanBeActivated = function(value) { canBeActivated = value };
Then, in your command file, import it and check whether it can be activated
const { getCanBeActivated, setCanBeActivated } = require("path/to/message.js")
module.exports = {
...
execute(...) {
// command wont run
if(!getCanBeActivated()) return
}
You can make some logic to make the command run if canBeActivated is false (like get a random number between 1-100 and if it matches 4 run it).In case you need to change it, just run, setCanBeActivated

discordjs v13 - subtract the variable

The code doesn't work when it subtract the variable (enemy's health)
This is my code
if (message.content === ".battle") {
//hidden code....
let damage = Math.floor(Math.random() * 10)
let user = message.author
let embed = new Discord.MessageEmbed()
.setTitle(`${user.username}'s battle`)
.setColor("GREEN")
.setDescription(`
**${user.username}'s Stats**
Health: ${player_health}
Mana: ${player_mana}
Power: ${power}
Frist Skill: ${a1}
Second Skill: ${a2}
Third Skill: ${a3}
`)
//enemy embed
let ene_health = 100
let ene_xp = 10
let embed1 = new Discord.MessageEmbed()
.setTitle(`${user.username}'s battle`)
.setDescription(`
**Enemy's Stats**
Health: ${ene_health}
Mana: ${ene_mana}
`)
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('primary')
.setLabel(`Use: ${power}`)
.setStyle('PRIMARY'),
);
//hidden code......
await message.reply({ content: "You have 1 minute to choose the skills", embeds: [embed, embed1], components: [row] });
const filter = i => i.customId === 'primary' && i.user.id === `${message.author.id}`;
const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
collector.on('collect', async i => {
if (i.customId === 'primary') {
await i.deferUpdate();
await wait(4000);
await i.editReply({ content: `You've use ${power} power and you deal the ${damage} Dmg.`, components: [] })
//there the problem
damage - ene_health
}
});
collector.on('end', collected => console.log(`Collected ${collected.size} button`));
}
I wonder at the damage - ene_health why it doesn't subtract the enemy's health
I am using discord.js v13 and quickdb
damage - ene_health
isn't doing anything. In your case you have to CHANGE the damage variable.
damage = damage - ene_health
or even better, use the Substract assignment :
damage -= ene_health

Giveaway winner is coming out as undefined

const ms = require('ms');
const { MessageEmbed } = require('discord.js')
module.exports = {
name: 'giveaway',
description: 'start a giveaway',
async execute(client, message, cmd, args, Discord){
let author = message.author.username;
var time;
time = args[0];
let title = args.join(" ").slice(3);
if(!message.member.permissions.has(['ADMINISTRATOR'])){
message.channel.send(`Sorry **${author}** But you don't have enough permissions to use this command!`)
} else {
if(message.member.permissions.has(['ADMINISTRATOR'])){
let giveawayEmbed = new MessageEmbed()
.setColor('BLACK')
.setThumbnail(`${message.author.displayAvatarURL()}`)
.setTitle(`${author}'s Giveaway 🎉`)
.setDescription(`**${title}**`)
.addField(`Duration :`, ms(ms(time), {
long: true
}), true)
.setFooter("React to this message with 🎉 to participate !")
var giveawaySent = await message.channel.send({ embeds: [giveawayEmbed] });
giveawaySent.react('🎉');
console.log(giveawaySent.id)
setTimeout(async function(){
const react = await giveawaySent.reactions.cache.find(r => r.emoji.name === '🎉').users.fetch();
let index = Math.map(Math.random() * react.length);
let winner = react[index];
console.log(react)
console.log(index)
console.log(winner)
let winnerEmbed = new MessageEmbed()
.setColor('GREEN')
.setDescription(`Congratulations **${winner}** you won **${title}**`)
message.reply({ embeds: [winnerEmbed] })
}, ms(time))
}
}
}
}
I'm trying to code a giveaway module however the winner result is coming out as undefined and I can't seem to figure out why, If you guys can help me out be greatly appreciated
These were logged by the console if it helps any
index = NaN
winner = undefined
const ms = require('ms');
const { MessageEmbed } = require('discord.js')
module.exports = {
name: 'giveaway',
description: 'start a giveaway',
async execute(client, message, cmd, args, Discord){
let author = message.author.username;
var time;
time = args[0];
let title = args.join(" ").slice(3);
if(!message.member.permissions.has(['ADMINISTRATOR'])){
message.channel.send(`Sorry **${author}** But you don't have enough permissions to use this command!`)
} else {
if(message.member.permissions.has(['ADMINISTRATOR'])){
let giveawayEmbed = new MessageEmbed()
.setColor('BLACK')
.setThumbnail(`${message.author.displayAvatarURL()}`)
.setTitle(`${author}'s Giveaway 🎉`)
.setDescription(`**${title}**`)
.addField(`Duration :`, ms(ms(time), {
long: true
}), true)
.setFooter("React to this message with 🎉 to participate !")
var giveawaySent = await message.channel.send({ embeds: [giveawayEmbed] });
giveawaySent.react('🎉');
console.log(giveawaySent.id)
setTimeout(async function(){
const react = await giveawaySent.reactions.cache.find(r => r.emoji.name === '🎉').users.fetch();
const reactArray = react.map(c => c)
let index = Math.floor(Math.random() * reactArray.length);
let winner = reactArray[index];
console.log(reactArray)
// console.log(react)
console.log(index)
console.log(winner)
let winnerEmbed = new MessageEmbed()
.setColor('GREEN')
.setDescription(`Congratulations **${winner}** you won **${title}**`)
message.reply({ embeds: [winnerEmbed] })
}, ms(time))
}
}
}
}
Seems to have resolved the issue, Added const reactArray = react.map(c => c)
Changed
let index = Math.floor(Math.random() * react.length); to let index = Math.floor(Math.random() * reactArray.length); which made const react = await giveawaySent.reactions.cache.find(r => r.emoji.name === '🎉').users.fetch(); into an array of user id's

discord.js v12 - Warn command for each guild

I have script for warn command and i need help with that, because this
code working, this command saving warns in warnings.json, but when i warn someone that warn be in every guild i want only in one guild warns. Please help :D
const { MessageEmbed } = require("discord.js")
const fs = require('fs')
const warns = JSON.parse(fs.readFileSync("./warnings.json", "utf8"))
const moment = require('moment')
module.exports = {
name: "warn",
description: "Wysyła ankiete",
guildOnly: true,
cooldown: 5,
run(msg, args) {
// Embed na permisjebota
const permisjebota = new MessageEmbed()
.setTitle("⛔ Nie mam uprawnień! :O")
.setColor('ffff00')
.setDescription("Nie mam uprawnień do tej komendy! Daj mi uprawnienia lub skonsultuj się z adminem serwera")
.setTimestamp()
// Embed na permisje dla użytkownika
const permisje = new MessageEmbed()
.setTitle("Nie masz permisji do tej komendy! :O")
.setColor('ffff00')
.setDescription("Nie masz uprawnień do tej komendy! Jeżeli uważasz, że to błąd skonsultuj się z adminem serwera!")
if (!msg.member.guild.me.hasPermission("ADMINISTRATOR"))
return msg.channel.send(permisjebota)
if (!msg.member.hasPermission("MANAGE_MESSAGES")) return msg.channel.send(permisje)
if(!args[0, 1]) {
const bananekbot = new MessageEmbed()
.setTitle("Nie podałeś argumentów!")
.setColor('ffff00')
.setDescription("Poprawne użycie: `m!warn <nick> <powód>`")
return msg.channel.send(bananekbot)
}
var warnUser = msg.guild.member(msg.mentions.users.first() || msg.guild.members.get(args[0]))
var reason = args.slice(1).join(" ")
if (!warnUser) return msg.channel.send("Brak argumentu poprawne użycie: m!warn <nick> <powód>")
if (!warns[warnUser.id]) warns[warnUser.id] = {
warns: 0,
}
warns[warnUser.id].warns++
fs.writeFile("./warnings.json", JSON.stringify(warns), (err) =>{
if(err) console.log(err)
})
const warnembed = new MessageEmbed()
.setTitle("✅ Nadano warna")
.setColor('ffff00')
.setTimestamp()
.setDescription(`Użytkownik: ${warnUser} (${warnUser.id})
Nadający warna: ${msg.author}
Powód: ${reason}`)
return msg.channel.send(warnembed)
}
}
A potential solution to this is to have warnings.json as an array, and in side containing an object with guild id, warns and anything else you need to store. So warnings.json ends up something like this.
[
{
"guild_id": "12345678901234",
"an_extra": "Thing",
"warns": [
"your_warns",
"are_here",
"store_in_any_format"
]
},
{
"guild_id": "12345678901234",
"an_extra": "Guild",
"warns": [
"so_on",
"And so forth",
"go the warns and guilds"
]
}
]
This way, you can simply do Array.find(guild => guild.guild_id === msg.guild.id) (Assuming the guild you are trying to access is msg.guild).
Learn more on MDN about Array.prototype.find()

Categories