简体   繁体   中英

Getting roles of mentioned user

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM