skip to Main Content

I was trying to give myself a role when executing a "/" command, and ive tryed many solutions from stackoverflow but none of them work for discord.js v14. Im pretty new to js.

tryed:

const guild = interaction.guild
const role = guild.roles.cache.find(role => role.name === 'Admin');
var dcuser = interaction.user.id
dcuser.roles.add(role)

Got:

TypeError: Cannot read properties of undefined (reading ‘add’)

2

Answers


  1. The user.id (string) does not have .add(role) method

    Try this

    const guild = interaction.guild
    const role = guild.roles.cache.find(role => role.name === 'Admin'); // Find role named "Admin" in cached roles
    const member = interaction.member; // Guild member
    await member.roles.add(role); // Add role to member
    
    Login or Signup to reply.
  2. In Discord.js v14, the roles property is not directly accessible on the User object. Instead, you need to get the GuildMember object for the user and then use the roles property on that object to add or remove roles.

    Here’s how you can give a user a role with a slash command:

    const { SlashCommandBuilder } = require('@discordjs/builders');
    
    module.exports = {
      data: new SlashCommandBuilder()
        .setName('giverole')
        .setDescription('Give a user a role.')
        .addUserOption(option =>
          option.setName('user')
            .setDescription('The user to give the role to.')
            .setRequired(true))
        .addRoleOption(option =>
          option.setName('role')
            .setDescription('The role to give to the user.')
            .setRequired(true)),
      async execute(interaction) {
        const guild = interaction.guild;
        const member = guild.members.cache.get(interaction.options.getUser('user').id);
        const role = interaction.options.getRole('role');
    
        try {
          await member.roles.add(role);
          await interaction.reply(`The role ${role.name} has been added to ${member.user.username}.`);
        } catch (error) {
          console.error(error);
          await interaction.reply('There was an error giving the role.');
        }
      },
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search