shows an error l“cannot read property ‘servers’ of undefined ”

Tags:



get my result here is my code :

const client = new Discord.Client();
const token = process.env.DISCORD_BOT_TOKEN;
const activities = [
`${this.client.servers.cache.size} servers!`,
`${this.client.channels.cache.size} channels!`,
`${this.client.guilds.cache.reduce((a, b) => a + b.memberCount, 0)} users!`
];


client.on('ready', message  => {
        let i = 0;
setInterval(() => this.client.user.setActivity(`${activities[i++ % activities.length]}`, { type: 'WATCHING' }), 10000);
  console.log(`Thank you for starting the mighty Towers. Please keep this page open to keep it running bro!!! This is ${client.user.tag}! hosted by Abhinav`) 
});

client.login(token);

Error

1: https://i.stack.imgur.com/DWiPg.png – this is an pick

this is the error ${this.client.servers.cache.size} servers!

Answer

The error is happening because this.client is not defined. You have defined const client so it is not accessible as this.client but as just client

Changing this.client to client in the code should solve your problem.

    const client = new Discord.Client();
    const token = process.env.DISCORD_BOT_TOKEN;
    const activities = [
    `${client.servers.cache.size} servers!`,
    `${client.channels.cache.size} channels!`,
    `${client.guilds.cache.reduce((a, b) => a + b.memberCount, 0)} users!`
    ];


    client.on('ready', message  => {
        let i = 0;
        setInterval(() => client.user.setActivity(`${activities[i++ % activities.length]}`, { type: 'WATCHING' }), 10000);
        console.log(`Thank you for starting the mighty Towers. Please keep this page open to keep it running bro!!! This is ${client.user.tag}! hosted by Abhinav`) 
    });

    client.login(token);


Source: stackoverflow