Vincent Harris
Vincent Harris

Reputation: 70

How do I retrieve old messages from a channel?

I have a bot that should allow me to read all the messages from a selected server and channel when I request it. I've tried using channel.messages.cache.array(), but that just returns []. How do I effectively retrieve all (or most) of the messages from a Channel? Also, I'm using Discord.js v12.3.1.

// logging in the bot
var data = {};
client.on('guildCreate', function (guild) {
    var channel = guild.systemChannel;
    var msgs = channel.messages.cache.array();
    console.log(msgs);
});

Upvotes: 1

Views: 2378

Answers (1)

Lioness100
Lioness100

Reputation: 8402

I believe the reason that is not working is that when the bot joins the guild, none of the messages are cached. Instead, you should be using MessageManager#fetch(). This method can directly request the Discord API and get message data from there!

channel.messages.fetch().then((messages) => {
   console.log(messages.array());
   // ...
});

MessageManager.fetch() will by default only fetch the 50 latest messages, but you can override that with the limit option:

channel.messages.fetch({ limit: xxx }).then((messages) => {
   console.log(messages.array());
   // ...
});

Upvotes: 2

Related Questions