'TypeError: Cannot read properties of undefined (reading 'cache') when trying to get a random users avatar Discord.js

This code gets displays a random user's avatar when you type !avatar, but it does not work and only returns TypeError: Cannot read properties of undefined (reading 'cache')

const { MessageEmbed } = require('discord.js');

module.exports = {
    name: 'avatar',
    /**
     * 
     * @param {Client} client
     * @param {Message} message
     */
    description: "Get avatar",
    async execute(client, args, message,){
        const user = client.users.cache.random()

        message.channel.send(
            new MessageEmbed()
                .setColor("RANDOM")
                .setImage(user.displayAvatarURL())
        )
    }

}

I changed module.exports to module.exports.execute



Solution 1:[1]

You can try changing this code line:

const user = client.users.cache.random()

to:

const user = message.guild.members.cache.random()

because you only need to cache on your main server or whenever the bot gets in

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 æ–°Acesyyy