Obtain a compilation of users who have expressed their reaction to a message with a specific emoji on Discord

Check out this Discord.js code snippet for a Discord bot:

client.channels.fetch('channelID here').then(function (channel) {
 channel.messages.fetch('messageID here').then(function (message) {
  console.log(message.reactions.cache.get('EmojiID here').users);
 });
});

When executed, the console displays the following information:

ReactionUserManager {
  cacheType: [class Collection extends Collection],
  cache: Collection [Map] {},
  reaction: MessageReaction {
    message: Message {
      channel: [TextChannel],
      deleted: false,
      id: 'MessageID here',
      type: 'DEFAULT',
      system: false,
      content: 'What role do you want?\n' +
        'React with:\n' +
        '<:Red:870224025811558450>  for <@&870162738561814578> \n' +
        '<:Blue:870224213976444959> for <@&870162842983206922> \n' +
        '<:Yellow:870224106061172776> for <@&870162885412810773>\n' +
        'You will be assigned the role corresponding to your most recent reaction.\n' +
        'Unreact to remove the role.',
      author: [User],
      pinned: false,
      tts: false,
      nonce: null,
      embeds: [],
      attachments: Collection [Map] {},
      createdTimestamp: 1627548937713,
      editedTimestamp: 1627617831107,
      reactions: [ReactionManager],
      mentions: [MessageMentions],
      webhookID: null,
      application: null,
      activity: null,
      _edits: [],
      flags: [MessageFlags],
      reference: null
    },
    me: true,
    users: [Circular],
    _emoji: ReactionEmoji {
      animated: undefined,
      name: 'Red',
      id: 'EmojiID here',
      deleted: false,
      reaction: [Circular]
    },
    count: 2
  }
}

In the output, count: 2 is shown. To retrieve the list of objects associated with these two users, how can this be accomplished?

Answer №1

You were very close to the solution. The ReactionUserManager is a manager that includes a cache property which returns a collection of User objects.

If you want to fetch the users as well, you can follow this approach:

client.channels.fetch('channelID').then(function (channel) {
 channel.messages.fetch('messageID').then(function (message) {
  const reaction = message.reactions.cache.get('EmojiID')
  reaction.users.fetch().then(function (users) {
    console.log(users)
  })
 })
})

Using async-await in an async function can make the code more readable like this:

const channel = await client.channels.fetch('channelID')
const message = await channel.messages.fetch('messageID')
const reaction = message.reactions.cache.get('EmojiID')
const users = await reaction.users.fetch()

console.log(users)

// For example, you can add a role to each user
users.each(async (user) => {
  // Retrieve the member object as users do not have roles
  const member = await message.guild.members.fetch(user.id)
  member.roles.add('ROLE ID')
})

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 a Dynamic Dropdown Menu in Rails 4

I am attempting to create a dynamic selection menu following this tutorial; however, I am encountering issues as the select statement does not seem to be updating. Below is the code snippet I currently have: #characters_controller.rb def new ...

Creating an alert pop-up that displays text based on the prompt input type: A step-by-step guide

I'm a new to Javascript and I'm trying out some basic scripts. My objective is to display a prompt message (1.) asking for a name, then show an alert (2.) based on the input from the prompt. If the input is a valid name (a string), then the alert ...

Dealing with a Nodejs/Express and Angular project - Handling the 404 error

Recently, I decided to dive into learning the MEAN stack and thought it would be a great idea to test my skills by building an application. My goal was simple: display a static variable ('hello') using Angular in the HTML. However, I ran into an ...

Seamlessly adaptive HTML5 video playback

Has anyone figured out how to make an HTML5 video in an absolutely positioned <video> element resize to fit the window width and height without ever getting cropped? Many solutions I've come across rely on using the <iframe> tag, which is ...

Guide on implementing factory updates to the display

