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

Viewed 447

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

3 Answers

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.
    })
  })
})

Considering you already have a channel as a message property you should do something like this:

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

The problem is MessageManager#fetch() returns a Collection (Map) of all the fetched messages. You are trying to call .react() directly on what is essentially a list of multiple messages. Use .forEach() to react to each individual message.

message.channel.messages.fetch(channelID).then(channel => {
            channel.messages.fetch({limit : 5}).then(messages => {
                messages.forEach(msg => {
                   msg.react('✅')
                })
            })
       })

Documentation for MessageManager#fetch()

Related