2 numbers not adding together correctly - discord

I'm using repl.it database for a discord economy bot that i'm making. I made a withdraw command, but when I type !withdraw 10 I'm expecting to receive currentbalance + amount (like if current balance is 50 and i typed !with 100 I should get 150) but I keep getting "50100". Here is my code:
if (message.content.toLowerCase().startsWith("#ايداع")) {
const args = message.content.trim().split(/ +/g);
let money = await db.get(`wallet_${message.member}`)
let currentbalance1 = await db.get(`wallet_${message.member}`)
let currentbalance = await db.get(`bank_${message.member}`)
let gembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("ليس لديك مبلغ كافي للايداع")
let cembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("يرجى تحديد مبلغ للايداع");
let amount = args[1];
if (!amount || isNaN(amount))
return message.reply(cembed);
await db.set(`bank_${message.member}`, currentbalance + amount);
await db.set(`wallet_${message.member}`, currentbalance1 - amount)
let sembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("لقد قمت بايداع" + amount + "الى حسابك البنكي");
message.channel.send(sembed);
}

If your output is 50100 from 50 + 100 it means that your numbers (50 and 100) are strings not numbers. A simple solution would be to use parseInt.
Example:
let currentbalance1 = await db.get(`wallet_${message.member}`);
let currentbalance = await db.get(`bank_${message.member}`);
await db.set(`bank_${message.member}`, parseInt(currentbalance) + parseInt(amount));
await db.set(`wallet_${message.member}`, parseInt(currentbalance1) - parseInt(amount));
Full example:
if (message.content.toLowerCase().startsWith("#ايداع")) {
const args = message.content.trim().split(/ +/g);
let money = await db.get(`wallet_${message.member}`)
let currentbalance1 = await db.get(`wallet_${message.member}`)
let currentbalance = await db.get(`bank_${message.member}`)
let gembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("ليس لديك مبلغ كافي للايداع")
let cembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("يرجى تحديد مبلغ للايداع");
let amount = args[1];
if (!amount || isNaN(amount)) return message.reply(cembed);
await db.set(`bank_${message.member}`, parseInt(currentbalance) + parseInt(amount));
await db.set(`wallet_${message.member}`, parseInt(currentbalance1) - parseInt(amount))
let sembed = new Discord.MessageEmbed()
.setColor("RED")
.setDescription("لقد قمت بايداع" + amount + "الى حسابك البنكي");
message.channel.send(sembed);
}

Related

How do I substract/add currency to balance with quick.db?

The bot says that I robbed someone but does not add/substract the currency from neither of the users.
Another issue I found is that I can rob myself.
Code I used:
const Discord = require("discord.js");
const db = require("quick.db");
const ms = require("parse-ms");
module.exports.run = async (bot, message, args) => {
if(!message.content.startsWith('db!'))return;
let user = message.mentions.members.first()
let targetuser = await db.fetch(`money_${message.guild.id}_${user.id}`)
let author = await db.fetch(`rob_${message.guild.id}_${user.id}`)
let author2 = await db.fetch(`money_${message.guild.id}_${user.id}`)
let timeout = 600000;
if (author !== null && timeout - (Date.now() - author) > 0) {
let time = ms(timeout - (Date.now() - author));
let timeEmbed = new Discord.RichEmbed()
.setColor("#FFFFFF")
.setDescription(`❌ You have already robbed someone\n\nTry again in ${time.minutes}m ${time.seconds}s `);
message.channel.send(timeEmbed)
} else {
let moneyEmbed = new Discord.RichEmbed()
.setColor("#FFFFFF")
.setDescription(`❌ You need atleast 200 dabloons in your wallet to rob someone`);
if (author2 < 200) {
return message.channel.send(moneyEmbed)
}
let moneyEmbed2 = new Discord.RichEmbed()
.setColor("#FFFFFF")
.setDescription(`❌ ${user.user.username} does not have anything you can rob`);
if (targetuser < 0) {
return message.channel.send(moneyEmbed2)
}
let vip = await db.fetch(`bronze_${user.id}`)
if(vip === true) random = Math.floor(Math.random() * 200) + 1;
if (vip === null) random = Math.floor(Math.random() * 100) + 1;
let embed = new Discord.RichEmbed()
.setDescription(`✔️ You robbed ${user} and got away with ${random} dabloons!`)
.setColor("#FFFFFF")
message.channel.send(embed)
db.subtract(`money_${message.guild.id}_${user.id}`, random)
db.add(`money_${message.guild.id}_${user.id}`, random)
db.set(`rob_${message.guild.id}_${user.id}`, Date.now())
};
}
module.exports.help = {
name:"rob",
aliases: [""]
}
I tried using code from other people, but the code I used did not work and just broke the bot
To solve the db issue, you can see Elitezen's comment
To solve the issue where you can rob yourself,
you can simply check if the person getting robbed is the author of the message
if(message.mentions.members.first().id === message.member.id) return message.channel.send(errorEmbed)
Also, this is a super outdated version of discord.js and is highly recommended to update.

(CLOSED) Bot doesnt send anything, and doesnt give an error

I have this code:
#rob
#client.command()
#commands.cooldown(1,10800,commands.BucketType.user)
async def rob(ctx,member:discord.User = None):
if member == None:
em = discord.Embed(title='ERROR:', description='Please specify a member you want to rob!', color=0xff0000)
await ctx.send(embed = em)
return
await open_account(ctx.author)
await open_account(member)
bal = await update_bank(member)
if bal[0]<50:
em = discord.Embed(title='ERROR:', description="The member you try to rob doesn't have that much money!", color=0xff0000)
await ctx.send(embed = em)
return
if amount<0:
em = discord.Embed(title='ERROR:', description="Amount must be positive!", color=0xff0000)
await ctx.send(embed = em)
return
earnings = random.randrange(0, bal[100])
fine = random.randrange(0, bal[100])
em1 = discord.Embed(title='Succesfully robbed!', description=f"You robbed {earnings} coins!", color=0x00ff00)
em2 = discord.Embed(title='Caught!', description=f"You got caught! You paid a {fine} coins fine! ", color=0x00ff00)
yesorno = random.randrange(0, 1)
if yesorno == 1:
await ctx.send(embed = em1)
await update_bank(ctx.author,earnings)
await update_bank(member,-1*earnings)
else:
await ctx.send(embed = em2)
await update_bank(ctx.author,-1*fine)
This function's goal is to rob someone and take their money or give them a fine, but it doesn't work. It doesn't send em1 or em2, I don't know how to fix it. I tried many things, but it doesn't give an error!
What fixed it for me was changing the yesorno function. Changed it to:
yesorno = random.randrange(0, 2)
if yesorno == 1:
await ctx.send(embed = em1)
await update_bank(ctx.author,1*earnings)
await update_bank(member,-1*earnings)
else:
await ctx.send(embed = em2)
await update_bank(ctx.author,-1*fine)
await update_bank(member,1*fine)

how to fix that quick.db doesn't make a negative output

I am doing an economic system at my discord bot. It went well but when I use some subtract command or withdraw command or your balance will be subtract
it got to negative number like I minus my balance to 50 but my balance is only 25 now my balance is now -25 how to fix it??
My balance file:
module.exports ={
name:'bal',
description: "bal for user",
execute(message, args, Discord, db){
const target = message.mentions.users.first() || message.author
const targetid = target.id
if(db.get(`user_${targetid}.bal`) === null){
message.channel.send('you need to create an account')
}else{
let bal = db.get(`user_${targetid}.bal`)
let bank = db.get(`user_${targetid}.bank`)
let embed = new Discord.MessageEmbed()
.setTitle(`${target.username} BALANCE`)
.setColor('GREEN')
.setDescription(`coins: ${bal} Cheese Coins \nbank: ${bank} Cheese Coins`)
message.channel.send(embed)
}
}
}
My substract file:
module.exports ={
name:'sub',
description: "sub",
execute(message, args, Discord, db){
const hey = message.mentions.users.first()
const number = args[1]
if(!hey){
message.channel.send('Mention someone or ill take yours')
}else if(!number){
message.channel.send('Put a number, take it or leave it')
}else{
let embed = new Discord.MessageEmbed()
.setTitle('Poor speedrun Any%')
.setColor('YELLOW')
.setDescription(`Total of ${number} money has revoked been from ${hey}, **SAD ${hey} NOISES**`)
db.subtract(`user_${hey.id}.bal`, number)
message.channel.send(embed)
}
}
}
Verify if the userbalance is less than the amount you trying to substract.
const userbalance = db.get(`user_${hey.id}.bal`);
if(userbalance < number) return;
db.subtract(`user_${hey.id}.bal`, number)

Economy leaderboard command: undefined

