Undefined username in leaderboard command [ quick.db / discord.js ] - node.js

I've tried making a leaderboard command with quick.db for my Discord.js bot but it isnt working.
It replies with undefined users and stuff like that!
var money = await db.all(`money_${message.guild.id}`, { sort: ".data" });
let resp = "";
for (let i = 0; i < money.length; i++) {
let user = client.users.cache.get(money[i].ID.split("_")[1]);
resp += `${i + 1}. ${user} - ${money[i].data}$\n`;
}
return message.channel.send(
new Discord.MessageEmbed().setAuthor(`Leaderboard`).setDescription(resp)
);
Here is the code ^^^^
Here is the output for the command

It means that money[i].ID.split("_")[1] is not a valid ID. Have you thought about logging these values in the loop to check the validity of the data you store?

Related

.permission.has() discord.js v12 - Cannot read property 'permissions' of undefined

I'm having trouble coding my bot for people who have MANAGE_MESSAGES to be able to say 'badword'. Here is my code:
const Discord = require('discord.js')
const bot = new Discord.Client()
const token = process.env.DISCORD_TOKEN
let set = new Set(['badword'])
bot.on('message', msg => {
if (msg.author.bot) {
return
}
let wordArray = msg.content.split(' ')
if (!msg.member.hasPermission('MANAGE_MESSAGES')) {
for(var i = 0; i < wordArray.length; i++) {
if(set.has(wordArray[i].toLowerCase())) {
msg.delete()
msg.channel.send(`${msg.author.username}, you said a bad word.`)
break
}
console.log('message filtered')
}
}
})
bot.login(token)
The .permissions.has() is not working as according to this website https://discordjs.guide/additional-info/changes-in-v12.html#permissions-haspermission-s, it says that .hasPermission() / .hasPermissions() is now completely removed from v11 and added permissions.has(). Yes, my bot is upgraded to v12 so please help.
The correct way to use it is .hasPermission('MANAGE_MESSAGES')
if (!msg.member.hasPermission('MANAGE_MESSAGES'))
You're using the GuildMember class which uses the hasPermission() method. You were looking at the permission class.
https://discord.js.org/#/docs/main/stable/class/GuildMember

TypeError: Cannot read property ' ' error with discord.js

