Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
How do I get the last message sent in a channel? | discord.js v13

I already know how to grab the last message sent. However, it keeps grabbing the message sent to execute the command. For example, if initiating the comment is by writing in the channel !test then the last message sent would be !test. I need the actual last message sent, which is the one before it.

Code:

let last = "";
let lastMessage = await message.channel.messages.fetch({ limit: 2 });
lastMessage.each((msg) => {
    last = msg.content; 
})

I've tried setting the limit to 2 in hopes that it would grab both the command sent to initiate the function and the previous message sent itself. However, I do not know how to differentiate between the two to grab the actual previous message as msg.content just returns the command !test.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you use the limit option to fetch the last two messages in a channel, it returns a collection. These messages are sorted in descending order, based on the date they were posted. It means, the first item in the returned collection is the last message sent (the one with the command), the second item is the second last message (the last one before the command).

Collections have methods like first() and last() that return the first and last items respectively.

let lastMessages = await message.channel.messages.fetch({ limit: 2 });
// this is the last message sent before this command
let previousMessage = lastMessages.last();

message.reply(`The last message was _"${previousMessage.content}"_`);
message.reply(
  `Is the first fetched message (i.e. \`lastMessages.first()\`) the same as this message?\n ${
    message.id === lastMessages.first().id ? '✅ yes' : '❌ no'
  }`,
);

enter image description here

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!