Search code examples
javascriptcommandbotsdiscorddiscord.js

Discord.js command that gives a role


so I'm trying to make a command that where you type $test and it gives you, for example, a "Test" role. This is my current code but I keep getting an error: "Cannot read property 'addRole' of undefined"

const Discord = require("discord.js");
const { send } = require("process");
const { clear } = require("console");
const client = new Discord.Client();
var prefix = "$";

client.login("token");

//TEST COMMAND
client.on("message", message => {

    if (message.content.startsWith(prefix + "test")) {
        message.channel.send("You have been given `Need to be tested` role! You will be tested shortly!")
        client.channels.get("701547440310059059").send(` please test ${message.author}!`)
        const member = message.mentions.members.first();
        let testRole = message.guild.roles.find(role => role.id == "609021049375293460")
        member.addRole(testRole)
        
    }})
    
    
client.on('ready',()=>{
    console.log(`[READY] Logged in as ${client.user.tag}! ID: ${client.user.id}`);
    let statuses = [
        "  status "
    ]
    setInterval(function(){
            let status = statuses[Math.floor(Math.random() * statuses.length)];
            client.user.setActivity(status, {type:"WATCHING"})
    
        }, 3000) //Seconds to Random
});

Please let me know how I can do this easily or something.


Solution

  • In discord.js v12, GuildMember does not have a function .addRole, you need to use GuildMemberRoleManager's .add, also you need to add .cache when getting roles from server, like this:

    const member = message.mentions.members.first();
            let testRole = message.guild.roles.cache.find(role => role.id == "609021049375293460")
            member.roles.add(testRole)