0

I would like to create a leaderboard to make it in my discord bot.

Already to start it, I made a JSON classic database with just userID and Coins columns.

{"3879720334874588161":{"coins":5},"3919222756303420417":{"coins":5}}

Now I would make a leaderboard with this database, but I have some problem:

(node:15500) UnhandledPromiseRejectionWarning: TypeError: coins.sort is not a function
    at Object.module.exports.run (c:\Users\StarKleey\Desktop\Bot discord\Bot Folletto\Commandes\list.js:9:9)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
warning.js:32
(node:15500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
warning.js:32
(node:15500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

And my code is as follows

const Discord = require("discord.js");
const fs = require('fs');

module.exports.run = async (client, message, args) => {
  await message.delete();

  let coins = JSON.parse(fs.readFileSync("./coins.json", "utf8"));

  coins.sort([
    ['coins', 'descending']
  ]).exec((err, res) => {
    if (err) console.log(err);

    let embed = new Discord.MessageEmbed()
      .setTitle("Coins Leaderboard")
    //if there are no results
    if (res.length === 0) {
      embed.setColor("RED");
      embed.addField("No data found", "Please type in chat to gain coins!")
    } else if (res.length < 10) {
      //less than 10 results
      embed.setColor("BLURPLE");
      for (i = 0; i < res.length; i++) {
        let member = message.guild.members.get(res[i].userID) || "User Left"
        if (member === "User Left") {
          embed.addField(`${i + 1}. ${member}`, `**Coins**: ${res[i].coins}`);
        } else {
          embed.addField(`${i + 1}. ${member.user.username}`, `**Coins**: ${res[i].coins}`);
        }
      }
    } else {
      //more than 10 results
      embed.setColor("BLURPLE");
      for (i = 0; i < 10; i++) {
        let member = message.guild.members.get(res[i].userID) || "User Left"
        if (member === "User Left") {
          embed.addField(`${i + 1}. ${member}`, `**Coins**: ${res[i].coins}`);
        } else {
          embed.addField(`${i + 1}. ${member.user.username}`, `**Coins**: ${res[i].coins}`);
        }
      }
    }

    message.channel.send(embed);
  })
}
module.exports.help = {
  name: "leaders"
}

Could someone solve my problem or know another solution to do a leaderboard?

1 Answer 1

0

The error you have says that coins.sort() is not a function.

Your coins variable is an Object. If you look at MDN / another website for what methods are available on an object, you will see that there is no sort method available.

So you are trying to call a function that does not exist, hence the error.

Current way you are storing users & coins (not recommended)

If you want to sort your coins object with your current file you could use

const sorted = [];
const keys = Object.keys(coins)

for (let user in coins) {
  const coin = coins[user].coins;
  
  const entry = {[keys[sorted.length]] : coins[user]}
  
  if (sorted.length === 0) {
    sorted.push(entry);

    continue;
  }
  let i = 0;
  while (sorted[i] !== undefined && sorted[i][Object.keys(sorted[i])].coins > coin) {
    i++;
  }
    
  sorted.splice(i, 0, entry)
}

JSFiddle Example

The way I would store the users and then sort (recommended)

I would recommend to save your users with coins as :

[{userID: "123", coins: 12}, ]

then you could use

betterCoins.sort((a,b)=>{b.coins - a.coins});

JSFiddle Example

You can also just cast your Object to an array and use the recommended method without needing to change how your file is structured :

const newCoins = [];

for(let userObj in coins){
    newCoins.push({"name" : userObj, "coins": coins[userObj].coins })
}
4
  • Thank you very much ! I'm going to do it your way right away !
    – StarKleey
    May 5, 2020 at 13:32
  • Hey, I'm back to ask you if you have a tutorial or documentation to explain your solutions to me
    – StarKleey
    May 5, 2020 at 13:49
  • @StarKleey I am not sure which part(s) of my solution(s) you don't understand, if you can provide more context I might be able to help.
    – Twiggeh
    May 5, 2020 at 14:40
  • I don't understand how u save your data ? it's on json or directly on js ? And i don't know how i can my data like you.
    – StarKleey
    May 5, 2020 at 15:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.