Skip to content
Advertisement

How do i fix Cannot read property ‘channels’ of undefined

I want to make a discord bot program. when someone new goes to the server they have to type !daftar to be able to enjoy the server. and when they type !daftar message list will appear on #welcome channel. but I get an error that is in the title. here is my code

const { GuildMember } = require("discord.js");

module.exports = {
    name: 'daftar',
    description: "This is for add roles to a member",
    execute(message, args) {
        let role = message.guild.roles.cache.find(r => r.name === "Members")

        if (message.member.roles.cache.some(r => r.name === "Members")) {
            message.channel.send('Kamu sudah menjadi MEMBER Di grup ini');
        } else {
            message.member.roles.add('817360044622217276');
            message.member.roles.remove('817965925122048010');
            message.channel.send('Baiklah silahkan menikmati Server');
            GuildMember.guild.channels.cache.get('817957997312737290').send(`Selamat Datang <@${GuildMember.user.id}>`)

        }


    }
}

Advertisement

Answer

GuildMember is not exactly defined. Yes, you are destructuring it as the property of discord.js, but it’s not exactly defined as who the member actually is. Right now it’s just an empty object that belongs to no one, meaning that it also has no properties itself as it does not know what it refers to.

Assuming that you’re wanting to give the role to the member who typed this command, you’d have to make the GuildMember object the property of the Message object that is defined as message in your parameters. We can get this object using the member property of message => message.member.

Now, assuming that the channel you’re looking to send the message to is found in the same guild as the message object, there is no sense behind using a GuildMember object to find a certain channel, when we can instead use the Message object, as seen below:

Final Code

module.exports = {
    name: 'daftar',
    description: "This is for add roles to a member",
    execute(message, args) {
        let role = message.guild.roles.cache.find(r => r.name === "Members")

        if (message.member.roles.cache.some(r => r.name === "Members")) {
            message.channel.send('Kamu sudah menjadi MEMBER Di grup ini');
        } else {
            message.member.roles.add('817360044622217276');
            message.member.roles.remove('817965925122048010');
            message.channel.send('Baiklah silahkan menikmati Server');
            message.guild.channels.cache.get('817957997312737290').send(`Selamat Datang <@${GuildMember.user.id}>`)    
        }
    }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement