简体   繁体   中英

I have the TypeError: Cannot read property 'toString' of undefined

I'm making a discord welcomer bot and there's a problem where when someone joins the server it sends this error:

TypeError: Cannot read property 'toString' of undefined

Here is the source code:

module.exports = (client) => {
    const channelid = "865471665168580628";
    client.on("guildMemberAdd", (member) => {
        const serverid = member.guild.id
        const guild = client.guilds.cache.get(serverid);

        console.log("member");
        const ruleschannel = guild.channels.cache.find(channel => channel.name === "rules");

        const message = `welcome <@${member.id}> to music and chill! please read the ${member.guild.channels.cache.get(ruleschannel).toString()} before you start chatting.`;

        const channel = member.guild.channels.cache.get(channelid);
        channel.send(message);
    })
}

Can someone please help me?

It means member.guild.channels.cache.get(ruleschannel) is undefined . As ruleschannel is a channel object, and the Collection#get() method needs a snowflake, you need to use its id property.

So member.guild.channels.cache.get(ruleschannel.id) should work.

A better way would be to check if the ruleschannel exists though. Also, you can just simply add rulesChannel inside the backticks and it gets converted to a channel link. Check out the code below:

client.on('guildMemberAdd', (member) => {
  // not sure why not just: const { guild } = member
  const guild = client.guilds.cache.get(member.guild.id);
  const rulesChannel = guild.channels.cache.find((channel) => channel.name === 'rules');

  if (!rulesChannel)
    return console.log(`Can't find a channel named "rules"`);

  const channel = guild.channels.cache.get(channelid);
  const message = `Welcome <@${member.id}> to music and chill! Please, read the ${rulesChannel}.`;

  channel.send(message);
});

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