Home > Blockchain >  Add role for role ID discord.js
Add role for role ID discord.js

Time:06-13

I am trying to add a role from a role ID, but I cannot figure it out, Please help!

Here is the code I am using:

module.exports= {
    name: 'giver',
    description: "Give the user who ran the command the role they asked for",
    execute(message, args, Discord){
        message.channel.send(`${args}`)
        
        let role = message.guild.roles.cache.find(r => r.name === `${args}`);

        if(message.member.roles.cache.some(r => r.name === `${args}`)){
            const youAlreadyHaveTheRole = new Discord.MessageEmbed()
            .setColor('#0')
            .setDescription(`You have already have the role ${role}!`)
            message.channel.send(youAlreadyHaveTheRole);
        } else {
           const TheRoleWasAdded = new Discord.MessageEmbed()
           .setColor('#0')
           .setDescription(`The role ${role} was added!`)
           message.member.roles.add(role).catch(console.error);
           message.channel.send(TheRoleWasAdded);
        }

    }
}

How can I make it so that the role ID that the user entered would be converted into a role ?? Please help!

CodePudding user response:

Hopefully this code fixes the problem you're having. I'm assuming the command is something like !giver 1234

module.exports= {
    name: 'giver',
    description: "Give the user who ran the command the role they asked for",
    execute(message, args, Discord){
        message.channel.send(args)
        
        let role = message.guild.roles.cache.find(r => r.name === args[1]);

        if(message.member.roles.cache.some(r => r.name === args[1])){
            const youAlreadyHaveTheRole = new Discord.MessageEmbed()
            .setColor('#0')
            .setDescription(`You have already have the role ${role}!`)
            message.channel.send(youAlreadyHaveTheRole);
        } else {
           const TheRoleWasAdded = new Discord.MessageEmbed()
           .setColor('#0')
           .setDescription(`The role ${role} was added!`)
           message.member.roles.add(role).catch(console.error);
           message.channel.send(TheRoleWasAdded);
        }

    }
}

CodePudding user response:

If the args[0] is the role ID or ping you can use :

const role = message.mentions.roles.first() || message.guild.roles.cache.get(args[0]) 

if it a role name you should use the code that @anotherpillow gave you

  • Related