I am making a discord economy/currency bot, and this is the leaderboard command. It works, but whenever I run the command !leaderboard, I don't get any of the user's tags, I just get the undefined#0000. I would like my leaderboard command to show the users with the highest amount of currency.
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = {
name: "leaderboard",
description: 'server\'s $ leaderboard',
aliases: ['lb'],
}
module.exports.run = async (message) => {
let money = db.all().filter(data => data.ID.startsWith(`money_`)).sort((a, b) => b.data - a.data);
if (!money.length) {
let noEmbed = new MessageEmbed()
.setAuthor(message.member.displayName, message.author.displayAvatarURL())
.setColor("BLUE")
.setFooter("No leaderboard")
return message.channel.send(noEmbed)
};
money.length = 10;
var finalLb = "";
for (var i in money) {
let currency1;
let fetched = await db.fetch(`currency_${message.guild.id}`);
if (fetched == null) {
currency1 = '🎱'
} else {
currency1 = fetched
}
if (money[i].data === null) money[i].data = 0
finalLb += `**${money.indexOf(money[i]) + 1}. ${message.guild.members.cache.get(money[i].ID.split('_')[1]) ? message.guild.members.cache.get(money[i].ID.split('_')[1]).tag : "undefined#0000"}** - ${money[i].data} ${currency1}\n`;
};
const embed = new MessageEmbed()
.setTitle(message.guild.name)
.setColor("BLUE")
.setDescription(finalLb)
.setTimestamp()
.setFooter('Command: !help for currency commands')
message.channel.send(embed);
}
Try following code:
let money = db.all().filter(data => data.ID.startsWith(`money_${message.guild.id}`)).sort((a, b) => b.data - a.data)
money.length = 10;
var finalLb = "";
for (var i in money) {
finalLb += `**${money.indexOf(money[i])+1}. ${client.users.cache.get(money[i].ID.split('_')[1]) ? client.users.cache.get(money[i].ID.split('_')[1]).tag : "Unknown User#0000"}** - ${money[i].data}\n`;
}
const embed = new Discord.MessageEmbed()
.setAuthor(`Global Coin Leaderboard!`, message.guild.iconURL())
.setColor("#7289da")
.setDescription(finalLb)
.setFooter(client.user.tag, client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(embed);
I personally use above code for my bot and it works pretty well for me.
Try putting the client.login('token') at the bottom of your code. Maybe the bot can't find the user tag's because of that?

How would I add a hug reaction command

I have no idea what I’m doing. I don’t code but my friend helped me out up to this part
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('This Bot is online!');
client.user.setActivity('Prefix +k')
});
client.on('message', msg=>{
if(msg.content === "+k Hello"){
msg.reply('Welcome!');
}
})
client.on('message', msg=>{
if(msg.content === "+k Credits"){
msg.reply('Pokemon DB for Info, MrTechGuy for code help!');
}
})
client.on('message', msg=>{
if(msg.content === "+k Credits"){
msg.reply('Pokemon DB for Info, MrTechGuy for code help!');
}
})
client.on('message', msg=>{
if(msg.content === "+k DAList"){
msg.reply('1 - Butterfree <:V:750540886680666282> <:grass:750540661396340826>, 2 = Butterfree <:VMAX:750540886701637743> <:grass:750540661396340826>,');
}
})
client.login('[REDACTED]');
Again, how would I add a hug command that targets the user, e.g. +k hug #user 1, my friend is out for the month and I do not know how to do it
response: #user 2 hugged #user 1 ! (gif here)
For this to work you will need to create a folder named "hug" and with images which are "gif".
if(message.content.startsWith('+k hug')) {
let user = msg.mentions.users.first(); // refers to the user you wish to mention
if (!user) {
let maxImageNumber1 = 7; // represents the number of images in the folder
let hug = Math.floor(Math.random() * (maxImageNumber1 - 1 + 1)) + 1;
let imageName1 = `${hug}.gif` // if the images you put are png/jpg just remove the ".gif" with either ".png" or ".jpg"
let imagePath1 = `/hug/${imageName1}` // folder name
let file1 = new Discord.MessageAttachment(imagePath1);
let embed1 = new Discord.MessageEmbed();
embed1.setImage(`attachment://${imageName1}`)
embed1.setDescription(`**${msg.author.username}** hugged their clone`)
embed1.setColor('RANDOM')
msg.channel.send({ files: [file1], embed: embed1 });
}
if (user) {
let maxImageNumber1 = 7; // represents the number of images in the folder
let hug = Math.floor(Math.random() * (maxImageNumber1 - 1 + 1)) + 1;
let imageName1 = `${hug}.gif` // if the images you put are png/jpg just remove the ".gif" with either ".png" or ".jpg"
let imagePath1 = `/hug/${imageName1}` // folder name
let file1 = new Discord.MessageAttachment(imagePath1);
let embed1 = new Discord.MessageEmbed();
embed1.setImage(`attachment://${imageName1}`)
embed1.setDescription(`**${msg.author.username}** hugged **${user.username}**`)
embed1.setColor('RANDOM')
msg.channel.send({ files: [file1], embed: embed1 });
}
}
Im assuming you are using discord.js v12
TIP:
I'd recommend you define your prefix with something like const prefix = '+k'; and when you want to make a command do this: if(message.content.startsWith(prefix + 'hug')){}

Resources