Search code examples
discorddiscord.js

Discord js Cannot read properties of undefined (reading 'add')


Hey I have a little problem.

I wan't to assign a discord role when the bot starts up I wan't it to work with id's like user id and role id but it is saying Cannot read properties of undefined (reading 'add')

Thanks in advance Neo

My intents are enabled on discord developer portal

const client = new Client({

intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS], }); // intents stuff

enter image description here


Solution

  • Guild should not be a variable as it is going to change. Roles need to be fetched from the cache. And then once you have defined guild you can use it without defining it again. Try the code below and you should be good.

    client.on('ready' async () => {
        const guild = client.guilds.cache.get('976862525801000960')
        const role = guild.roles.cache.get('978375133649592361')
        const member = await guild.members.cache.get('404645579705024523')
        
        member.roles.add(role).then(
            console.log(`TOKEN: `)
        )