Getting roles of mentioned user - javascript

Working on a marriage system for my Discord bot but I am struggling to find out of a user has the "married" role already.
const Discord = require('discord.js');
module.exports = {
name: "marry",
aliases: ['m'],
description: "marry someone",
async run(client, message, args) {
const user = message.mentions.users.first() || client.users.get(args[0]);
let marriedRole = message.guild.roles.cache.find(r => r.name === "Married");
let singleRole = message.guild.roles.cache.find(r => r.name === "Single");
let proposerID = message.author.id;
let proposerName = message.author.username;
if (user.roles.cache.some(marriedRole)) {
let embed = new Discord.MessageEmbed()
.setDescription(`Sorry **${user.tag}**, is already married!`);
let messageEmbed = await message.channel.send({ embeds: [embed] });
}
if (message.member.roles.cache.some(role => role.name === 'Single')) {
let embed = new Discord.MessageEmbed()
.setDescription(`**${user.username}**, **${message.author.username}** is asking for your hand in marriage, would you like to accept?`);
let messageEmbed = await message.channel.send({ embeds: [embed] });
messageEmbed.react('✅');
messageEmbed.react('❌');
}
if (message.member.roles.cache.some(role => role.name === 'Married')) {
let embed = new Discord.MessageEmbed()
.setDescription(`Sorry **${message.author.username}**, but you are already married!`);
let messageEmbed = await message.channel.send({ embeds: [embed] });
}
}
}
I keep getting the error
if (user.roles.cache.some(marriedRole)) {
^
TypeError: Cannot read properties of undefined (reading 'cache')

By using message.mentions.users.first(), you are getting a User object in return which doesn't have the roles property. Instead, you need the GuildMember object. To get it, all you have to do is change the part where you declare the user variable to:
const user = message.mentions.members.first() || client.users.get(args[0]);
Answer from Zsolt Meszaros
Since, if there is no mention in the message, message.mentions.members.first(), so keep that in mind. client.users.get(args[0]) would also just get a User object, so instead of using that, you can use this:
const user = message.guild.members.cache.get(args[0])

Related

How do i got from user to GuildMember

So im making a ban slash command using .addUserOption but when i try to get the permissions from the .addUserOption so that the bot doesnt crash when trying to ban an admin i get an error. I already know why, you cant get permissions from a user, only a GuildMember, so how would i go from user to GuildMember?
CODE: (if needed)
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageEmbed } = require('discord.js')
module.exports = {
data: new SlashCommandBuilder()
.setName("ban")
.setDescription("Bans the specified user!")
.addUserOption((option) =>
option
.setName("user")
.setDescription('Who do you want to ban?')
.setRequired(true)
)
.addStringOption((option) =>
option
.setName('reason')
.setDescription("Whats the reason youre banning this user?")
),
async execute(client, interaction) {
if (client.cooldowns.has(interaction.user.id)) {
let cooldownEmbed = new MessageEmbed()
.setTitle("Please wait for the cooldown to end.")
.setDescription("This is so that the bot doesnt overload")
.setColor("RED")
.setFooter("The cooldown is 5 sec")
.setTimestamp()
interaction.reply({ embeds: [cooldownEmbed], ephemeral: true });
} else {
const user = interaction.member
const permission = user.permissions.has('BAN_MEMBERS');
let embed = new MessageEmbed()
.setTitle("❌️ | You dont have the permissions to use this command.")
if(!permission)
return interaction.reply({embeds: [embed]})
const tgt = interaction.options.getUser('user')
let permsEmbed = new MessageEmbed()
.setTitle("The user you are trying to ban is an Administrator!")
.setColor("RED")
if (tgt.permissions.has('BAN_MEMBERS')) return interaction.reply({ embeds: [permsEmbed]})
const reason = interaction.options.getString('reason') || "No reason specified"
client.cooldowns.set(interaction.user.id, true);
setTimeout(() => {
client.cooldowns.delete(interaction.user.id);
}, client.COOLDOWN_SECONDS * 1000);
}
}
}
I checked CollinD's suggestion and i managed to fix the problem. Heres the code if anyone else runs into this problem and needs an answer.
CODE:
const tgt = interaction.options.getUser('user');
let permsEmbed = new MessageEmbed()
.setTitle('The user you are trying to ban is an Administrator!')
.setColor('RED');
const guildMember = interaction.guild.members.cache.get(tgt.id);
if (guildMember.permissions.has('BAN_MEMBERS'))
return interaction.reply({ embeds: [permsEmbed] });