So I have figured out how to set up a simple database with discord.js in a users.json file and my !start cmnd works to create the users database, but when me and my cousin tried the !daily cmnds, the cmnd seems to be fine but I get this error: TypeError: Cannot read property 'a number' of undefined. I believe the number refers to my user number or database number (a number means an actual long number, not "a number").
Also here is the code that goes along with this that is in my index.js file:
var UserJSON = JSON.parse(Fs.readFileSync('./DB/users.json'));
UserJSON[message.author.id] = {
bal: 0,
lastclaim: 0,
}
Fs.writeFileSync('./DB/users.json', JSON.stringify(UserJSON));
let SuccessEmbed = new Discord.MessageEmbed();
SuccessEmbed.setTitle("**SUCCESS**");
SuccessEmbed.setDescription("You have joined the economy! type !help to get started");
message.channel.send(SuccessEmbed);
return;
}
if (args[0] == "daily") {
let userJSON = JSON.parse(Fs.readFileSync('./DB/users.json'));
if (Math.floor(new Date().getTime() - UserJSON[message.author.id].lastclaim) / (1000 * 60 * 60 * 24) < 1) {
let WarningEmbed = new Discord.MessageEmbed()
WarningEmbed.setTitle("**ERROR**");
WarningEmbed.setDescription("You have claimed today already");
message.channel.send(WarningEmbed);
return;
}
UserJSON[message.author.id].bal += 500;
UserJSON[message.author.id].lastclaim = new Date().getTime();
Fs.writeFileSync('./DB/users.json', JSON.stringify(UserJSON));
let SuccessEmbed = new Discord.MessageEmbed();
SuccessEmbed.setTitle("**SUCCESS**");
SuccessEmbed.setDescription("You have claimed a daily reward of 500 coins!");
message.channel.send(SuccessEmbed);
}
}
})
Also to specify, the ./DB/users.json refers to the folder DB for database and users.json is the file that stores the databases.
Here is what the user.json file looks like:
{"*my database number*":{"bal":0,"lastclaim":0},"*my cousin's database number*":{"bal":0,"lastclaim":0}}
Is there any code I need to add into my index.js file to stop this from happening. If possible, answer as soon as possible so I can get this error worked out. Thank You!
Edit: I somehow figured this out by re-doing it and this is the finished product if anyone wants to start an economy bot:
const Discord = require("discord.js");
const client = new Discord.Client();
const Fs = require("fs");
const prefix = "!";
client.on("ready", () => {
console.log("Ready!");
});
client.on("message", async (message) => {
if(message.content.startsWith(prefix)) {
var args = message.content.substr(prefix.length)
.toLowerCase()
.split(" ");
if (args[0] == "start") {
let UserJSON = JSON.parse(Fs.readFileSync("./DB/users.json"));
UserJSON[message.author.id] = {
bal: 0,
lastclaim: 0,
}
Fs.writeFileSync("./DB/users.json", JSON.stringify(UserJSON));
let SuccessEmbed = new Discord.MessageEmbed();
SuccessEmbed.setTitle("**SUCCESS**");
SuccessEmbed.setDescription("You have joined the economy! type !help to get started");
message.channel.send(SuccessEmbed);
return;
}
if (args[0] == "daily") {
let UserJSON = JSON.parse(Fs.readFileSync("./DB/users.json"));
if (Math.floor(new Date().getTime() - UserJSON[message.author.id].lastclaim) / (1000 * 60 * 60 * 24) < 1) {
let WarningEmbed = new Discord.MessageEmbed()
WarningEmbed.setTitle("**ERROR**");
WarningEmbed.setDescription("You have claimed today already");
message.channel.send(WarningEmbed);
return;
}
UserJSON[message.author.id].bal += 500;
UserJSON[message.author.id].lastclaim = new Date().getTime();
Fs.writeFileSync("./DB/users.json", JSON.stringify(UserJSON));
let SuccessEmbed = new Discord.MessageEmbed();
SuccessEmbed.setTitle("**SUCCESS**");
SuccessEmbed.setDescription("You have claimed a daily reward of 500 discord coins!");
message.channel.send(SuccessEmbed);
}
}
})
client.login('your token');
also remember to make a DB folder with an users.json file
I realized that the problem with the code is that instead of vars, it needed to be let before the UserJSON, so the line of code should read:
let UserJSON = JSON.parse(Fs.readFileSync("./DB/users.json"));
UserJSON[message.author.id] = {
bal: 0,
lastclaim: 0,
}

Can someone please fix this loop? It has errors in iterating next value and saving array data

