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

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.

Related

2 numbers not adding together correctly

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

Discord warn command + time

Greetings I want to do something to my warn command
I want to add a time to it like: ,warn Noob 5m Cause a noob
warn [name | nickname | mention | ID] [time] [Reason]
I have no idea how to do it can someone help?
const { MessageEmbed } = require("discord.js");
const { redlight } = require('../../JSON/colours.json')
const db = require('quick.db');
module.exports = {
config: {
name: "warn",
aliases: ['report'],
category: "moderation",
description: "reports a user of the guild",
usage: "[name | nickname | mention | ID] <reason> (optional)",
accessableby: "Administrator",
},
run: async (bot, message, args) => {
if (!message.member.hasPermission("MANAGE_GUILD")) return message.channel.send("**You Dont Have The Permissions To Report Someone! - [MANAGE_GUILD]**");
if (!args[0]) return message.channel.send("**Please Enter A User!**")
let target = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!target) return message.channel.send("**Please Enter A User!**")
if (target.id === message.member.id) return message.channel.send("**Cannot Warn Yourself!**")
let reason = args.slice(1).join(" ")
if (target.roles.highest.comparePositionTo(message.guild.me.roles.highest) >= 0) return message.channel.send('**Cannot Warn This User!**')
if (target.hasPermission("MANAGE_GUILD") || target.user.bot) return message.channel.send("**Cannot Warn This User!**")
try {
const sembed2 = new MessageEmbed()
.setColor("RED")
.setDescription(`**Hello, You Have Been Warned In ${message.guild.name} for - ${reason || "No Reason!"}**`)
.setFooter(message.guild.name, message.guild.iconURL())
target.send(sembed2)
} catch {
}
if (reason) {
const embed = new MessageEmbed()
.setColor("GREEN")
.setAuthor(`${message.guild.name}`, message.guild.iconURL())
.setDescription(`**${target.displayName} Has Been Warned for ${reason}!**`)
message.channel.send(embed)
} else {
const embed = new MessageEmbed()
.setColor("GREEN")
.setAuthor(`${message.guild.name}`, message.guild.iconURL())
.setDescription(`**${target.displayName} Has Been Warned!**`)
message.channel.send(embed)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (!channel) return;
const sembed = new MessageEmbed()
.setColor(redlight)
.setTimestamp()
.setThumbnail(target.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.addField("**Moderation**", "report")
.addField("**User Reported**", `${target}`)
.addField("**User ID**", `${target.user.id}`)
.addField("**Reported By**", `${message.member}`)
.addField("**Reported in**", `${message.channel}`)
.addField("**Reason**", `**${reason || "No Reason"}**`)
.addField("**Date**", message.createdAt.toLocaleString());
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(sembed)
}
}
Thanks in advance!
(Telling me to add more details but idk what I can say more so ignore this lol)
Basically, Your code is hard to get, atleast for me. But you can add timeout fuction like this:-
setTimeout(function(){
//thing you wanna do
}, 1000); //time in milliseconds
Also before you proceed ahead, I don't think you want to make timed warns, which clear after particular time, Maybe. it's on you.

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?

Discord.Js - making a bot that creates custom roles

I'm someone who just got into coding recently.
I'm trying to create a Discord bot that can do custom roles that can allow a user of that custom role to edit its hex or name.
There's also the creation of a role creator that also assigns the mentioned user the role.
My problem is that I've encountered an issue with the role creation + assignment and the commands that allow the user to edit their role.
Here are the problems:
(node:6288) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'get' of undefined for the role creator command
When I try to use the commands that allow the user to customize their roles, the commands don't work, or to be more specific, they don't activate.
I do believe that the codes I'm using could be outdated, therefore if that is the case, please give me the exact location and the right code.
Here are some pictures of the codes. I've pasted the codes below, but I'm a bit new to this forum, so please pay attention to the separating pieces like "Role Customization Code:" to distinguish which one's which. For some reason, the module.exports aren't going in there. Please describe and let me know a solution to these problems in a specific way since I am a newbie at this topic.
Role creation command + assignment error.
Role creation command + assignment code part 1.
Role creation command + assignment code part 2.
Role customization code part 1.
Role customization code part 2.
Role customization code part 3.
Role creation + assignment code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
if (!args[0]) return message.channel.send("Please specify a user to add!");
let toAdd = message.guild.members.get(args[0]) || message.guild.members.get(message.mentions.users.first().id);
let rolejoin = args.slice(1).join(" ");
let myRole = message.guild.roles.cache.get((val) => val.name.toLowerCase() === rolejoin.toLowerCase());
if (!toAdd) return message.channel.send("User not found!");
if (!rolejoin) return message.channel.send("Please specify a role to add!");
let botRole = message.guild.members.get(bot.user.id).highestRole;
let isPosition = botRole.comparePositionTo(myRole);
if (isPosition <= 0) return message.channel.send(embedFail("This role is higher than me, I cannot add this role!"));
let res = await query(`SELECT * FROM user_roles WHERE role_id='${myRole.id}'`);
if (res[0]) {
await query(`DELETE FROM user_roles where role_id='${myRole.id}'`);
toAdd.removeRole(myRole);
message.channel.send(embedSuccess(`Removed role ${myRole.name} from ${toAdd.user.username}`));
} else if (!res[0]) {
await query(`INSERT INTO user_roles (guild_id, user_id, role_id) VALUES ('${message.guild.id}',${toAdd.id},'${myRole.id}')`);
toAdd.addRole(myRole);
message.channel.send(embedSuccess(`Adding role ${myRole.name} to ${toAdd.user.username}`));
}
};
Role Customization Code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args, db) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
let res = await query(`SELECT * FROM user_roles WHERE guild_id = '${message.guild.id}' AND user_id = '${message.author.id}'`);
if (!args[0]) {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
let assignNames = "";
let embed = new Discord.RichEmbed()
.setAuthor(`Current role assigned to ${message.author.username}`, message.guild.iconURL)
.setColor(myRole.hexColor)
.addField(`Name`, `${myRole.name}`, true)
.addField(`Colour`, `${myRole.hexColor}`, true);
message.channel.send(embed);
} else {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
if (!myRole) {
await query(`DELETE FROM user_roles where guild_id = '${message.guild.id}' AND role_id = '${res[i].role_id}' and user_id = '${res[i].user_id}'`);
return message.channel.send(embedFail("You do not have a role!"));
}
switch (args[0]) {
case "name":
let name = args.slice(1).join(" "),
oldName = myRole.name;
await myRole.setName(name);
await message.channel.send(embedSuccess(`You have changed ${oldName}'s name to ${name}!`));
break;
case "color":
case "color":
let hexCode = args[1],
oldHex = myRole.hexColor;
await myRole.setColor(hexCode);
await message.channel.send(embedSuccess(`You have changed ${myRole.name}'s color from ${oldHex} to #${hexCode}!`));
break;
}
}
};

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