Quick.db .add function not working correctly - javascript

Im making an addmoney cmd for my discord bot but when the money, it gets added weirdly.
Eg. normally it would be 200 if i add 100 and there was already 100 but im my occasion its 100100.
Anyways code:
const { QuickDB } = require('quick.db');
const db = new QuickDB();
const discord = require("discord.js")
module.exports.run = async (bot, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return message.reply("You do not have the permissions to use this command😔.")
if (!args[0]) return message.reply("Please specify a user❗")
let user = message.channel.members.first() || message.guild.members.cache.get(args[0]) || messsage.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.member.cache.find(r => r.displayName.toLowerCase() === args[0].toLocaleLowerCase())
if (!user) return message.reply("Enter a valid user⛔.")
if (!args[1]) return message.reply("Please specify the amount of money💰.")
var embed = new discord.MessageEmbed()
.setColor("#C06C84")
.setAuthor(message.author.tag, message.author.displayAvatarURL({dynamic: true}))
.setDescription(`Cannot give that much money⛔.
Please specify a number under 10000💸.`)
.setTimestamp()
if (isNaN(args[1]) ) return message.reply("Your amount is not a number❗.")
if (args[0] > 10000) return message.reply({embeds: [embed]})
await db.add(`money_${user.id}`, args[1])
let bal = await db.get(`money_${user.id}`)
let moneyEmbed = new discord.MessageEmbed()
.setColor("#C06C84")
.setDescription(`Gave $${args[1]} \n\nNew Balance: ${bal}`)
message.reply({embeds: [moneyEmbed]})
}
module.exports.help = {
name: "addmoney",
category: "economy",
description: 'Adds money!',
}

One way you could get this kind of behaviour is if args[1] was a string. In that case, instead of adding the value, it would just concatenate it with the current value of money_${user.id}. So, to fix it all you have to do is, instead of passing it directly, use parseInt() and then pass it. Then, your fixed part might look like this =>
await db.add(`money_${user.id}`, parseInt(args[1]))

Related

Getting GuildMember Object with user ID Discord.js v13

I'm fairly new to discord.js and Javascript in general. Here I created a simple userinfo command which fetches data of the user and embeds it neatly as you can see below. You can also see that the command requires the author/mod to mention the user to get the result embed but I want to get the same result by member's discord userID.
I tried message.mentions.users.first() || message.guild.member.length(args[0]) but this creates a lot of problems. So basically how do I get to use the same command/code by discord ID.
const moment = require('moment');
const Discord = require('discord.js');
const { MessageEmbed } = require('discord.js')
module.exports = {
description: 'whois',
run: async (client, message, args) => {
const user = message.mentions.users.first()
const embed = new MessageEmbed()
.setTitle(`**PASSION ISLAND MODERATIONS**`)
.setColor('#ffc0cb')
.setThumbnail(user.displayAvatarURL({ dynamic: true }))
.addField('Username', user.username)
.addField('User Id', user.id)
.addField('Account Type', `${user.bot ? 'Bot' : 'Human'}`)
.addField(`Roles`, `${message.member.roles.cache.size}`)
.addField(`Joined At`, `${moment.utc(message.member.joinedAt).format('ddd, MMM Do, YYYY, h:mm a')}`)
.addField(`created At`, `${moment.utc(message.member.createdAt).format('ddd, MMM Do, YYYY, h:mm a')}`)
.setTimestamp()
.setFooter(`Requested by ${message.author.username}`)
message.channel.send({ embeds: [embed] })
},
}
You can try using
let user;
if(message.mentions.members.first()) {
user = message.mentions.members.first()
} else {
let x = await message.guild.members.cache.get(`${args[0]}`)
user = x.user;
}
This would work well with IDs since you can pass a snowflake within the .get() function.
This is the code I'm using, can find by user's id, user's name or user's tag.
let user = message.mentions.users.first()||null;
if (!user && args.length > 0) {
let input = args.join(' ')
let temp = message.guild.members.cache.get(input) || message.guild.members.cache.find(mem => mem.user.username === input) || mmessage.guild.members.cache.find(mem => mem.user.discriminator === input) || null
if (temp) user = temp.user;
}
If you want to be 100% sure you will find the user if he exists in the server can do:
message.mentions.users.first() || message.guild.members.fetch(args[0])
You can try using
message.mentions.members.first().then((m) => {
if (!m) {
// code
}
})
// or do this
const member = await message.mentions.members.first();
if (!member) {
// Code
}
or change the members to an users
as other people have shown you can do that by finding the id in the server like so
message.guild.members.cache.get(args[0]);
// This will return null if it doesnt exist so you can do this
const member = await message.guild.members.cache.get(args[0]);
if (!member) {
// code
}
You can combine both of them to check it and be sure that the member exists like this
const member = await message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!member) {
// Code
}
hopefully this helped
NOTE : I see that you are using multiple .addField() you can use .addFields() to optimize your code
like this
const embed = new MessageEmbed()
.addFields(
{ name: 'name', value: 'the description', inline: true || false },
{ name: 'name', value: 'the description', inline: true || false },
)

Reacting to the emoji only once - Discord.js

I am developing this bot, and I want the user to be able to react only once in the emoji, and if he reacts other times the command does not work. Can someone help me?
let messagereturn = await message.channel.send(embed);
await messagereturn.react('🔁');
const reactions = ['🔁'];
const filter = (reaction, user) => reactions.includes(reaction.emoji.name) && user.id === User.id;
const collector = messagereturn.createReactionCollector(filter)
collector.on('collect', async emoji => {
switch(emoji._emoji.name) {
case('🔁'):
const embed1 = new Discord.MessageEmbed()
.setColor('#00ff00')
.setDescription(`${User} **deu um tapa em** ${message.author}`)
.setImage(rand)
await message.channel.send(embed1)
}
})
The createReactionCollector method has an optional options object, and it allows you to set the max reactions to collect, which in your case is 1.
example:
const collector = messagereturn.createReactionCollector(filter, { max: 1 })

Discord.js crypto currency command returning undefined for prices

I created a command to get the price data of a given cryptocurrency. When I run my command, the embed has "undefined" for each price value.
Here is my code:
module.exports = {
name: 'crypto',
description: 'gets crypto data',
async execute (message, args) {
let cc = args.slice(0).join(' ');
const noArgs = new Discord.MessageEmbed()
.setTitle('Missing arguments')
.setColor((Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0'))
.setDescription('You are missing some args (ex: -crypto bitcoin || -covid dogecoin)')
.setTimestamp(new Date().getTime())
if(!cc) return message.channel.send(noArgs);
await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${cc}&vs_currencies=usd%2Ceur%2Cgbp`)
.then (response => response.json)
.then(data => {
let usdprice = data.usd
let europrice = data.eur
let gbpprice = data.gbp
const embed = new Discord.MessageEmbed()
.setTitle(`**Current price of ${cc}:**`)
.setDescription('This data might be inaccurate.')
.setColor((Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0'))
.setTimestamp(new Date().getTime())
.addField('**USD:**', usdprice, true)
.addField('**EURO:**', europrice, true)
.addField('**GBP:**', gbpprice, true)
message.channel.send(embed)
})
}
}
There is also no error in the console when I run the command.
You can use async/await if you've already got an async execute function. this way you can get rid of the then()s.
One of the problem is what #Mellet mentioned, you need to call response.json().
The other one is that the fetch data looks like this (if the coin id is "bitcoin"):
{
"bitcoin": {
"usd": 44833,
"eur": 36948,
"gbp": 32383
}
}
It means that it returns an object which contains another object with the coin id as the key. So if cc's value is bitcoin, you can get the USD price from data.bitcoin.usd. You can't and don't want to hardcode the coin id though, so you will need to add the key as a variable: data[coinId].usd.
I also added a helper function to check if the returned data is empty, so you can send an error message:
const isEmptyObject = (obj) => Object.keys(obj).length === 0;
module.exports = {
name: 'crypto',
description: 'gets crypto data',
async execute(message, args) {
let cc = args.slice(0).join(' ');
if (!cc) {
const noArgs = new Discord.MessageEmbed()
.setTitle('Missing arguments')
.setColor('RANDOM')
.setDescription(
'You are missing some args (ex: -crypto bitcoin || -covid dogecoin)',
)
.setTimestamp(new Date().getTime());
return message.channel.send(noArgs);
}
const response = await fetch(
`https://api.coingecko.com/api/v3/simple/price?ids=${cc}&vs_currencies=usd%2Ceur%2Cgbp`
);
const data = await response.json();
if (isEmptyObject(data)) {
return message.channel.send(
`No returned data from the API. Are you sure "${cc}" is a valid id?`,
);
}
let usdprice = data[cc].usd;
let europrice = data[cc].eur;
let gbpprice = data[cc].gbp;
const embed = new Discord.MessageEmbed()
.setTitle(`**Current price of ${cc}:**`)
.setDescription('This data might be inaccurate.')
.setColor('RANDOM')
.setTimestamp(new Date().getTime())
.addField('**USD:**', usdprice, true)
.addField('**EURO:**', europrice, true)
.addField('**GBP:**', gbpprice, true);
message.channel.send(embed);
},
};
PS: You can set the colour to 'RANDOM', so you don't need to use extra functions.
.then (response => response.json)
Should be
.then (response => response.json())

Need Assistance With My unmute command for discord.js

Basically This command is giving one major issue and that the fact that when the user is muted he won't be unmuted because of the command not responding back to the mute command
const Discord = require('discord.js');
const fs = module.require('fs');
module.exports.run = async (client, message, args) => {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return;
let unMute = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!unMute) {
let exampleEmbed = new Discord.MessageEmbed()
.setDescription("__UNMUTE INFO__")
.setColor(client.colors.success)
.setThumbnail(client.user.displayAvatarURL())
.addField(`Unmute Command`, `Unmutes a mentioned user.`)
.addField(`Unmute Command`, `Unmutes User By Id.`)
.addField("Example", `${client.config.prefix}Unmutes #user`)
.addField("Example", `${client.config.prefix}Unmutes #id`)
message.channel.send(exampleEmbed);
return;
}
let role = message.guild.roles.cache.find(r => r.name === 'Muted');
message.channel.send(`Please Check roles to be sure user was unmuted`);
if (!role || !unMute.roles.cache.has(role.id)) return message.channel.send(`That user is not muted.`);
if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send(`----`);
let guild = message.guild.id;
let member = client.mutes[unMute.id];
if (member) {
if (member === message.guild.id) {
delete client.mutes[unMute.id];
fs.writeFile("./mutes.json", JSON.stringify(client.mutes), err => {
if (err) throw err;
})
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
}
return;
}
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
message.delete();
}
module.exports.config = {
name: 'unmute',
description: 'Unmute a user.',
access: 'Manage Messages Permission',
usage: 'unmute #vision'
}
I'm Also getting an error message when manually unmuting the user
(node:6604) UnhandledPromiseRejectionWarning: ReferenceError: User is not defined
Any Form of help would be greatly appreciated and thank you for your time.
On the line if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send('----'), you reference the variable User, but you haven't definied it anywhere, and even if it was defined, you need a role not a member or user. I'm pretty sure it should instead be Role.id. Also, not 100% sure on this, but I tnink it should just be Role not Role.id.

Discord Bot - Setting up an embed table/list with contents split into sections

I'm still learning Javascript and such, getting into discord.js so I'm pretty sure the code I'm inputting is absolutely wrong and definitely in need of work.
Essentially what I'm looking to do is split up a command's arguments and separate them into new lines of an embed.
For example, if I was to do: !results "Result 1" "Result 2" "Result 3" it would output into an embed like table:
RESULTS:
Result 1
Result 2
Result 3
Instead, my output keeps coming out as:
Image of what happens in discord
I have tried various different things from searching on google, but I can't seem to find the thing that I need.
const { RichEmbed } = require("discord.js");
module.exports = {
name: "results",
category: "info",
description: "posts results in embed",
usage: "<mention, id>",
run: async (client, message, args) => {
if (message.deletable) message.delete();
let [result1, result2, result3, result4, result5, result6, result7] = args;
if (!args[0])
return message.channel.send("Please provide Result 1.").then(m => m.delete(5000));
if (!args[1])
return message.channel.send("Please provide Result 2.").then(m => m.delete(5000));
if (!args[2])
return message.channel.send("Please provide Result 3.").then(m => m.delete(5000));
if (!args[3])
return message.channel.send("Please provide Result 4.").then(m => m.delete(5000));
if (!args[4])
return message.channel.send("Please provide Result 5.").then(m => m.delete(5000));
if (!args[5])
return message.channel.send("Please provide Result 6.").then(m => m.delete(5000));
if (!args[6])
return message.channel.send("Please provide Result 7.").then(m => m.delete(5000));
const channel = message.guild.channels.find(c => c.name === "cards")
if (!channel)
return message.channel.send("Couldn't find a `#cards` channel").then(m => m.delete(5000));
const embed = new RichEmbed()
.setColor("RANDOM")
.setTimestamp()
.setAuthor("Posted by GM:", (message.author.username, message.author.displayAvatarURL))
.setTitle("**TestTitle**")
.setFooter(message.guild.name, message.guild.iconURL)
.setDescription(`**__Results!__**`)
.addField(`**> Result 1:** ${result1}`)
.addField(`**> Result 2:** ${result2}`)
.addField(`**> Result 3:** ${result3}`)
.addField(`**> Result 4:** ${result4}`)
.addField(`**> Result 5:** ${result5}`)
.addField(`**> Result 6:** ${result6}`)
.addField(`**> Result 7:** ${result7}`);
return channel.send(embed);
}
}
EDIT: I have made some progress, this is the most recent code and this is the output:
IMAGE
You are adding a field, which requires both a title and value. But you are only giving it a value.
I'd recommend just using the description field and separating your stuff by new lines. It will often times look better. Be sure to keep in mind that the description field is only up to 2048 characters though.
Here's a guide you can take a look at:
https://discordjs.guide/popular-topics/embeds.html#embed-preview
In order to parse the arguments you probably have to create a new delimiter, use a comma or something.
const prefix = "!";
if (message.author.bot) return; // exit processing if author is a bot
if (!message.content.startsWith(prefix)) return; // exit processing if message is not a bot command
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if(command === "ping"){
message.channel.send("Hello");
}
if(command === "test"){
message.channel.send("it is a good day for testing!");
if (args.length > 0) {
message.channel.send("Hello " + args[0]);
}
}
You would change the .split(' ') to something like a comma .split(',')
So the user would enter !test,myName
the the bot would reply:
it is a good dat for testing
Hello myName

Categories

Resources