Here is the loop.
for(let k = 0; k <2; k++) {
await dmb.page.waitForSelector('a > div > div.Igw0E.rBNOH.YBx95.ybXk5._4EzTm.soMvl > div[class]');
await dmb.page.click('a > div > div.Igw0E.rBNOH.YBx95.ybXk5._4EzTm.soMvl > div[class]');
await dmb.page.waitFor(2000);
for(let i = 0; i < textbycomma.length; i++){
let type = textbycomma[i];
await dmb.page.waitForSelector('textarea[placeholder="Message..."]');
await dmb.page.type('textarea[placeholder="Message..."]', type , {delay: 100});
let toClick = await dmb.page.$x('//button[contains(text(), "Send")]');
await toClick[0].click();
await dmb.page.waitFor(2000);
let readurls = []
readurls[k] = dmb.page.url();
var hrefs = {
href : readurls
}
fs.writeFileSync('./savedlinks.json', JSON.stringify(hrefs));
if(i = textbycomma.length){
break;
}
}
await dmb.page.goto('https://www.example.com');
}
Please see here for references:
script: async(text = []) => {
var textbycomma = [] = text.toString().split(',');
This is my example data:
Console:
text : Hello, Nice
textbycomma : ['Hello','Nice']
Loop variable *i* value remains 0 as many times as the loop runs. This only sends the 1st message (Hello) to the users.
In my savedlinks.json, the value saved is:
{"href":[null,"https://www.example.com/"]}
What I want to do with this loop is to send the first message Hello save the sent message urls to my savedlinks.json.
In a cronjob of 1 hour delay, this scripts runs again and checks if the urls match the new users urls, if not it sends the first message and if yes, it send the send message Nice.

How to make a invites command (Discord.js)

Hello, I am currently wondering how to make a invites command for my discord bot.
How it would work will be I use n!invites and it comes with
You have (num) invites.
I would like it to be the amount of invites the user has gained.
If I could get some help here that would be appreciated. Thanks.
Note I have looked at the the discord.js website and there is a place for it but I never understood.
Here is a code I found on another question
client.on('message', message => {
if(message.content === "n!invites"){
var user = message.author;
message.guild.fetchInvites()
.then
(invites =>
{
const userInvites = invites.array().filter(o => o.inviter.id === user.id);
var userInviteCount = 0;
for(var i=0; i < userInvites.length; i++)
{
var invite = userInvites[i];
userInviteCount += invite['uses'];
}
message.reply(`You have ${userInviteCount} invites.`);
}
)
}
});
It gets every invite links from the guild using
message.guild.fetchInvites()
and finds an invite link that was created by the user which is the author, in this case, using a filter
const userInvites = invites.array().filter(o => o.inviter.id === user.id);
Using a for loop, it adds the amount of invites the user has until the invites the user has matches it.
var userInviteCount = 0;
for(var i=0; i < userInvites.length; i++)
{
var invite = userInvites[i];
userInviteCount += invite['uses'];
}
Then it adds the amount of uses to the userInviteCount statement which will be 0 if there is no invite found made by the user or the user has not invited anybody to the server.
Finally is sends a reply with the amount of invites the user has
message.reply(`You have ${userInviteCount} invites.`);
It is in a Template String so you don't have to put + but instead put ${expression} which is userInviteCount, so the amount of invites the user has.
I believe the command you're looking for would look something like this:
if (message.content === 'n!invites') {
var userId = message.author.id;
var userInvites = message.guild.fetchInvites().then(invites => invites.find(invite => invite.inviter.id === userId));
var useAmount = userInvites.uses;
if (useAmount === undefined) {
message.channel.send(`${message.author.username} has 0 invites`);
}
else {
message.channel.send(`${message.author.username} has ${useAmount} invites`);
}
}

How would I make my bot react with random emoji?

I use Discord.js, here's my code so far;
if (message.content === '..react') {
message.react('😀')
message.react('😂')
message.react('🤣')
message.react('😎')
message.react('🙂')
message.react('😣')
message.react('🙄')
message.react('😥')
message.react('😪')
message.react('🤐')
message.react('😛')
const embed = new RichEmbed()
.setDescription('I just reacted with diffrent emojies! React to your favorite!')
.setColor(0x1ED5E7)
message.channel.send(embed);
}
});
I want it to react with any emojis that's available, without going over 11 reactions. Help would be greatly appreciated.
If you want to react random emojies you can get all client emoji.id , shuffle it, then slice and react in array map. I do not know methods to get standard unicode emoji lists in Discord, so maybe you need to great all unnciode emoji array and then concat its with emojilist array.
React with 11 random available client emoji you can somethink like this
if (message.content === '..react') {
let emojiList = bot.emojis.map(emoji => emoji.id)
let randTenEmojies = shuffle(emojiList).splice(0,11)
randTenEmojies.map(emoji => message.react(emoji))
const embed = new RichEmbed()
.setDescription('I just reacted with diffrent emojies! React to your favorite!')
.setColor(0x1ED5E7)
message.channel.send(embed);
}
});
const shuffle = (arr) => {
var j, temp;
for(var i = arr.length - 1; i > 0; i--){
j = Math.floor(Math.random()*(i + 1));
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
return arr;
}

Resources