Discord.js v13 Cannot read properties of undefined (reading 'roles')

Viewed 1314

I'm trying to create a command where if you say a slash command with a use parameter then it will give that user the role. I keep receiving this error even though I know that the member exists.

TypeError: Cannot read properties of undefined (reading 'roles')

My code:

const { commandName, options } = interaction;
const user = options.getUser('user');

if (commandName == 'givebetatester'){
     console.log(user);
     const role = interaction.guild.roles.cache.get('917609388154425374');
     interaction.reply('Success');

     user.member.roles.add(role);
}

I've double-checked that I have the role and the user exist and I have no idea what's wrong at this point. Any help would be appreciated.

2 Answers

You can only go from a GuildMember to User and not the other way around. You're trying to go from a User to a GuildMember by using user.member

Either change your slash command options to accept a Member instead of a User

Or ensure you have the Guild Member's Intent enabled and fetch the GuildMember object with the User id:

// Async/Await
const member = await interaction.guild.members.fetch(user.id);

Fixed! I switched from user to mentionable which might break if someone tries to type something other than a role but it does the trick.

Code:

const { commandName, options } = interaction;
const user = options.getMentionable('user');

if (commandName == 'givebetatester'){
     const role = interaction.guild.roles.cache.get('917609388154425374');
     user.roles.add(role);

     interaction.reply('<a:ncheckmark:917609071195074600>');
}
Related