Click here to Skip to main content
15,878,543 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey all,
I'm coding a discord bot and I've coded a function that fetches messages from a channel on discord, but the bot can't read messages. I couldn't solve the problem, can anyone help me?

Error stack tree;

An error occurred while trying to fetch the channels:  TypeError: Cannot read properties of undefined (reading 'messages')
    at file:///C:/Users/Administrator/Desktop/gb-ac-bot/src/utils.js:7:88
    at Array.map (<anonymous>)
    at Object.allMessagesFromChannelList (file:///C:/Users/Administrator/Desktop/gb-ac-bot/src/utils.js:7:53)
    at Object.updateServerInfo (file:///C:/Users/Administrator/Desktop/gb-ac-bot/src/scheduler.js:6:34)
    at Timeout._onTimeout (file:///C:/Users/Administrator/Desktop/gb-ac-bot/src/index.js:53:21)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)

----------

utils.js file;

JavaScript
const allMessagesFromChannelList = async (client) => {
    const channels = global.channels.map(id => client.channels.cache.get(id))

    try {
        const messages = await Promise.all(channels.map(async channel => await channel.messages.fetch({ limit: 50 })))
        return messages.map(collection => collection.map(value => value))
            .flat()
            .filter(msg => msg.author.id === global.botId)
    } catch (error) {
        console.error('An error occurred while trying to fetch the channels: ', error)
        return []
    }
}


------------

The line of code that throws that error (line 7);
JavaScript
const messages = await Promise.all(channels.map(async channel => await channel.messages.fetch({ limit: 50 })))


What I have tried:

I read some articles from the Web, but it was not enough for me to solve the error. So I can't say that I tried a lot.
Posted
Updated 9-Aug-22 21:19pm
v2
Comments
Richard MacCutchan 10-Aug-22 3:27am    
The error is telling you that the object you are trying to use to read the messages has not been initialised. So it could be any one of Promise, channels, the return value from map(), channel, or channel.messages. You will need to do some debugging to find out which one.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900