wick3d
wick3d

Reputation: 1422

How to get last N messages by a particular user in discordJS?

I am trying to delete the messages sent by a particular user.

eg. !purge 5 @someone

To get N message sent by a specific userId i am using this.

const getAllMessageByUserId = async (message, messageCount) => {
  const userId = getUserId(message);
  return await message.channel.messages.fetch({ limit: 100 }).then(async (messages) => {
    const filteredMessages = await messages.filter((m) => m.author.id === userId);
    if (filteredMessages.size <= messageCount) {
      console.log('User does not have that many messages to be deleted?');
      return;
    }
    const data = [...filteredMessages];
    const messagesToBeDeletedByCount = data.slice(Math.max(data.length - messageCount), 1);
    console.log(messagesToBeDeletedByCount);
    console.log(typeof messagesToBeDeletedByCount);
    return messagesToBeDeletedByCount;
  });
};

Console:

[]
object

data has all the messages stored in an array and I have confirmed that using console earlier.

But when I try with splice it does not work and gives an empty array.

Upvotes: 0

Views: 164

Answers (1)

Elitezen
Elitezen

Reputation: 6730

Collections have a .last() method, call last N on your collection of filtered messages.

filteredMessages.last(N);

More on Collections

Upvotes: 1

Related Questions