I have the discord getting started example project running and working, so that I can run /test
and it gives a working response. I also created a new command /getmessages
, which now just returns a string.
I want to edit this command so it gets all messages sent in the channel, I’ve been trying to get this stackoverflow answer working:
Discord.js get an array of all messages in a channel
But I’m having trouble implementing the code from that stackoverflow accepted answer:
const channel = client.channels.cache.get("Your channel ID");
channel.messages.fetch({ limit: 100 }).then(messages => {
console.log(`Received ${messages.size} messages`);
//Iterate through the messages here with the variable "messages".
messages.forEach(message => console.log(message.content))
})
If I try to add the first part, getting channel to my javascript code like so:
if (name === 'getmessages') {
// Get all messages from this channel
console.log("try to get messages")
try{
const channel = client.channels.cache.get("961001859659759751");
}catch(err){
console.log("ERROR GETTING CHANNEL: ", err)
}
// Send a message into the channel where command was triggered from
return res.send({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
// Fetches a random emoji to send from a helper function
content: '2. Hello we will try to get messages ' + getRandomEmoji(),
},
});
}
I get this error:
ERROR GETTING CHANNEL: ReferenceError: client is not defined
Is this the correct method I should use for trying to get every channel message using the discord example javascript bot as a starting off point? I’m not sure what the ‘client’ var would be since my app.js code is already communicating with discord and receiving/posting messages correctly.