discordjs v13 - subtract the variable - javascript

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

Related

interaction failed without any reason discord.js v13

I was making a simple coinflip command in my discord bot. It is working but makes an "Interaction Failed" event without reason. It edits the embed and changes things it should change. and it deletes the message without any problem.
My Code:
const randomResult = Math.floor(Math.random() * 2) == 0 ? "Heads" : "Tails";
const embed = new MessageEmbed()
.setTitle("Coin Flip")
.setColor("YELLOW")
.setDescription(` > ${randomResult}`)
.setFooter({
text: `Requested by ${message.author.username}`,
iconURL: message.author.displayAvatarURL(),
});
const row = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId("again")
.setLabel("Throw Again")
.setEmoji("πŸ”")
.setStyle("PRIMARY"),
new MessageButton()
.setCustomId("delete")
.setLabel("Delete")
.setEmoji("β™»")
.setStyle("DANGER")
);
message.channel.send({ embeds: [embed], components: [row] }).then(msg => {
global.msg = msg;
})
const iFilter = (i) => i.user.id === message.author.id;
const collector = message.channel.createMessageComponentCollector({
filter: iFilter,
time: 30000,
});
collector.on("collect", async (i) => {
if (i.customId === "again") {
const randomResult =
Math.floor(Math.random() * 2) == 0 ? "Heads" : "Tails";
const newEmbed = new MessageEmbed()
.setTitle("Coin Flip")
.setColor("YELLOW")
.setDescription(` > ${randomResult}`)
.setFooter({
text: `Requested by ${message.author.username}`,
iconURL: message.author.displayAvatarURL(),
});
const row = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId("again")
.setLabel("Throw Again")
.setEmoji("πŸ”")
.setStyle("PRIMARY"),
new MessageButton()
.setCustomId("delete")
.setLabel("Delete")
.setEmoji("β™»")
.setStyle("DANGER")
);
msg.edit({ embeds: [newEmbed], components: [row] });
}
if (i.customId === "delete") {
msg.delete();
}
})
collector.on("end", async (i) => {
const newEmbed2 = new MessageEmbed()
.setTitle("Coin Flip")
.setColor("YELLOW")
.setDescription(` > ${randomResult}`)
.setFooter({
text: `Requested by ${message.author.username}`,
iconURL: message.author.displayAvatarURL(),
});
const row = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId("ended")
.setLabel("Coin Flip Ended")
.setEmoji("❎")
.setStyle("DANGER")
.setDisabled(true),
);
msg.edit({embed: [newEmbed2], components: [row]})
})
Note: I am not getting any errors. I am using discord.js v13 and node.js v16
You still have to reply to the interaction using Interaction#reply() method. This is to acknowledge to discord that you handled the interaction. Something like interaction.reply("success") will probably do the job

Discord.js Send a message every X seconds with Client.on('ready', () => { });

