Achieving an accurate tally of Discord members using discord.js

I am working on creating a command for my Discord bot that allows users to check in within a specific time frame and receive a count of how many people are present, regardless of the maximum capacity. Here is the code I have so far:

case "report":
    const filter = m => m.content.startsWith('here');
    
    message.channel.sendMessage("Report your accountability!");
    message.channel.awaitMessages(filter, { 
        max: 200,
        time: 30000,
        errors: ['time'] 
    })
    .then(collected => {
        message.channel.sendMessage(`Accountability is ${collected.size} of ${message.guild.members.size}, present or accounted for.`);
    });
    break;
}

I'm encountering some issues with this code despite it appearing to work initially in my test channel after sending the first message. Any insights or clarifications would be greatly appreciated! Thank you.

Answer №1

It seems that the issue at hand is your expectation for .then to be triggered once the time limit is reached. In actuality, reaching the time limit is considered an "error" according to the .awaitMessages Example:

...
// Errors: ['time'] treats hitting the time limit as an error
channel.awaitMessages(filter, { max: 4, time: 60000, errors: ['time'] })
    .then(collected => console.log(collected.size))
    .catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`));

To have your code function as intended, simply add a .catch statement following your channel.awaitMessages call like so:

message.channel.awaitMessages(filter, { 
    max: 200,
    time: 30000,
    errors: ['time'] 
})
.then(collected => {
    message.channel.send(`Accountability is ${collected.size} of ${message.guild.members.size}, present or accounted for.`);
})
// The .catch will handle errors - including time's up being an error
.catch(collected => {
    message.channel.send(`Accountability is ${collected.size} of ${message.guild.members.size}, present or accounted for.`);
});

Please Note: As pointed out by @Splinxyy in the comments, it's advisable to use .send instead of the outdated .sendMessage function.

Revision: You mentioned in the comments your interest in counting only unique users who send 'here' in the channel. One approach would involve storing user ids in an array and checking if the id has already been counted using a filter array:

let uidHolder = [];
const filter = m => {
    let id = m.author.id;
    if (uidHolder.includes(id) || !m.content.startsWith('here'))
        return false;
    else {
        uidHolder.push(id);
        return true;
    }
};

If you prefer another method, you could manipulate the collected variable from .then / .catch. Nevertheless, utilizing the filter function may prove simpler.

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

Creating dynamic buttons and textboxes on a JSP page

<form:form action="approveAccount.html" method="GET"> <input type="submit" value="approvAll"/> <p>List of Pending Accounts for Approval</p> <c:forEach items="${accountIdList}" var="val"> <li>${val}</li> ...

Tips for transferring the content of a variable to a handlebars block

Currently, I am grappling with HTML code that involves handlebars templates to store internal variables. While I may not be an expert in handlebars, I am trying my best to navigate through it. The crux of my issue lies in the need to access a lengthy list ...

Arranging by upcoming birthday dates

Creating a birthday reminder app has been my latest project, where I store names and birthdays in JSON format. My goal is to display the names sorted based on whose birthday is approaching next. Initially, I considered calculating the time until each pers ...

Display an error message when the button is clicked and the input field is left empty in a Vue 3 script setup

Hello, I am currently exploring Vue 3 and embarking on a new Vue 3 project venture. However, I seem to be encountering a challenge when it comes to displaying an error message if the button is clicked while the input field remains empty in my Vue 3 script ...

Is it possible to continuously update a Google line chart by programmatically adding rows at specific intervals using an AJAX call

Is there a way to dynamically add rows to the Google line chart each time data is retrieved via an AJAX call at set intervals? This is the existing code: google.charts.load('current', {'packages':['line']}); google.charts. ...

Javascript Google Maps API is not working properly when trying to load the Gmap via a Json

Trying to display a map using Gmaps and Jquery Ajax through JSON, but encountering difficulty in getting the map to appear on the page. The correct coordinates are being retrieved as confirmed by testing in the console. Puzzled by why it's not showin ...

Creating concise one-liner If statements with Handlebars: a simple guide

I am seeking clarification on the correct syntax for this code snippet: <li class="nav-item {{# if undefined !== user}} hidden {{/if}}"> My goal is to add the class name hidden only if the user variable exists. When I try implementing this, it res ...

What is the method for establishing session or cookie in an HTTPS request to a specific URL?

When making an HTTPS GET request in Node.js to a specific URL, it is necessary to include the session cookie. In this case, I already have the value of the cookie that needs to be sent. var URL = require('url-parse'); var appurl = "https://test ...

Is it possible to include a concealed bounding box in a three.js environment?

I need to expand the clickable area for an object by detecting a click on its bounding box instead of just the object itself. Here is how I load the object: var loader2 = new THREE.ObjectLoader(); loader2.load( "models/Platform/Platform.json", ...

JavaScript - Matching overlapping time intervals

Struggling to develop a custom filter using Javascript, I aim to determine if two time ranges in millisecond getTime() format match. The first time range is retrieved from an object while the second comes from user input for filtering. Currently, my code c ...

Move tables by dragging and dropping them into place

Currently, I am on the lookout for a drag and drop plugin that works with jQuery, Angular, or JavaScript to help me create dynamic tables. Specifically, I need a plugin that allows me to add new tables through drag and drop functionality. While I have com ...

Pause jQuery at the conclusion and head back to the beginning

As a beginner in the world of jQuery, I am eager to create a slider for my website. My goal is to design a slideshow that can loop infinitely with simplicity. Should I manually count the number of <li> elements or images, calculate their width, and ...

Is the straightforward AJAX functionality I've implemented in my personal library enough?

Here's the specific code we're looking at: ajax = function(url, cb) { xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('MicrosoftXMLHTTP'); xhr.onreadystatechange = function() { ...

Is it possible to set the state property in React js using the axios response?

After receiving data from axios, I am trying to store the response in a state value for rendering it in html. However, even though response.results displays the data when printed out, setting response.results in setState() results in an empty value. Here ...

What is the best way to navigate to a different page, such as Google, using Node.js?

I need to retrieve a number to store in a short variable, and then search the database for a corresponding shortUrl associated with that number. If a match is found, I want the response to be the full URL, such as www.google.com. For example, if a user ty ...

Converting JSON data to CSV format with JavaScript

I have been attempting to convert a JSON object to CSV using JavaScript, but the results are not as expected. UPDATE: The JSON object is stored in a variable, and every time I try to access 'list', it returns as undefined. Is there a way to acce ...

What is the best way to create a function library that works seamlessly across all of my Vue.js components?

I am currently in the process of developing a financial application using Vue.js and Vuetify. As part of my project, I have created several component files such as Dashboard.vue Cashflow.vue NetWorth.vue stores.js <- Vue Vuex Throughout my development ...

Assigning an object to a field within an array using Vega-lite

I am currently working on an interactive data dashboard with a dataset stored in an array of objects. I want to enhance the functionality by displaying data from one object at a time instead of all objects collectively, which is already functioning well. T ...

Importing JSON data from a URL to display in an HTML table

Looking to utilize the Untappd API for a beer menu project, I've encountered an issue. The goal is to showcase the JSON data received from the server and organize it into an HTML table. Despite successfully importing data from a local list.json file ...

Error encountered in Node/Express application: EJS partials used with Angular, causing Uncaught ReferenceError: angular is not defined

I seem to be missing something important here as I attempt to incorporate ejs partials into a single-page Angular app. Every time I try, I encounter an Uncaught ReferenceError: angular is not defined in my partial. It seems like using ejs partials instead ...