Locating discord.js users who possess multiple roles

Here is my code in its entirety as I have received some confusion on other forums:

I am working on creating a Discord bot that can list users with a specific role. The plan is to create an array of roles, compare user inputs to the array, and display users who have all specified roles.

For example, if Spookybot and SpookySeed both have the admin role but only Spookybot has the moderator role, typing "role admin moderator" should only display Spookybot. Any ideas on how to achieve this?

const Discord = require ('discord.js')
const { MessageEmbed } = require ('discord.js')
const { type } = require('os')
const { receiveMessageOnPort } = require('worker_threads')
const client = new Discord.Client()

client.on('ready', () => {
    console.log("Connected as " + client.user.tag)

    client.user.setActivity("you senpai!", {type: "LISTENING"})
})

client.on('message', (receivedMessage) => {
    if (receivedMessage.author == client.user) {
        return
    }
    if (receivedMessage.content.startsWith("``")) {
        processCommand(receivedMessage)
    }
})

function processCommand(receivedMessage) {
    let fullCommand = receivedMessage.content.substr(2)
    let splitCommand = fullCommand.split(" ")
    let primaryCommand = splitCommand[0]
    let argument = splitCommand.slice(1)

    if (primaryCommand == "help") {
        helpCommand(argument, receivedMessage)
    }
    else if (primaryCommand == "role") {
            roleDisplayCommand(argument, receivedMessage)
    } 
    else {
        receivedMessage.channel.send("Uknown command")
    }
}

function helpCommand(argument, receivedMessage) {
    if (arguments.length > 0) {
        receivedMessage.channel.send("It looks like you might need help with but i am still in beta sorry!")
    } else {
        receivedMessage.channel.send("Unknown command")
    }
}

function roleDisplayCommand(arguments, receivedMessage) {
    if (arguments.length > 0) {
        const roleNames = receivedMessage.content.split(" ").slice(1);

        receivedMessage.author.send(`These users have the ${roleNames.join(" ")} role(s)` )
        
        const userList = roleNames.map(roleName => receivedMessage.guild.roles.cache.find(r => r.name === roleName).members.map(m=>m.user.tag).join("\n"))
        
        const sortedList = userList.join().split(",").filter((item, index, self) => self.indexOf(item) === index);
        receivedMessage.author.send(sortedList.join("\n"))
        
    }
     else {
        receivedMessage.channel.send("Unknown command")
    }
}
client.login("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") 

Answer №1

One way to refine and narrow down your guild users list is by using a filter function:

const specificUsers = users.filter(user =>
    user.roles.has(role1.id) && user.roles.has(role2.id)
)

Answer №2

To efficiently display users with specific roles, it is advised to iterate over the roles and filter out users without those roles. The code snippet below demonstrates how this can be achieved:

function showUsersWithRoles(arguments, message) {
    ...
    const roleNamesList = message.content.split(" ").slice(1);

    message.author.send(`Here are the users with the ${roleNames.join(" ")} role(s)` );
       
    let allUsers = message.guild.members.cache;
    roleNamesList.every(
      role => {
        allUsers = allUsers.filter(user => user.roles.cache.some(r => r.name === role));
      });

    // Displaying users
    message.author.send(Array.from(allUsers.values()).join("\n"));

    // Alternative method (not tested)
    // message.author.send(Array.prototype.join.call(allUsers, "\n"));
    ...
}

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

Execute an asynchronous request using Javascript to communicate with a Spring Controller

I've created a JSP page that includes some JavaScript code: function sendData(tableID) { var table = document.getElementById(tableID); var dataArray= new Array(); for (var i = 1;i<table.rows.length; i++){ var row = table. ...

The offlinefirst.sock encountered an EPERM error

Encountering an error when attempting to run https://github.com/jakearchibald/wittr on Windows bash. Assistance in either resolving or troubleshooting this issue would be greatly appreciated: Development server listening. (PID:469) Config server liste ...

Enhance your security with Ember-simple-auth when using ember-cli-simple-auth-token

