Discord.js – Get users who reacted to old messages

Discord.js – Get users who reacted to old messages

So, you want to get a list (or select a random one) of the users who reacted to messages PRIOR to your bot restarting. That can be done, and I am here showing you the code needed to do so. The code I am about to show you has two possibilities; You can select to get a list of all users who reacted, or you can have a random user sent back.

const filter = m => m.author.id === message.author.id; //This is the filter we use for awaitMessages, basically: It checks that the author of the collected message is correct
message.channel.send(`What message should I check?`); //Prompts what message to check
const msgId = (await message.channel.awaitMessages(filter, { max: 1 })).first().content; //Collects the messageID into the const msgId (You should input the correct ID after the prompt
const fetchMsg = await message.channel.messages.fetch(msgId); //Fetches the message equal to the ID from above
let reactions = fetchMsg.reactions.cache.find(emoji => emoji.emoji.name == '✅'); //Collects the reactions of the message, where reaction = :white_check_mark: (✅)
fetchMsg.reactions.cache.map(async (reaction) => { //Maps out every reaction made on the collected message
    let usersThatReacted = []; //Initiates usersThatReacted as an array
    if (reaction.emoji.name !== "✅") return; //If the reaction checked isn't equal to ✅, return
    let reactedUsers = await reaction.users.fetch(); //Fetches the users that reacted with the ✅ on the collected message
    reactedUsers.map((user) => { //Maps out every user that reacted with ✅
        usersThatReacted.push(`**${user.username}#${user.discriminator}**`); //Pushes each user into the array with formatting ** (bold text) username#discriminator
    });
    let users = usersThatReacted.join('-').trim(); //Joins all items in the array with a hyphen 
    let randomuser = Math.floor(Math.random()*usersThatReacted.length); //Selects a random number, based on the length of the above array
    message.channel.send(`Randomly selected user:\n${usersThatReacted[randomuser]}`); //Shows the randomly selected user that reacted. If you want to show all users, simply exchange: ${usersThatReacted[randomuser]} with ${users} !!
});

This is a short snippet with the comments all in the code, describing what each line does.
As always, if you have questions about any code leave it as a comment below or join my Discord server to ask questions there.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *