Is there a way to prevent the leaderboard from resetting each time I restart my client?

Is it possible to prevent the leaderboard from resetting every time I restart my client? You can see an example here: https://i.stack.imgur.com/2nEPw.png

Please disregard the "undefined" error, I will correct it.

In the current setup, the leaderboard only displays users who have interacted with the bot after its restart. Once they use a command, their ranking is reflected on the leaderboard as shown in this image:

https://i.stack.imgur.com/5oiMe.png

This is the code I am using:

    let Data = await UserModel.find({});
    let Members = [];
    for (let obj of Data) {
      if (
        message.guild?.members.cache.map((member) => member.id).includes(obj.ID)
      )
        Members.push(obj);
    }
    const Embed = new MessageEmbed()
      .setTitle(`${message.guild?.name}'s Leaderboard`)
      .setFooter({
        text: `You aren't ranked yet!`,
        iconURL: message.author.displayAvatarURL({ dynamic: true }),
      });
    Members = Members.sort(function (b, a) {
      return a.Money - b.Money;
    });
    Members = Members.filter(function BigEnough(value) {
      return value.Money > 0;
    });
    let pos = 0;
    for (let obj of Members) {
      pos++;
      if (obj.ID === message.author.id) {
        Embed.setFooter({
          text: `You are ranked ${pos} in the leaderboard!`,
          iconURL: message.author.displayAvatarURL({ dynamic: true }),
        });
      }
    }

    Members = Members.slice(0, 10);
    let desc: any;
    for (let i = 0; i < Members.length; i++) {
      let User = message.guild?.members.cache.get(Members[i].ID);
      if (!User) return;
      let Bal = Members[i].Money;
      desc += `${i + 1}. ${User.user.tag} - $${Math.round(Bal)}\n`;
    }
    Embed.setDescription(desc);
    Embed.setColor("RED");
    message.reply({ embeds: [Embed] });

Currently, the code seems to be pulling cached user data only. Is there a way to fetch all the users in the server?

Answer №1

Ensure you retrieve all the members of the guild initially in order to populate the cache with them.

You can achieve this by utilizing the method: guild.members.fetch(); or adjusting your client's default caching settings.

message.guild.members.fetch(members => {
  let membersArray = members.array();
  for(var guildMemberId in membersArray) {
    let member = membersArray[guildMemberId];
    //Implement necessary logic with each member here.
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to employ the inequality operator while querying a collection in AngularFire

I'm facing a challenge with pulling a collection from Firebase that is not linked to the user. While I've managed to query the user's collection successfully, I am struggling to retrieve the collection that does not belong to the user using ...

Guide to transmitting a "token" to an "API" using "React"

As a novice developer, I am facing a challenge. When users log in to our website, a JWT is created. I need to then pass this token to the API on button click. If the backend call is successful, the API response should be displayed. If not, it should show ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

Issues with command functionality within the VS Code integrated terminal (Bash) causing disruptions

When using Visual Studio Code's integrated terminal with bash as the shell, I have noticed that commands like ng and tsc are not recognized. Can anyone shed some light on why this might be happening? ...

The error TS2304 occurs when the e2e tsconfig types cannot find the name 'browser'

I am facing challenges while setting up a sample angular project with a basic webdriverio end-to-end test, encountering some compilation errors in my e2e test. Setting up tsconfig The project is configured with the following key files: e2e / test / [e2e t ...

Neglectful TypeScript null checks overlooking array.length verification

When TypeScript is compiled with strict null checks, the code snippet below does not pass type checking even though it appears to be correct: const arr: number[] = [1, 2, 3] const f = (n: number) => { } while (arr.length) { f(arr.pop()) } The comp ...

Using Typescript to assign a new class instance to an object property

Recently, I crafted a Class that defines the properties of an element: export class ElementProperties { constructor( public value: string, public adminConsentRequired: boolean, public displayString?: string, public desc ...

A guide to testing the mui Modal onClose method

When using material UI (mui), the Modal component includes an onClose property, which triggers a callback when the component requests to be closed. This allows users to close the modal by clicking outside of its area. <Modal open={open} onCl ...

Extracting data from a JSON object using Angular 2

I need advice on the most efficient way to handle JSON within my angular2 application. The JSON data I am working with includes: { "rightUpperLogoId": { "id": 100000, "value": "" }, "navbarBackgroundColorIdCss": { "id" ...

Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS. My goal is to integrate this ...

Can a form component be recycled through the use of inheritance?

Greetings to the Stackoverflow Community, As I delve into this question, I realize that examples on this topic are scarce. Before diving into specifics, let me outline my strategy. I currently have three pages with numerous FormGroups that overlap signif ...

I am encountering an issue trying to create a Docker image featuring TypeScript

I am facing an issue while trying to build a docker image using the docker build . command in my next.js app An error is being encountered Error: buildx failed with: error: failed to solve: process "/bin/sh -c yarn run build" did not complete su ...

Improved method for linking two enums with similar appearances

Currently, I use two enums as shown: enum Tab { Approved = "Approved", Pending = "Pending", Sold = "Sold", } enum ProductStatus { Approved = "Approved", Pending = "Pending", Sold = "Sold&q ...

Tips for querying enum data type using GraphQL

I am having trouble querying an enum from GraphQL in my Nest.js with GraphQL project. I keep getting an error message saying: "Enum 'TraitReportType' cannot represent value: 'EMBEDDED'". I have tried using type:EMBEEDED, but it did not ...

What is the best way to initialize a discriminated union in TypeScript using a given type?

Looking at the discriminated union named MyUnion, the aim is to invoke a function called createMyUnionObject using one of the specified types within MyUnion. Additionally, a suitable value for the value must be provided with the correct type. type MyUnion ...

An issue arises when using enums in TypeScript

Let's analyze this demonstration. Initially, an enum is created as follows: enum myEnum { a = 'a', b = 'b' } The next step involves creating a similar enum but with the addition of one more numeric value! This alteration is c ...

Merge information from two sources utilizing concatMap

I am encountering an issue where I need to extract a specific value from the data obtained from my first service in order to pass it on to the second service. Angular seems to have trouble with 'firstserviceResultsJson.indSsn'. How can I successf ...

Understanding how to infer the type of a function when it is passed as an argument

Looking at the images below, I am facing an issue with my function that accepts options in the form of an object where one of the arguments is a transform function. The problem is that while the type of the response argument is correctly inferred for the e ...

What is the proper way to input a Response object retrieved from a fetch request?

I am currently handling parallel requests for multiple fetches and I would like to define results as an array of response objects instead of just a general array of type any. However, I am uncertain about how to accomplish this. I attempted to research "ho ...

Issues encountered while attempting to update data in angular2-datatable

Once the datatable has been rendered, I am facing an issue where I cannot update the data. I'm utilizing angular2-datatable. In my appcomponent.html file: If I try to update 'data2' in my appcomponent.ts file as shown below: this.httpserv ...