Currently, I am in the process of utilizing ember-simple-auth alongside ember-cli-simple-auth-token: "ember-cli-simple-auth-token": "^0.7.3", "ember-simple-auth": "1.0.1" Below are my configurations: ENV['simple-auth-token'] = { authoriz ...

Updates to Providers in the latest release of Angular 2

When working with angular 2.0.0-rc.1, we implemented a Provider using the new Provider method as shown in the code snippet below: var constAccessor = new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => EJDefaultValueAccessor), ...

Sending back JSON arrays containing Date data types for Google Charts

One of my challenges involves using a 'Timelines' chart from Google Charts, which requires a JavaScript Date type when populating data. Here is my initial code snippet: var container = document.getElementById('divChart1'); var chart = ...

Simplified React conditional rendering made easy

Currently, I am utilizing React 16 with Material-Ui components. In my root component, I have a requirement to load a tab and a view conditionally based on a property. Although I have managed to implement this functionality, the code appears quite messy a ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

Looping through required fields in jQuery based on a CSS class

Is there a way to loop through required fields marked with <input class="required">? Currently, only the first input in the loop is being evaluated. How can I traverse the DOM using a loop to check all input boxes? Thank you for your help. While I ...

Exploring plyr and vue.js: utilizing a computed property to fetch video duration

I am currently attempting to load content dynamically based on the duration of a video being displayed. However, I am encountering issues when trying to access the duration property. Could this problem be related to the timing of plyr's appearance wit ...

When the visitor is browsing a particular page and comes across a div element, carry out a specific action

I am trying to determine if I am currently on a specific page and, if so, check if a certain div exists in that page. Here is what I know: To check if a specific page exists, I can use the code if('http://'+location.hostname+location.pathname+& ...

Tips for storing data from a table using a button

I have implemented a data table to display information from a database. I am looking for a way to save user information whenever they export data in Excel, CSV, or PDF format from the table. I have already created a function to handle saving user data, but ...

The function estimatedDocumentCount() actually returns an object rather than a numerical value

I am currently working on a feature in my web application where I want to display the number of documents stored in my MongoDB database whenever a user visits the homepage. To achieve this, I have outlined the implementation process in the following diagra ...

Aligning a div with absolute positioning vertically

There are two elements positioned side by side: an input field and a div. The div is absolutely positioned inside a relative element and placed to the right of the input. The input field has a fixed height, while the height of the div depends on its conte ...

Creating a Command Line Interface (CLI) application in JavaScript for the browser: A guide to simulating blocking I/O

Developing a CLI application becomes quite simple with a blocking I/O API like PrintLn / ReadLn, making the process smooth and efficient. However, the challenge arises when trying to create a terminal application that runs on a browser using JS. In this s ...

I'm having trouble understanding how to utilize startAt and endAt in Firebase version 9

Trying to implement geo querying in my firestore db with the new version of firebase has been challenging. The code examples provided in the documentation reference an older version, making it difficult for me to understand how to use ".startAt" and ".endA ...

Conceal the child elements underneath a selected element using jQuery

I am currently working on an order form within a website and the HTML code is structured as below: <table class="variations"> <div class="tawcvs-swatches" data-attribute_name="attribute_pa_t-shirt- one-color"> <span class="swat ...

Elements that are added dynamically do not contain any space between each other

I have a markup template that looks like this. <template id="unsequenced-template"> <button type="button" class="btn btn-primary railcar"></button> </template> Then, I use the following JavaScript ...

Change the date string to year, month, and day

When using Ajax's getResponseHeader("Last-Modified"), it returns a date string with the format displayed below: Thu Oct 13 2016 13:05:17 GMT+0200 (Paris, Madrid, sommartid) I am wondering if it is achievable in javascript to extract the year, month, ...

What are some strategies for navigating the constraint of having multiple root elements in Vue.js?

Seeking assistance from the experts here to solve this particular issue. I have a dataset that looks like this: [ { title: 'Header', children: [ { title: 'Paragraph', children: [], }, ], }, ...

Reorganizing an array using a custom prioritized list

Is it possible to sort an array but override precedence for certain words by placing them at the end using a place_last_lookup array? input_place_last_lookup = ["not","in"]; input_array = [ "good", "in", "all&qu ...