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

Defining the type of the createAction() function in TypeScript within the context of Redux Toolkit

Lately, I have been delving into the redux-toolkit library but I am struggling with understanding the type declaration of the createAction function as demonstrated below. The createAction function returns a PayloadActionCreator which includes a generic of ...

Here's a method to extract dates from today to the next 15 days and exclude weekends -Saturday and Sunday

Is there a way to generate an array of dates starting from today and spanning the next 15 days, excluding Saturdays and Sundays? For example, if today is 4/5/22, the desired array would look like ['4/5/22', '5/5/22', '6/5/22' ...

What is the best way to destructure a blend of React props and my own custom props in my code?

I have a requirement to develop a custom React component that serves as a wrapper for the Route component in order to create secure routes. The challenge I am facing is how to access the element property, which is typically specified in the <Route> e ...

The ngOnInit function is not triggered upon instantiation of an Injectable class

What could be causing the ngOnInit() method not to be called upon resolution of an Injectable class? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable ...

Error with Typescript types when using Styled Components

After successfully setting up styled-components in react-native, I encountered an issue while trying to use it in a simple example with react-native-web: import * as React from 'react'; import styled from 'styled-components'; export d ...

Error in Angular 4: Undefined property 'replace' causing trouble

I've been trying to use the .replace() JavaScript function in Angular 4 to remove certain characters from a string. Here is the code snippet from my component: @Component({...}) export class SomeComponent implements OnInit { routerUrl: string = &apo ...

Displaying a TypeScript-enabled antd tree component in a React application does not show any information

I attempted to convert the Tree example from antd to utilize TypeScript, however, the child-render function does not seem to return anything. The commented row renders when I remove the comment. The RenderTreeNodes function is executed for each element in ...

Error encountered when upgrading to Material-UI v5 rc.0 with typescript

After updating my material-ui to version v5-rc.0, I decided to implement styled-components. However, as I was working on my Component.styles.ts file, I encountered an error: The inferred type of 'StyledStepper' cannot be named without a referen ...

Tips for distinguishing a mapped type using Pick from the original type when every property is optional

I am working with a custom type called ColumnSetting, which is a subset of another type called Column. The original Column type has most properties listed as optional: type ColumnSetting = Pick<Column, 'colId' | 'width' | 'sort ...

The name property of event.currentTarget is now being returned as currentTarget

I am facing an issue with my handleChange function in typescript. When I try to retrieve the name attribute from a text field and log it, it returns 'currentTarget' instead of the assigned name. Additionally, the value is showing up as undefined. ...

Unable to create resource in nestjs due to typeScript compatibility issue

Encountered an Error: TypeError: Cannot access 'properties' property of undefined Failed to execute command: node @nestjs/schematics:resource --name=post --no-dry-run --language="ts" --sourceRoot="src" --spec Attempts made ...

The data type 'string | undefined' cannot be assigned to the data type 'string' when working with .env variables

Trying to integrate next-auth into my nextjs-13 application, I encountered an error when attempting to use .env variables in the [...nextauth]/route.ts: Type 'string | undefined' is not assignable to type 'string'. https://i.stack.im ...

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

"Unsuccessful API request leads to empty ngFor loop due to ngIf condition not being

I have been struggling to display the fetched data in my Angular 6 project. I have tried using ngIf and ngFor but nothing seems to work. My goal is to show data from movies on the HTML page, but for some reason, the data appears to be empty. Despite tryin ...

Fixing prop passing issues in Vue.js components to prevent errors

My Vue-cli install with TypeScript is set up to render JSX using a boilerplate. However, I am facing an issue when trying to pass a property to the HelloWorld component. Here's what my code looks like: export default Vue.extend({ name: 'App&apo ...

[deactivated]: Modify a property's value using a different component

One of the requirements for my button is that it should be disabled whenever the callToActionBtn property is true. match-component.html <button [disabled]="callToActionBtn" (click)="sendTask()>Send</button> match-component.ts public callToA ...

Navigating Mixins in Ember CLI Typescript

I'm curious about the best approach for handling mixins in a typed Ember application. While removing mixins from the application is ideal, many addons do not yet support TypeScript. So, how can we effectively utilize Ember Simple Auth's applicati ...

Expanding the Mui Typescript breakpoints within a TypeScript environment

Encountering a typescript error when attempting to utilize custom names for breakpoint values: Type '{ mobile: number; tablet: number; desktop: number;}' is not compatible with type '{ xs: number; sm: number; md: number; lg: number; xl: numb ...

Tips for efficiently parsing multiple JSON files in Typescript while maintaining clean and concise code

Currently, my app is designed to read multiple Json files in Typescript and populate select boxes. However, I am striving to avoid repeating code with the wet (write everything twice) principle and keep things dry (don't repeat yourself). Initially, I ...