Skip to content

Discord.js: Add role to message sender

i am trying to make a discord.js bot that adds a role to a user when they type: +rolename .

This is what I have come up with:

const { Client } = require("discord.js");
const { config } = require("dotenv");
const fs = require('fs');

const client = new Client({
    partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});

config({
    path: __dirname + "/.env"
});

client.on("ready", () => {
    console.log(`Hi, ${client.user.username} is now online!`);
    client.user.setStatus('online');
    client.user.setActivity('me getting developed', { type: "WATCHING"})
        .then(() => console.log('bot status set'))
        .catch(console.error);
});

client.on("message", (message) => {
    if (message.content.startsWith("+")) {
        var args = message.content.split(' ');
        if (args.length == 1) {
            console.log(`message is created -> ${message}`);
            const { guild } = message;

            var passrole = args[0];
            var roleid = passrole.substring(1);
                
            var role = message.guild.roles.cache.find((role) => {
                return role.name == roleid;
            });
            
            console.log('role found')
            var authoruser = message.author.id;
            if (!role) {
                message.reply('this role does not exist')
                console.log('role does not exist')
                return;          
            }

            console.log(target)
            authoruser.roles.add(role)
                            
            console.log("role added")
        } else {
            message.reply('invalid argument length passed')
            return;
        }
    } else {
        return;
    }
});

client.login(process.env.TOKEN);

When running the code i get the following error:

TypeError: Cannot read property ‘add’ of undefined

This doesn’t happen when I use this code and type +test @DiscordName#0001:

const { Client } = require("discord.js");
const { config } = require("dotenv");
const fs = require('fs');

const client = new Client({
    partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});

config({
    path: __dirname + "/.env"
})

client.on("ready", () => {
    console.log(`Hi, ${client.user.username} is now online!`);
    client.user.setStatus('online');
    client.user.setActivity('me getting developed', { type: "WATCHING"})
        .then(presence => console.log('bot status set'))
        .catch(console.error);
});

client.on("message", (message) => {
    let target = message.mentions.members.first();
    if (message.content.startsWith("+")) {
        var args = message.content.split(' ');
        if(args.length == 2){
            console.log(`message is created -> ${message}`);
            const { guild } = message;

            var passrole = args[0]
            var roleid = passrole.substring(1);
                
            var role = message.guild.roles.cache.find((role) => {
                return role.name == roleid;
            })
            
            console.log('role found')
            if (!role) {
                message.reply('role does not exist')
                console.log('role does not exist')
                return;          
            }

            console.log(target)
            target.roles.add(role)
                            
            console.log("role added")
        } else {
            message.reply('invalid argument length passed')
            return;
        }
    } else {
        return;
    }
});

client.login(process.env.TOKEN);

My question is: How can I add the role to the message author.

Thanks in advance

Answer

The problem is that your authoruser is the users id (= string) not the member. You cannot add roles to users. Also if you get the role’s id and not the name of the role you can add the role with the role’s id.

client.on("message", message =>{
    if (message.content.startsWith("+")) {
        var args = message.content.split(' ');
        if (args.length !== 1) {
            message.reply('invalid argument count passed');
            return;
        }

        if (!message.member ||!message.guild) {
            message.reply('can only be used in guilds');
            return;
        }

        console.log(`message is created -> ${message}`);
        const { guild } = message;

        var passrole = args[0];

        var roleid = passrole.substring(1);
        
        // If you get the role's id then you won't need this
        var role = message.guild.roles.cache.find((role) => role.name == roleid);
            
        if (!role) {
            message.reply('this role does not exist');
            console.log('role does not exist');
            return;          
        }

        console.log('role found');
        console.log(target);

        message.member.roles.add(role);
        // If you get the role's id use this:
        message.member.roles.add(roleid);

        console.log('role added');
});