I would like to send a message every X seconds and that the user who reacts first gives him 10 coins.
The problem does not come from the system of coins, it is correctly executed.
This code does not work and tells me
Cannot read properties of undefined (reading 'send')
I know this is because I'm not using Client.on('message', message => { }) but I really wish it would go through ready is there any way to do it differently? Can you help me to correct this code?
Client.on('ready', () => {
const fs = require('fs');
const userCoin = JSON.parse(fs.readFileSync('Storage/userCoin.json', 'utf-8'));
const channel2up22 = Client.channels.cache.get('935549530210983976');
//Random Drop
const doSomething = () => {
let Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription("Be the **first** to react ``'πŸš€'`` to this message to win **10 πŸͺ™!**")
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter(text="πŸ€– GuinbearBot | 🌐 Guinbeargang.io")
.setTimestamp()
channel2up22.send(Embed)
.then(message => {
message.react('πŸš€');
Client.on('messageReactionAdd', (reaction, user) => {
if (reaction.emoji.name === 'πŸš€' && user.id == "338621907161317387") {
message.delete();
var Magic09 = 1;
while (Magic09 <= 10)
{
userCoin[user.id].CoinsAmount++;
Magic09++;
}
fs.writeFile('Storage/userCoin.json', JSON.stringify(userCoin), (err) => {if (err) console.error(err);})
let Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription("<#"+ user.id + "> has won the **Wild Gift 🎁 !**")
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter(text="πŸ€– GuinbearBot | 🌐 Guinbeargang.io")
.setTimestamp()
channel2up22.send(Embed)
}
})
}).catch(console.error);
}
setInterval(doSomething(), 5000)
})
//Random Drop
});
Not able to fully test this code but this should work assuming all this code goes into a single file, if you get errors or anything comment below and I'll see what I can do to help out.
// Near top of file but after you have defined your client with const Client = new Discord.Client()
const fs = require('fs')
const Discord = require('discord.js')
const Client = new Discord.Client ({
intents: /*your intents here*/,
})
const guild = Client.guilds.cache.get('935549530210983976')
const channel2up22 = guild.channels.cache.get('935549530210983976');
// channels are an element of the guild not the client
const userCoin = JSON.parse(fs.readFileSync('Storage/userCoin.json', 'utf-8'));
// placing the function outside of a listener and can be called at anytime
function doSomething() {
const Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription("Be the **first** to react ``'πŸš€'`` to this message to win **10 πŸͺ™!**")
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter({
text: "πŸ€– GuinbearBot | 🌐 Guinbeargang.io"
})
.setTimestamp()
channel2up22.send({
embeds: [Embed]
}).then(message => {
message.react('πŸš€');
}).catch(console.error);
}
Client.on('ready', () => {
setInterval(doSomething(), 5000)
// every 5 seconds
})
// you want to avoid nesting listeners if at all possible
Client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.message.channel.id === channel2up22) {
if (reaction.emoji.name === 'πŸš€' && user.id === "338621907161317387") {
// only lets one user react
reaction.message.delete();
var Magic09 = 1;
while (Magic09 <= 10) {
userCoin[user.id].CoinsAmount;
Magic09++;
}
fs.writeFile('Storage/userCoin.json', JSON.stringify(userCoin), (err) => {
if (err) console.error(err);
})
const Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription(`${user} has won the **Wild Gift 🎁 !**`)
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter({
text: "πŸ€– GuinbearBot | 🌐 Guinbeargang.io"
})
.setTimestamp()
channel2up22.send({
embeds: [Embed]
})
}
}
})
Here is my code after your first modifications,
I got now an error back : Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'channels') on the line : const channel2up22 = guild.channels.cache.get('935549530210983976');
const Discord = require("discord.js");
const Client = new Discord.Client;
const fs = require('fs')
const guild = Client.guilds.cache.get('925830522138148976');
const channel2up22 =
guild.channels.cache.get('935549530210983976');
const userCoin = JSON.parse(fs.readFileSync('Storage/userCoin.json', 'utf-8'));
function doSomething() {
const Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription("Be the **first** to react ``'πŸš€'`` to this message to win **10 πŸͺ™!**")
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter({
text: "πŸ€– GuinbearBot | 🌐 Guinbeargang.io"
})
.setTimestamp()
channel2up22.send({
embeds: [Embed]
}).then(message => {
message.react('πŸš€');
}).catch(console.error);
}
Client.on('ready', () => {
setInterval(doSomething(), 5000)
});
Client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.message.channel.id === channel2up22) {
if (reaction.emoji.name === 'πŸš€' && user.id === "338621907161317387") {
reaction.message.delete();
var Magic09 = 1;
while (Magic09 <= 10) {
userCoin[user.id].CoinsAmount;
Magic09++;
}
fs.writeFile('Storage/userCoin.json', JSON.stringify(userCoin), (err) => {
if (err) console.error(err);
})
const Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription(`${user} has won the **Wild Gift 🎁 !**`)
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter({
text: "πŸ€– GuinbearBot | 🌐 Guinbeargang.io"
})
.setTimestamp()
channel2up22.send({
embeds: [Embed]
})
}
}
});

Suggestion Command Using Discord Buttons Discord.JS

So I am trying to make a suggestion command using discord buttons in Discord.JS. When I run the command the embed and the buttons send but whenever I click one of the buttons whether it be Upvote, Maybe, or Downvote it edits the embed, but it never updates the number. I've tried upvote_number ++ and upvote_number + 1 but it doesn't work. It would be awesome if somebody could help me with this. Thank you.
const Discord = require('discord.js');
const disbut = require('discord-buttons');
const { MessageActionRow, MessageButton } = require("discord-buttons");
const { Color, Prefix } = require("../../config.js");
const { MessageEmbed } = require("discord.js");
const disbutpages = require("discord-embeds-pages-buttons")
const db = require('quick.db');
module.exports = {
name: "suggest",
aliases: [],
description: "Suggestion Command",
usage: "^suggest <suggestion>",
run: async(client, message, args) => {
const SayMessage = message.content.slice(8).trim();
let upvote_number = 0
let downvote_number = 0
let maybe_number = 0
const embed = new Discord.MessageEmbed()
.setAuthor("Suggestion from: " + message.author.tag, message.author.displayAvatarURL({dynamic: true}))
.setThumbnail(message.author.displayAvatarURL({dynamic: true}))
.setDescription(SayMessage)
.addField(`Votes`, `Upvote: **${upvote_number}**
Downvote: **${downvote_number}**`)
let upvotebutton = new MessageButton()
.setLabel(`Upvote`)
.setID(`upvote`)
.setEmoji(`⬆️`)
.setStyle("green")
let maybebutton = new MessageButton()
.setLabel(`Maybe`)
.setID(`maybe`)
.setEmoji(`🀷`)
.setStyle("blurple")
let downvotebutton = new MessageButton()
.setLabel(`Downvote`)
.setID(`downvote`)
.setEmoji(`⬇️`)
.setStyle("red")
let row = new MessageActionRow()
.addComponents(upvotebutton, maybebutton, downvotebutton)
const MESSAGE = await message.channel.send(embed, { components: [row] })
const filter = ( button ) => button.clicker.user.id === message.author.id
const collector = MESSAGE.createButtonCollector(filter, { time : 120000 });
collector.on('collect', async (b) => {
if(b.id == "upvote") {
await upvote_number + 1
await MESSAGE.edit(embed, { components: [row] });
await b.reply.defer()
}
if(b.id == "downvote") {
downvote_number + 1
MESSAGE.edit(embed, { components: [row] });
await b.reply.defer()
}
if(b.id == "maybe") {
maybe_number + 1
MESSAGE.edit(embed, { components: [row] });
await b.reply.defer()
}
})
collector.on('end', (b) => {
})
}
};
You'd want to use the += operator for your question. By the way, because of how button collectors work, the suggestions will be timing out after some time, which may cause you some issues in the future, so you may want to switch to the event. My only other concerns are that you are using d.js 12 and discord-buttons which are both deprecated. As d.js 12 is losing support soon because of discord's api updates, I'd highly recommend switching to v13, as it has built in buttons, along with many other new features such as menus and slash commands.
let upvote_number = 0
let downvote_number = 0
let maybe_number = 0
/* ... */
collector.on('collect', async b => {
if(b.id == "upvote") {
upvote_number += 1
updateEmbed()
await MESSAGE.edit(embed, { components: [row] })
await b.reply.defer()
} else if (b.id == "downvote") {
downvote_number += 1
updateEmbed()
await MESSAGE.edit(embed, { components: [row] })
await b.reply.defer()
} else if (b.id == "maybe") {
maybe_number += 1
updateEmbed()
await MESSAGE.edit(embed, { components: [row] })
await b.reply.defer()
}
});
updateEmbed(){
embed.fields.find(i=>i.name==='Votes').value = `Upvote: **${upvote_number}**
Downvote: **${downvote_number}**`
}
tldr: Use += to set vars dynamically as well as update the embed object, and update to `discord.js#latest`

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

Error [ERR_REQUIRE_ESM]: require() of ES Module

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

Categories