I am attempting to update a reference within my factory in an asynchronous fashion, but I am not seeing the changes reflected in my view. View <div ng-repeat="Message in Current.Messages">{{Message.text}}</div> Controller angular.module(&ap ...

Having trouble getting Vue.js data to show up on the screen. I'm attempting to show a list of todos, but all that

I'm currently working on my App.vue file where I have set up the data for a todo list. However, despite creating an array of todos and attempting to display them, nothing is showing up on the screen. I'm at a standstill and could really use some ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

Adjust the dimensions of an element using Protractor

When using the getSize method, I am able to determine the size of an element but I am struggling to understand how to change its height. To provide some additional context, my goal is to verify if a user can resize a textarea element. Should I simply adju ...

Establishing updated file path for resources in JavaScript based on environment

I'm currently facing an issue with my external Javascript file that uses the getScript() function to execute another JS file. Both files are located on static.mydomain.com, as I am trying to set up a Content Delivery Network (CDN) for the first time. ...

What are the steps to designing a unique JSON data format?

When working with a JSON data structure containing 100 objects, the output will resemble the following: [{ "Value": "Sens1_001", "Parent": Null, "Child": { "Value": "Sens2_068", "Parent":"Sens1_001", "Child" : { ...

Changing a file object into an image object in AngularJS

Can a file object be converted to an image object? I am in need of the width and height from the file (which is an image). Here is my code: view: <button id="image_file" class="md-button md-raised md-primary" type="file" ngf-select="uploadFile($file ...

Preserve the custom hook's return value in the component's state

I am currently facing a challenge in saving a value obtained from a custom hook, which fetches data from the server, into the state of a functional component using useState. This is necessary because I anticipate changes to this value, requiring a rerender ...

Combine two elements in an array

I am faced with a challenge in binding values from an Array. My goal is to display two values in a row, then the next two values in the following row, and so on. Unfortunately, I have been unable to achieve this using *ngFor. Any assistance would be greatl ...

Can you explain the significance of the regular expression in a dojo configuration file named dj

As I was working on developing dojo application modules, I came across a regular expression in tutorials. var pathRegex = new RegExp(/\/[^\/]+$/); var locationPath = location.pathname.replace(pathRegex, ''); var dojoConfig = { asyn ...

Is employing setTimeout a legitimate technique for circumventing a stack overflow issue when implementing callbacks?

Let's imagine a scenario where I deliberately create a complex sequence of callbacks: function handleInput(callback) { ... } function fetchData(url, callback) { ... } function processResponse(callback) { .... } function updateDatabase ...

Comparing the length of an array to whether the length of the array is greater than

What distinguishes checking an array's length as a truthy value from verifying that it is greater than zero? In simple terms, is there any advantage in utilizing one of these conditions over the other: var arr = [1,2,3]; if (arr.length) { } if (arr ...

Unable to adjust metadata titles while utilizing the 'use client' function in Next.js

I have a /demo route in my Next.js 13 application, and it is using the App Router. However, I am facing an issue with changing the title of the page (currently displaying as localhost:3000/demo). The code snippet for this issue is shown below: /demo/page ...

I am unsure about implementing the life cycle in Svelte.js

Unknown Territory I am not well-versed in front-end development. Desire to Achieve I aim to utilize the lifecycle method with SvelteJS. Error Alert An error has occurred and the lifecycle method is inaccessible: ERROR in ./node_modules/svelte/index.m ...

Executing multiple nested `getJSON` requests in a synchronous manner using jQuery

I am facing an issue with my code that connects to an API using $.getJSON. It retrieves JSON data and then iterates three times through a for loop because the data has 3 objects. During each of these iterations, it makes another $.getJSON call to fetch spe ...

Implement using a variable as a key for an object in a reducer function

I am facing an issue with constructing an object. The string, named "SKU" in this scenario is being passed through action as action.name. Although I have all the necessary data in the reducer function, I need to dynamically replace the hardcoded SKU with ...