Check for bot presence in Discord.js, and continuously loop through the mentions

Currently, I have this command that is functioning well. However, I am looking to customize it so that it only selects users and excludes bots. The purpose of the command is to randomly choose users and then mention them in a message.


let number = args[0];

if(isNaN(number)){
 return message.channel.send(`The specified amount is either not a number or no amount was provided. Please use: !randommention (number)`);
}else{

let ret = "";


for (i = 0; i < number; i++) {
    let randomName = message.guild.members.cache.random().user;
    //My unsuccessful attempt at blocking bot mentions
    if(randomName == message.member.user.bot){
      repeat(randomName)}
    ret += `\n${randomName}`
  }
  

  message.channel.send(`**User(s) Selected:** ${ret}`)

}}

I experimented with a workaround using a "repeat" function, which unfortunately didn't yield the desired result. Any suggestions on how to effectively exclude bots entirely?

Answer №1

Believe me, while loops can be quite handy at times.
Give this a shot in your situation:

let i = 0;
while(i < number){
    let randomMember = message.guild.members.cache.random();
    //You don't actually need the .user
    if(randomMember.bot){  //Checks if the user is a bot
        continue;
        //Note: If it's a bot, the count won't increase
        //So the total count will remain as desired
        //It may create an infinite loop if there are fewer members in the guild than selected
    } else { //Better safe than sorry
        i++; //Moves on only if the user is not a bot
        ret += `\n${randomMember}`;
    }
}
message.channel.send(`**User(s) Selected:** ${ret}`);

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

Using AngularJS $resource for making JSONP requests

I have defined two services in AngularJS that should both return JSONP for a cross domain request. Service A: angular.module('ServiceA', ['ngResource']). factory('A', function ($resource) { return $resource('url/ ...

App Script encounters a service error while attempting to transfer data between spreadsheets

My goal is to transfer data from one spreadsheet to another. The code should ideally retrieve data from one spreadsheet, save it into a 2D array, and then print all the data into another spreadsheet. However, I am encountering an error during the printing ...

Tips for Implementing Conditional Statements in SoundCloud API JavaScript Functions

Currently, I am attempting to retrieve a specific group of users by utilizing the SC.get() method within the SoundCloud API. My goal is to filter the resulting user set based on their follower_count falling between a range that I set. This follower_count d ...

Enable parents to make all children draggable, so that when a child is clicked, it becomes draggable and sortable

I am trying to achieve the functionality where I can make all child elements draggable when their parent is clicked. However, with my current code, I am only able to drag individual child elements and unable to drag the entire list along with its children. ...

What could be the reason my homing missile algorithm is not functioning properly?

The code I'm currently using for my projectile was heavily inspired by an answer I found on a game development forum, but it's not working as expected. Most of the time, the initial direction of the projectile is perpendicular to the target inste ...

Using JQuery to visually enhance the menu selection by displaying an image and altering the background color upon hovering

Hello fellow JQuery/Javascript beginners! I recently put together a menu and wanted to add some interactive elements. Specifically, I want the background color to change when a user hovers over an item (simple enough with CSS), but I also want to include a ...

typescript: Imported modules in typescript are not functioning

I'm facing an issue where I installed the 'web-request' module but unable to get it working properly. Here is my code: npm install web-request After installation, I imported and used it in my class: import * as WebRequest from 'web-r ...

Instructions on displaying a pop-up message upon clicking the edit button with the use of javascript

How can I display a popup message box when the edit button is clicked on my PHP page? I want to confirm before passing data to the edit page, but currently, the data is being sent without displaying any message. Any suggestions on how to fix this issue w ...

Code to clear checkbox selection in DataGrid MUI?

I am facing an issue with my delete function. Even after deleting an item, it remains selected and does not unselect until I manually do so. Is there a way to remove selection through code? I attempted the suggested DataGrid.UnselectAllCells() method but ...

The strategic manipulation of numerous elements within a group

I am interested in finding out the safe limits for DOM manipulation using jQuery to avoid freezing the browser. What are the most efficient methods for mass manipulation of the DOM? Typically, I may need to handle lists containing up to 40k li elements. ...

Adjustable diagonal line within a container using CSS styling

Seeking assistance with a rectangular div that can have its diagonal length adjusted using JavaScript. I am looking to add a diagonal line to label the diagonal length when it is increased or decreased using the +/- buttons. I require the line to resize a ...

What might be causing my enzyme test for React to fail when calling document.getElementById()?

I am currently facing an issue while trying to render a Snapshot test for a nested React component. The problem lies with the test code failing to handle a document.getElementById() request within the component's relevant code section: componentDid ...

The style of declaring functions in ECMA6 is incompatible

When parent is a jQuery element and I use the following code: parent.change(function (e) { e.preventDefault(); console.log($(this)); console.log($(this).data('tab')); }); It works perfectly fine. However, when I try using this code: ...

Guide to implementing event handling with JavaScript on an HTML form webpage

On my HTML page, I have a PHP extension file named 'welcome.php'. Within this page, there is a button labeled "baggage.php" that, when clicked, opens another page. On this new page, I have created dropdown menus for 'From' and 'To& ...

Distinguishing Response Headers in XMLHttpRequest and jQuery AJAX FunctionUniqueness:

Hello, I'm facing an issue that is not a duplicate. Here is the code snippet: var data = {'userId': window.cookie.get('userId'), 'sessionId': window.cookie.get('sessionId')} $.post(window.DbUrl + '/t ...

Combining the powers of Socket.io, node.js, and smart routing

How can I pass an already connected socket from socket.io to the controller when making a post request from the application to the server, using Vue and a Node server with Socket.io? I attempted declaring global.io = io, but the socket remains undefined. ...

Printing the string only if the value is absent or null

I am currently working on a project that involves scraping a name database and displaying the values based on certain conditions defined in the code. However, when an element in the data is null or not present, I want to display "-" instead of showing "n ...

Update the array in state by adding a new element using setState

How can I add a new element to an array using setState? Consider the following data: this.state = { items : [ { "id" : "324", "parent" : "qqqq", "text" : "Simple root node" }, { "id" : "24", "parent" : "dwdw", "text" : "Root node" }, { "id" ...

Using jQuery to remove all inline styles except for a specific one

Just a quick inquiry: Our Content Management System (CMS) utilizes CKEditor for clients to modify their websites. The front-end styles include the use of a pre tag, which we have customized to our desired appearance. However, when their team members copy a ...

Inheriting CSS Styles in a JavaScript Toolbar Plugin

Recently, I created a javascript plugin that can be activated by clicking a button on my browser's toolbar. While it functions perfectly on certain websites, it appears unappealing on others due to inheriting CSS styles from the site itself. Are the ...