简体   繁体   中英

Why is .get() not working in my discord bot code?

I am trying to change a channel's name to show the number of users in the guild. However, when I start up my bot, it says the following in the console:

Cannot read property 'edit' of undefined

I narrowed the problem down to this line: bot.channels.get("533334637163053077");

Just in case you need it, here is my code:

const Discord=require('discord.js');
const fs = require("fs");
const bot = new Discord.Client();
const PREFIX = "-";
const guildID = "418505146876559371";
let ref = require("./ref.json");
let request = require(`request`);
const memberCountChannel = bot.channels.get("533334637163053077"); //This one is the one
//that is not working I think
bot.commands = new Discord.Collection();

var servers = {};

bot.on('warn', console.warn);
bot.on('error', console.error);

bot.on('ready', function(guild)
{
    console.log(`${bot.user.username} is online with ${bot.users.size} 
    members.\n\n\n\n\n\n\n\n\n`);
    bot.user.setActivity('with the server. Type -help for info.');
    memberCountChannel.edit(`Members: ${guild.memberCount}`, 8000); //Change name of channel
});
bot.on("guildMemberAdd", function(member){
    memberCountChannel.edit(`Members: ${guild.memberCount}`, 8000);//Change name of channel
});

bot.on("guildMemberRemove", async function(member){
    memberCountChannel.edit(`Members: ${guild.memberCount}`, 8000);//Change name of channel
});
bot.login('TOKEN HERE');

EDIT: The channel does exist and the bot does have privileges to do everything with the channel.

Essentially the issue was, as you correctly surmised with

const memberCountChannel = bot.channels.get("533334637163053077");

The reason for this is you are trying to call a method(.get) on an object (channels) that doesn't exist until the .on('ready') event is fired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM