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