The bot crashes whe3n i use user id

const Discord = require('discord.js');
const config = require('../config.json');
const { Permissions } = require('discord.js');
module.exports.run = async (client, message, args) => {
if(!message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS, true)) return message.channel.send('You can\'t use that!')
if(!message.guild.me.permissions.has(Permissions.FLAGS.BAN_MEMBERS, true)) return message.channel.send('I don\'t have the permissions.')
const member = message.mentions.members.first();
if(!args[0]) return message.channel.send('Please specify a user');
let reason = args.slice(1).join(" ");
if(!reason) reason = 'Unspecified';
message.guild.members.unban(`${member}`, `${reason}`)
.catch(err => {
if(err) return message.channel.send('Something went wrong')
})
let banembed = new Discord.MessageEmbed()
.setTitle('Member Unbanned')
.addField('User Unbanned', member)
.addField('Unbanned by', message.author)
.addField('Reason', reason)
.setFooter('Time Unbanned', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}
You're using a message.mentions.members.first() which is referring to a pinged person. To use their ID's you can use .fetch or cache.get
const member = await message.guild.members.fetch(args[0])
const member = await message.guild.members.cache.get(args[0])
also you can use them on the same line using or ||
const member = message.mentions.members.first() || await message.guild.members.fetch(args[0]) || await message.guild.members.cache.get(args[0])
I only don't know if its going to work with unban because the bot and the user should on the same server

Typescript: Cannot read properties of null (reading "add")

I wanted to create a role command in discord.js v13.6, but... It cannot read the line with adding a role. It gives the Typescript: Cannot read properties of null (reading "add") error. How do I fix it?
exports.run = async (client, message, args) => {
const ms = require("ms");
//!tempmute #user 1s/m/h/d
let tomute = message.mentions.users.first();
if (!tomute) return message.reply("Couldn't find user.");
let muterole = message.guild.roles.cache.find(role => role.name === "admin");
//start of create role
if (!muterole) {
try {
muterole = await message.guild.roles.create({
name: "admin",
color: "#ff0000",
permissions: []
})
message.guild.channels.cache.forEach(async (muterole, id) => {
await muterole.overwritePermissions({
ADMINISTRATOR: true
})
});
} catch (e) {
console.log(e.stack);
}
}
await (tomute.roles.add(muterole));
message.reply(`<#${tomute.id}> стал админом`);
}
let tomute = message.mentions.users.first();
This returns a user object which doesn't have role manager. You need a guild member object to be able to access the roles which can be obtained by replacing users with members in the above snippet
let tomute = message.mentions.members.first();
read about it here
Instead of using
let tomute = message.mentions.users.first();
Use
let tomute = message.mentions.members.first();
You can also use
let tomute = message.guild.members.cache.get(args[0]) //to use its ID
Or even use it at once
let tomute = message.mentions.members.first() || message.guild.members.cache.get(args[0])
as Arnav Mentioned. Using user return a user object which doesn't have role manager.

I'm trying to add a user to a role when reacting to an embed and won't add them

I made a command when using an embed the bot reacts to it and when anyone else reacts to it, it will add them to a rule. But it isn't adding the user to the role and I'm unsure why.
const {MessageEmbed} = require("discord.js");
module.exports = {
name: "reactionrole",
async execute(message, args, client) {
const channel = '914676864004554803';
const memberRole = message.guild.roles.cache.find(role => role.name === "Members");
const emojireact = '👍';
let embed = new MessageEmbed()
.setColor("#e42643")
.setTitle("MineCraft Server Rules")
.setDescription(
"To keep our server safe we need a few basic rules for everyone to follow!"
)
.setFooter("Please press 👍 to verify and unlock the rest of the server!")
let messageEmbed = await message.channel.send({ embeds: [embed] });
messageEmbed.react(emojireact);
client.on('messageReactionAdd', async(reaction, user, GUILD_MESSAGES_REACTIONS) => {
if(reaction.message.partial) await reaction.message.fetch();
if(reaction.partial) await reaction.fetch();
if(user.bot) return;
if(!reaction.message.guild) return;
if(reaction.message.channel.id === channel) {
if(reaction.emoji.name === emojireact) {
await reaction.message.guild.members.cache.get(user.id).roles.add(memberRole);
}
}else {
return;
}
});
}
}
The command shows the embed and the bot reacts but the user isn't added.
Not sure how are you not getting a ReferenceError but you are passing an unknown variable to the parameter.At .add(Members), I don't see Members defined anywhere in the code you sent.

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.

Categories