addRole to a mentioned user isn't working - javascript

I'm trying to make a discord bot, which can add a specific role to an user.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', (message) => {
let allowedRole = message.guild.channels.find(channel => channel.name === "Streamer");
let gRole = message.guild.channels.find(channel => channel.name === "Stream 1");
mention = message.mentions.users.first();
let member = message.mentions.users.first();
if (message.content === "addRole") {
members.get(message.mentions.user.id).addRole(gRole);
}
});
client.login('mytoken');
I expect that the bot can add role to a specific person

First of all, your first mistake was, that you searched for channel names and not role names in your variable gRole and allowedRole. I changed this 2 variables, so they search for roles instead of channels.
You defined twice the same, once as mention and once as member = message.mentions.users.first(). Because of this, I removed your variable named mention and used the variable member. I found that the code for this variable didn't match the name of the variable because your code returned the user Object and I changed it to the member Object (because your variable is named member).
Lastly, I used your predefined variable member and assigned the role gRole to it, so you don't have to get the member another time.
Try to use the following code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', message => {
const allowedRole = message.guild.roles.find(role => role.name === 'Streamer'); // isn't used
const gRole = message.guild.roles.find(role => role.name === 'Stream 1');
const member = message.mentions.members.first();
if (message.content === 'addRole') {
member.addRole(gRole);
}
});
client.login('mytoken');

Related

Discord bot recognize if someone pings an account and replies

I have been working on a basic discord bot to reply when someone pings my account. So far it works only for direct pings and not for when you ping my role. Any help would be appreciated.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
const ownerId = "";
client.on("message", async message => {
if (message.author.bot) return false;
if (message.mentions.has(ownerId)) {
message.reply(`reply`);
};
});
The basic idea in the code below is that it'll first grab the GuildMember object from the user in the Guild that the message was sent in. Then, it'll check the message for any mentions and place all of the role IDs in messageRoles. It also places all of the user's member roles into another array called memberRoles. Then, it compares the two arrays together with some (very handy method), and if it's true, then it'll reply back.
Code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
const ownerId = "";
client.on("message", async message => {
if (message.author.bot) return false;
if (message.mentions.has(ownerId)) {
message.reply(`reply`);
}
let user = client.users.cache.get(ownerId);
let currentGuild = message.guild;
let currentMember = currentGuild.members.cache.get(user.id);
let memberRoles = [];
currentMember.roles.cache.each(role => {
memberRoles.push(role.id);
});
let messageRoles = [];
console.log(message.mentions.roles);
message.mentions.roles.each(role => {
messageRoles.push(role.id);
})
let containsMention = messageRoles.some(x => memberRoles.includes(x));
if (containsMention) {
message.reply('reply');
}
});

add roles command not working (discord.js)

I am Coding my own discord bot for my server, I have a issue that the bot says no role doesn't exit even if I mentions the role. Here is the code:
const Discord = require('discord.js')
const client = new Discord.Client()
client.on("message", message => {
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase()
if (command === "add") {
if (!message.member.hasPermission("MANAGE_ROLES"))
return message.channel.send("Insufficient permissions")
const member = message.mentions.members.first()
if (!member)
return message.channel.send("No user mentioned")
const add = args.slice(1).join(" ")
if (!add)
return message.channel.send("No role said")
const roleAdd = message.guild.roles.find(role => role.name === add);
if (!roleAdd)
return message.channel.send("Role does not exist")
if (member.roles.has(roleAdd.id)){
return message.channel.send("User already has role")
}
if (member) {
member.addRole(roleAdd).catch((error) =>{
message.channel.send("I cant add...")
}).then((member) => {
message.channel.send(`:thumbsup: ${roleAdd} added to ${member.displayName}`)
})
}
}
})
client.login(config.token)
What did I made a mistake? Thanks.
First make sure you are using discord.js v12. Type npm i discord.js#latest in your terminal. Here you can see all changes in discord.js v12.
If you are using discord.js v12 now, this code should work for you:
if (!message.member.hasPermission("MANAGE_ROLES"))
return message.channel.send("Insufficient permissions")
const member = message.mentions.members.first()
if (!member)
return message.channel.send("No user mentioned")
const add = args.slice(1).join(" ");
if (!add)
return message.channel.send("No role said")
const roleAdd = message.guild.roles.cache.find(role => role.name === add);
if (!roleAdd)
return message.channel.send("Role does not exist")
if (member.roles.cache.has(roleAdd.id)) {
return message.channel.send("User already has role")
}
if (member) {
member.roles.add(roleAdd).catch((error) => {
message.channel.send("I cant add...")
}).then((member) => {
message.channel.send(`:thumbsup: ${roleAdd} added to ${member.displayName}`)
})
}
Mention the role you want to add won't work because here
const roleAdd = message.guild.roles.cache.find(role => role.name === add);
you just find the role by its name. To fix that you can change that line into:
const roleAdd = message.guild.roles.cache.find(role => role.name === add) || message.mentions.roles.first();
This will allow a user to mention the role as well.

