clubby789
clubby789

Reputation: 2733

Get last message sent to channel

I already have a variable containing a specific channel, but how can I obtain the last message sent to the channel? I want to make my bot only perform an action if the last message to the channel wasn't by it.

Upvotes: 12

Views: 38755

Answers (3)

T. Dirks
T. Dirks

Reputation: 3676

If you already have the specific channel stored in a variable, it's quite easy. You can call the MessageManager#fetch() method on that specific channel and get the latest message.

Example:

let channel // <-- your pre-filled channel variable

channel.messages.fetch({ limit: 1 }).then(messages => {
  let lastMessage = messages.first();
  
  if (!lastMessage.author.bot) {
    // The author of the last message wasn't a bot
  }
})
.catch(console.error);

 

However if you don't have the complete channel object saved in a variable but only the channel ID, you'll need to fetch the correct channel first by doing:

let channel = bot.channels.get("ID of the channel here");

Upvotes: 17

Dwza
Dwza

Reputation: 6565

There is a property containing the object of the last writte message. So the most short version of getting last Message is:

let lm = channel.lastMessage;

Of course @Tyler 's version is still working. But my IDE says that he don't know first(). So may this will be deprecated some day?!? I don't know.

Anyway, in both ways you retrieve an object of the message. If you want to have e.g. the text you can do this

let msgText = lm.content; // channel.lastMessage.content works as well

Upvotes: 3

Tyler
Tyler

Reputation: 1830

Recently I believe they've changed from channel.fetchMessages() to channel.messages.fetch()

channel.messages.fetch({ limit: 1 }).then(messages => {
  let lastMessage = messages.first();

  // do what you need with lastMessage below

})
.catch(console.error);

Upvotes: 7

Related Questions