Reputation: 615
I've been trying to get the last message of a channel writing a command in another channel.
I want to do something like this:
Channel 1 : (I write) "Get last message of channel 2 channel 2: Last message is ("Hello"); Channel 1: i receive the last message of channel 2 saying, the last message of channel 2 is . "Hello".
My code is this, but isn't working.
if (message.channel.id === '613573853565681671') {
message.channel.fetchMessages().then(collected => {
const filtered = collected.filter(message => message.author.bot);
const lastMessages = filtered.first(1); //Get the last message of this channel.
const TextMessages = `${lastMessages[0].content}`;
console.log(TextMessages + " is the last message of aviso jobs")
if (TextMessages === "look") { //If the last message of this channel is look then go to the other channel
if (message.channel.id === '613553889433747477') {
message.channel.fetchMessages().then(collected => {
const filtered = collected.filter(message => message.author.bot);
const lastMessages2 = filtered.first(1); //Get the last message of this other channel.
const TextMessages2 = `${lastMessages2[0].content}`;
console.log(TextMessages2 + " is the last message of bot")
});
}
}
});
}
Upvotes: 1
Views: 2209
Reputation: 224
I'm having troubles understanding your code so here's how i would do it, maybe it'll help you:
if (message.content.startsWith("!lastmessage")) {
let args = message.content.split(" "); //find every word of the message
if (args.length > 1) { //make sure that there is at least 1 argument, which should be the target channel's id
let target = message.guild.channels.find(c => c.id == args[1]) || null; // find the targeted channel
if (target) { // make sure that the targeted channel exists, if it exists then fetch its last message
target
.fetchMessages({ limit: 1 })
.then(f =>
message.channel.send(
`Last message from <#${target.id}> is...\n> ${f.first().content}`
) // send the last message to the initial channel
);
} else { //if target doesn't exist, send an error
message.channel.send("Target does not exist!");
}
}
}
Upvotes: 1