Discord.js TypeError: Cannot read property 'add' of undefined, what to do?

i wants to make /mute command, but have one problem with add role. On my line await member.roles.add(muterole).catch(console.error); write error:cannot read property 'add' of undefined. I do not know what to do. Please help me. My full code:
const Discord = require('discord.js');
const Bot = new Discord.Client();
Bot.on("ready", () => {
console.log(`Bot joined by ${Bot.user.tag}`);
});
Bot.on("message", async msg => {
if (msg.author.bot) return;
if (msg.channel.type === "dm") return;
let Prefix = "/";
if (msg.content.startsWith(Prefix)) {
let massive = msg.content.split(" ");
let cmd = massive[0];
let args = massive.slice(1);
if (msg.content.startsWith(`${Prefix}mute`)) {
let member = msg.mentions.users.first();
if (member) {
//let member = msg.guild.member(user);
let muterole = msg.guild.roles.cache.find(role => role.name === "Muted");
await member.roles.add(muterole).catch(console.error);
}
}
}
})
Bot.login('my token been hidden :)');
according to discord.js docs class User, which is represented by msg.mentions.users.first() entity here, does not have a property 'roles'
upd:
you might be looking for msg.mentions.members.first(), which is an entity of GuildMember.

Code returns all members and not the members in the role

This is the code:
let getMembers = message.guild.members.cache.filter(member => {
return message.guild.roles.fetch('701142571623252018');
}).map(member => {
return member.user.username;
});
It returns all members in the server, but not the members in the specific role, which it is supposed to do.
This is my full code:
const targetRole = message.guild.roles.cache.get('701142571623252018');
if (!targetRole) return console.log('No role found')
const members = message.guild.members.cache.filter((member) => !member.roles.cache.some((role) => role.id === targetRole.id)).map(m => m.user.username)
const players = new Discord.MessageEmbed()
.setColor('#6B238E')
.setTitle("Players:")
.setDescription(members);
message.channel.send(players);
//console.log(members);
That's because your filter function is not returning whether the member has the role or not: it's returning a Promise which should resolve into a Role, which is interpreted as true and so everything passes the filter.
You don't actually need to fetch the role, since you only need to check if that ID is one of the roles from of the member: to do that you can use GuildMember.roles.cache.has(), which will return whether the roles collection has a role with that ID.
Here's how you can do it:
message.guild.members.cache.filter(member => member.roles.cache.has('701142571623252018'))
.map(member => member.user.username)
You can use filter and method collection.some for check if member has role.
bot.on('message', (message) => {
const targetRole = message.guild.roles.cache.get('ROLE ID');
if (!targetRole) return console.log('No role found')
const members = message.guild.members.cache.filter((member) => member.roles.cache.some((role) => role.id === targetRole.id)).map(m => m.user.username)
});
V2
const Discord = require('discord.js')
const bot = new Discord.Client();
bot.on('message', (message) => {
const targetRole = message.guild.roles.cache.get('648157497051447317');
if (!targetRole) return console.log('No role found')
const members = message.guild.members.cache.filter((member) => member.roles.cache.some((role) => role.id === targetRole.id)).map(m => m.user.username)
console.log(members)
});
bot.login('TOKEN HERE')

Checking the channel name

const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', (oldMessage, newMessage, role, args, guild) => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', message => {
if (message.content === '.') {
if (message.guild.channel === 'dot-wars') {
message.guild.members.forEach(member => {
var role = message.guild.roles.find(role => role.name === 'Dot Master!');
member.removeRole(role);
})
}
var role = message.guild.roles.find(role => role.name === 'Dot Master!');
message.member.addRole(role);
}
});
okay so what i want to do is when someone sends a '.' the bot will remove the 'Dot Master!' role from everyone in the server and then add the 'Dot Master!' role to the person that sent it, but only if it is in the 'dot-wars' channel.
A text channel has a name property for reading its name. However, make sure you're checking the channel the message was sent in, not the guild (Message#channel).
if (message.channel.name === 'dot-wars') {
...
}

Categories