Search code examples
javascriptdiscord.jsfetchmessage

Trying to fetch 5 messages and then react to them - discord.js


I am trying to get 5 previous messages from a channel and then react to them with discord.js

message.channel.messages.fetch(channelID).then(channel => {
            channel.messages.fetch({limit : 5}).then(message => {
                message.react("✅");
            })
        })

The error I am getting: UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'messages' of undefined


Solution

  • You have two issues within your code (One of them that some seemed to ignore here).

    Your first error comes within the following line, stating:

    message.channel.messages.fetch(channelID).then(channel => {
    

    The Channel#messages#fetch() method does not return a Channel object, but a message object. Since you're trying to fetch messages from a channel object, you should be fetching a channel rather than a message. Try replacing your line with the following:

    client.channels.fetch(channelID).then(channel => { ... }
    

    The second issue is that when you're fetching more than one message in Discord.js, the method returns a collection of objects rather than an object. Unlike a regular single message object, a collection of message objects does not have a react() method property, and it should be split using the forEach() iterator to add the reactions separately between each message, as seen below:

    client.channels.fetch(channelID).then(channel => {
      channel.messages.fetch({ limit: 5 }).then(messages => {
        messages.forEach(async message => {
          await message.react('✅') // It is recommended to await a reaction method before going on to the next one.
        })
      })
    })