Economy leaderboard command: undefined - discord.js

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?

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.

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.

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')){}

DiscordJS Argument Slice

I want to make a image embed via arguments, but I can't set the Title of the embed.
But when I try to run the comand, it errors out and the embed won't appear
if(message.content.startsWith(prefix + "foto-annuncio"))
{
if(!message.member.hasPermission(["MANAGE_MESSAGES"]))
{
/* error message pops out */
}
let argsresult;
let mChannel = message.mentions.channels.first()
message.delete()
argsresult = args.slice(1).join(" ")
let url = args.slice(1).join(" ");
let title = args.slice(2);
message.delete();
const embed = new Discord.RichEmbed ()
.setImage(url)
.setColor('#008000')
.setAuthor('Delta Logistics', 'https://cdn.discordapp.com/attachments/604963851561336832/665504827044003860/zoom_delta_6_discord.png')
.setTitle(title)
mChannel.send(embed).catch(err => console.log(err));
message.channel.send("Done!");
}
As Giuuliopime said you can't set an array as a title, you prob meant to join the arguments:
const title = args.slice(2).join(" ");

Resources