简体   繁体   中英

Discord.JS Leaderboards

I currently have some code to detect how many times you can click a reaction in a certain amount of seconds.

I am trying to make a leaderboard for everyone that saves the top 10 with the highest CPS (clicks per second). The code works perfect otherwise, but I am stuck on the leaderboard.

This is my code:

let CPStest = new Discord.MessageEmbed()
    .setColor("#8f82ff")
    .setTitle("CPS Test")
    .setDescription(`Alright, ${message.author.username}. Ready to begin your CPS test? All you have to do is spam click this reaction above ^ as fast as you can, you have 10 seconds before the timer runs out. Good Luck!`)
    .setFooter("Note: This may be inaccurate depending on Discord API and Rate Limits.")
    message.channel.send(CPStest)
    message.react('🖱️');

  // Create a reaction collector
  const filter = (reaction, user) => reaction.emoji.name === '🖱️' && user.id === message.author.id;

  var clicks = 1 * 3; // (total clicks)
  var timespan = 10; // (time in seconds to run the CPS test)

  const collector = message.createReactionCollector(filter, { time: timespan * 1000 });

  collector.on('collect', r => {
      console.log(`Collected a click on ${r.emoji.name}`);
      clicks++;
});

  collector.on('end', collected => {
    message.channel.send(`Collected ${clicks} raw clicks (adding reactions only)`);
  clicks *= 2;
      message.channel.send(`Collected ${clicks} total approximate clicks.`);

  var cps = clicks / timespan / 0.5; // Use Math.round if you want to round the decimal CPS
    message.channel.send(`Your CPS averaged ~${cps} clicks per second over ${timespan} seconds.`);
  
  let userNames = '';
  const user = (bot.users.fetch(message.author)).tag;
    
  userNames += `${user}\n`;
    
  let cpsLeaderboard = new Discord.MessageEmbed()
  .setColor("#8f82ff")
  .setTitle("Current CPS Record Holders:")
  .addFields({ name: 'Top 10', value: userNames, inline: true },
    { name: 'CPS', value: cps, inline: true })
  .setTimestamp()
  message.channel.send(cpsLeaderboard)
    
});

If you want to have a leaderboard, you either need to save it to a file, use a database, or (if you're okay with it that you'll lose it when you restart your bot) you can declare a variable outside of your client.on('message') . It seems to be good enough for testing purposes.

You can create a topUsers array, push the player to that every time the game ends, then sort it and create a leaderboard.

Check the following snippet:

const topUsers = [];

client.on('message', (message) => {
  if (message.author.bot) return;

  let CPStest = new Discord.MessageEmbed()
    .setColor('#8f82ff')
    .setTitle('CPS Test')
    .setDescription(
      `Alright, ${message.author.username}. Ready to begin your CPS test? All you have to do is spam click this reaction above ^ as fast as you can, you have 10 seconds before the timer runs out. Good Luck!`,
    )
    .setFooter(
      'Note: This may be inaccurate depending on Discord API and Rate Limits.',
    );
  message.channel.send(CPStest);
  message.react('🖱️');

  // Create a reaction collector
  const filter = (reaction, user) =>
    reaction.emoji.name === '🖱️' && user.id === message.author.id;

  let clicks = 1 * 3; // (total clicks)
  const timespan = 10; // (time in seconds to run the CPS test)

  const collector = message.createReactionCollector(filter, {
    time: timespan * 1000,
  });

  collector.on('collect', (r) => {
    console.log(`Collected a click on ${r.emoji.name}`);
    clicks++;
  });

  collector.on('end', (collected) => {
    message.channel.send(
      `Collected ${clicks} raw clicks (adding reactions only)`,
    );
    clicks *= 2;
    message.channel.send(`Collected ${clicks} total approximate clicks.`);

    const cps = clicks / timespan / 0.5;
    message.channel.send(
      `Your CPS averaged ~${cps} clicks per second over ${timespan} seconds.`,
    );

    topUsers.push({ tag: message.author, cps });

    let cpses = '';
    let usernames = '';

    topUsers
      // sort the array by CPS in descending order
      .sort((a, b) => b.cps - a.cps)
      // only show the first ten users
      .slice(0, 10)
      .forEach((user) => {
        cpses += `${user.cps}\n`;
        usernames += `${user.tag}\n`;
      });

    const cpsLeaderboard = new Discord.MessageEmbed()
      .setColor('#8f82ff')
      .setTitle('Current CPS Record Holders:')
      .addFields(
        { name: 'Top 10', value: usernames, inline: true },
        { name: 'CPS', value: cpses, inline: true },
      )
      .setTimestamp();
    message.channel.send(cpsLeaderboard);
  });
});

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM