How to fetch messages until a specific date?

Viewed 144

How would one fetch messages from text channel beginning with the latest/newest message until a specific date. For example until the date two days ago.

The desired result is having a function that will do the job and return an array of messages dating in a range: now -> end date specified as the function's argument.

1 Answers

This would be my approach, feel free to post your own better answers :3

async function fetchMessagesUntil(channel, endDate, lastID) {
    let messages = (await channel.messages.fetch({ limit: 100, before: lastID })).array();
    if (messages.length == 0) return messages;
    for (let i = 0; i < messages.length; i++) {
        if (messages[i].createdAt.getTime() < endDate.getTime()) {
            return messages.slice(0, i);
        }
    }
    return messages.concat(
        await fetchMessagesUntil(channel, endDate, messages[messages.length - 1].id)
    );
}

Example usage

let end = new Date();
end.setDate(end.getDate() - 2); // Subtract two days from now
(await fetchMessagesUntil(message.channel, end)).forEach(x => console.log(x.content));
Related