I'm trying to get the last message of a specific channel but I've couldn't do that, I want that if i write a command in another channel (Channel 1) that command gives me the last message of another channel (channel 2).
My code is:
client.on('message', (message)=>{
if(message.channel.id === '613553889433747477'){
if(message.content.startsWith('start')){
message.channel.fetchMessages({ limit: 1 }).then(messages => {
let lastMessage = messages.first();
console.log(lastMessage.content);
})
.catch(console.error);
}
}
});
I cleaned up you code a bit, and added some comments explaining what is happening.
If you have more questions, i would recommend visiting the official Discord.js Discord server.
https://discord.gg/bRCvFy9
client.on('message', message => {
// Check if the message was sent in the channel with the specified id.
// NOTE, this defines the message variable that is going to be used later.
if(message.channel.id === '613553889433747477'){
if(message.content.startsWith('start')) {
// Becuase the message varibable still refers to the command message,
// this method will fetch the last message sent in the same channel as the command message.
message.channel.fetchMessages({ limit: 1 }).then(messages => {
const lastMessage = messages.first()
console.log(lastMessage.content)
}).catch(err => {
console.error(err)
})
}
}
})
If you want to get a message from another channel, you can do something like this.
And use the command start #channel
client.on('message', message => {
// Check if the message was sent in the channel with the specified id.
if(message.channel.id === '613553889433747477'){
if(message.content.startsWith('start')) {
// Get the channel to fetch the message from.
const channelToCheck = message.mentions.channels.first()
// Fetch the last message from the mentioned channel.
channelToCheck.fetchMessages({ limit: 1 }).then(messages => {
const lastMessage = messages.first()
console.log(lastMessage.content)
}).catch(err => {
console.error(err)
})
}
}
})
More about mentioning channels in messages can be found here. https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=mentions
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.