Search code examples
node.jstypescriptdiscord.js

DiscordJS Get member of x message in channel


I'm trying to get the member of a specific message in a specific channel. In the code below for example I'm trying to get the member of the 2nd message in a channel.

            let arr = []
            interaction.channel.messages.fetch({ limit: 100 }).then(messages => {
                messages.forEach((message) => {
                    arr.push(message)
                });
            }).catch(err => {
                console.log(err);
            });
            let firstMsg = interaction.channel.messages.fetch(arr[arr.length - 2].id)
            let memb = (await firstMsg).member.id

I get following error though:

TypeError: Cannot read properties of undefined (reading 'id')

Is there a better way to do this? If not how could I fix the error?


Solution

  • You should put the code in the then part of the promise:

                interaction.channel.messages.fetch({ limit: 100 }).then(messages => {
                    const secondMessage = messages.toJSON()[messages.size - 2];
                    const member = secondMessage.author.id;
    
                }).catch(err => {
                    console.log(err);
                });