add a role to a user discord.js - javascript

I am trying to make a command that gives a role to a member after I type power. I already have a mute command, and that one works completely fine, But if I copy that code and change the name of the command and the role it has to give, it gives the error:
TypeError: Cannot read property of 'roles' of undefined
my code is:
if(message.content.startsWith("power")) {
let role = message.guild.roles.cache.find(r => === "Role_ID");
let member = message.mentions.members.first();
member.roles.add(role)
}

You can try:
if(message.content.startsWith("power")) {
let role = message.guild.roles.cache.find(r => === "Role_ID");
let member = message.mentions.members.first();
member.addRole(role)
}

Related

Add a role in Discord.js

I'm new at JS and I'm trying to make my bot give a specific role to a specific member.
If you can help me, please, do this.
The code:
bot.on("message", (msg) => {
if ((msg.content === "!give", role, member))
var role = msg.guild.roles.cache.find((r) => {
return r.name === "convidado astolfofo";
});
var member = msg.mentions.members.first();
member.roles.add(role);
console.log(member);
console.log(role);
});
The errors I encountered:
(node:2364) UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.
TypeError: Cannot read property 'add' of undefined discord.js
There are a couple of errors with your code. I'm not sure what you tried to do with if ((msg.content === "!give", role, member)) -- probably checking if the message starts with !give and if there is a role and a member -- but it won't work like that in JavaScript. You need to check them separately and once these variables are defined.
If you check if msg.content === "!give" but you also want the member to mention a member, it will never be true. If the whole message is just !give, there is no mentioned user. If there is a mentioned user, msg.content will be more than !give. Try to check if the message.content starts with "!give".
Next, if you don't use curly braces following your if statement, only the next line is inside that statement. So you try to check if the command is !give, and if it is, you search for a role, but the following lines where you check where you add the role are outside of this statement. It means, it runs on every incoming message. Try to use curly braces.
It's also a good idea to check permissions and send replies to let the user know if there are any missing ones.
Check the working example below, I've added comments to make it easier to understand:
bot.on('message', async (msg) => {
if (msg.content.startsWith('!give')) {
// check if the message author has the permission to add a role
if (!msg.member.hasPermission('MANAGE_ROLES')) {
return msg.reply('You need `MANAGE_ROLES` permission to add a role');
}
// check if the bot has the permission to add a role
if (!msg.guild.me.hasPermission('MANAGE_ROLES')) {
return msg.reply('I do not have `MANAGE_ROLES` permission to add a role');
}
// check if there is a member mentioned
const member = msg.mentions.members.first();
// if there is none, send a reply
if (!member) {
return msg.reply("Don't forget to mention someone!");
}
// search for the role
// don't forget that it's case-sensitive
const role = msg.guild.roles.cache.find((r) => r.name === 'convidado astolfofo');
// check if the role exists
if (!role) {
return msg.reply("Oh-oh, I can't find the role `convidado astolfofo`");
}
// try to add a role
try {
await member.roles.add(role);
msg.reply(`Role added to ${member}`);
} catch (error) {
console.log(error);
msg.reply('Oops, role not added, there was an error');
}
}
});
You seem to be using return incorrectly. Try this:
bot.on("message", (msg) => {
if ((msg.content === "!give", role, member))
var role = msg.guild.roles.cache.find(r => r.id === "<role id goes here>");
var member = msg.mentions.members.first();
member.roles.add(role);
console.log(member.username);
console.log(role.name);
});
I also changed your console.log statements since your console would get spammed with objects

discord.js - Bot wont add role: TypeError: Cannot read property 'add' of undefined

I am making a Discord bot to moderate my server. I wanted to add a command that gives the author any role by using the command !role [role name].
I used this:
const member = message.author
const rle = message.content.split(/ +/).slice(1).join(' ');
const role1 = message.guild.roles.cache.find(role => role.name === `${rle}`);
try {
member.roles.add(role1);
} catch (e) {
message.author.send(${e});
}
It (given I spell the role correctly) returns the following error:
"TypeError: Cannot read property 'add' of undefined"
Does anyone know how I would fix this issue?
The author property does not have a roles property. This is a common mistake. message.author returns a User class, while message.member returns a GuildMember class.
All you have to do is change message.author to message.member and it'll work!
Try this:
const member = message.author
const rle = message.content.split(/ +/).slice(1).join(' ');
const role1 = message.guild.roles.cache.find(role => role.name === `${rle}`);
try
{
message.guild.member(member).roles.add(role1);
}
catch (e)
{
message.author.send(${e});
}

Auto role when someone starts streaming

I wanted to set a role for a user if he/she starts streaming and sending a message in #streaming. But I keep getting this error that TypeError: Cannot read 'add' of undefined.
client.on('presenceUpdate', (oldMember, newMember) => {
const guild = newMember.guild;
const streamingRole = guild.roles.cache.find(role => role.id === 'streamer');
if (newMember.user.bot) return;
if (newMember.user.presence.activities.streaming) { // Started playing.
let announcement = `Ebrywan ${newMember} just started streaming`;
let channelID = client.channels.cache.find(channel => channel.name.toLowerCase() === "streaming");
if (channelID) channelID.send(announcement);
newMember.roles.add(streamingRole)
console.log(`${streamingRole.name} added to ${newMember.user.tag}`)
}
});
From what i can see from the documentation newMember is a Presence and not a user you can add a role too. Try:
newMember.member.roles.add(streamingRole)
.member will give you the member and you can get the roles of a member + adding new roles should also be possible
Presence: https://discord.js.org/#/docs/main/stable/class/Presence
Member: https://discord.js.org/#/docs/main/stable/class/GuildMember

discord.js client.guilds.cache.get(role).members | Create a array with all members of a guild

I want to create an array with every user with a specific role. But I get the following error:
TypeError: Cannot read property 'members' of undefined
The code that I am currently using:
var role = receivedMessage.guild.roles.cache.find(role => role.name === "arole");
const guild = client.guilds.cache.get(role);
if (guild == "") {
console.log("guild not found");
} else {
const Members = client.guilds.cache.get(role).members.cache.map(member => member.id);
}
This code gets all members with a certain role in the server the message was sent in:
const guild = receivedMessage.guild;
if (!guild) return console.log("Couldn't get the guild.");
const members = guild.members.cache.filter(member => member.roles.cache.find(role => role.name === "arole")).map(member => member.id);
If you want to get all members with a certain role in a specific server, you can specify the guild ID:
const guild = client.guilds.cache.get(/* Guild ID */);
if (!guild) return console.log("Couldn't get the guild.");
const members = guild.members.cache.filter(member => member.roles.cache.find(role => role.name === "arole")).map(member => member.id);
For more information on valid properties and methods, please read the Discord.js docs.
Seems like the guild is non-existent or your bot doesn't have acccess to it, you can simply check this by doing something like
const guild = client.guilds.cache.get("335507048017952771");
if (!guild) return console.log("guild not found :(");
//also use the built-in array() method
console.log(guild.array());

Add On to Discord.JS Userinfo post

Alright, this may look like a copy and paste but it is NOT. I need more support. I'm trying to make my bot do more. I should've added it to the first question but I don't think it'll get viewed. Here's what I'm trying to add.
Say when user joined guild at what time and date
Tag user in userinfo.tag function
List user's nickname
I've tried using the .guildmember class but it just won't work, I'm attaching userMention to the .guildmember class, like this : userMention.guildmember.joinedAt or displayName. Most of my results when modifying my code were either TypeErrors from the bot or ReferenceErrors.
I did use other's code, and I installed Moment, so I could run it with another person's code, but again it gave out an error.
TypeError: Cannot read property 'filter' of undefined
I wasn't able to get the Moment code.
var commando = require('discord.js-commando');
var discord = require('discord.js');
class aboutuser extends commando.Command
{
constructor(client) {
super(client, {
name: 'aboutuser',
group: 'help',
memberName: 'aboutuser',
description: 'Lists information about a specific user.',
aliases: ['au', 'aboutu', 'auser', 'user'],
})
}
async run(message, args){
const userMention = message.mentions.users.first() || message.author;
let userinfo = {};
userinfo.bot = userMention.bot;
userinfo.createdat = userMention.createdAt;
userinfo.joinedat = userMention.message.guildmember.joinedat;
userinfo.discrim = userMention.discriminator;
userinfo.id = userMention.id;
userinfo.tag = userMention.tag;
userinfo.uname = userMention.username;
userinfo.status = userMention.presence.status;
userinfo.play = userMention.presence.game;
userinfo.avatar = userMention.avatarURL;
const rolesOfTheMember = userMention.roles.filter(r => r.name !== '#everyone').map(role => role.name).join(', ')
var myInfo = new discord.RichEmbed()
.setAuthor(userinfo.uname, userinfo.avatar)
.addField("Username",userinfo.uname, true)
.addField("Client Tag",userinfo.tag, true)
.addField("Created At",userinfo.createdat, true)
.addField("Joined at:",userinfo.joinedat, true)
.addField("Discriminator",userinfo.discrim, true)
.addField("Client ID",userinfo.id, true)
.addField("Bot?",userinfo.bot, true)
.addField("Status",userinfo.status, true)
.addField("Playing",userinfo.play, true)
.addField("Roles",rolesOfTheMember, true)
.setColor(0xf0e5da)
.setFooter('s!aboutserver')
.setTitle("About this user...")
.setThumbnail(userinfo.avatar)
message.channel.sendEmbed(myInfo);
}
}
module.exports = aboutuser;
Expect: A bot that lists all shown in the code, plus the bullets.
Actual: A bot that only shows Type and Reference Errors. It's things like
TypeError: Cannot read property 'guildmember' of undefined
TypeError: Cannot read property 'filter' of undefined
ReferenceError: guildmember is not defined
ReferenceError: user is not defined
I'm using these sites for reference
https://discord.js.org/#/docs/main/stable/general/welcome
How to show roles of user discord.js / userinfo command *Specifically this line!
.addField('Joined at:', `${moment.utc(user.joinedAt).format('dddd, MMMM Do YYYY, HH:mm:ss')}`, true)
https://www.youtube.com/watch?v=W2iI32FDYW8
Use
var umen = message.mentions.members.first() || message.member;
var umen2 = message.mentions.users.first() || message.author;
Also had trouble with "Booleans" and those should NOT be === "false" as they are Booleans, not strings. Do === false or === true
Try using userMention = message.mentions.members.first();
I think its what's causing the issue

Categories