Home > other >  Cannot read properties of undefined (reading 'cache') with role
Cannot read properties of undefined (reading 'cache') with role

Time:01-25

i work on a discord bot but i have a problem when i want to know if user who clicked on button have a role

if (interaction.customId === "button_one") {
            responseembed.description = `\u200b\n**${config.responses.response_1}**\n\u200b\n`

            if (interaction.user.roles.cache.has(config.lspd_role_id)) {
                const logchannel = interaction.guild.channels.cache.get(config.lspd_channel_id)
            }else if (interaction.user.roles.cache.has(config.lssd_role_id)) {
                const logchannel = interaction.guild.channels.cache.get(config.lssd_channel_id)
            }
            
            logchannel.send({ embeds: [PriseService], ephemeral: false })
            // let invitecutie = new MessageButton()
            //     .setLabel("Invite Link")
            //     .setStyle("url")
            //     .setURL("Link")
            // let buttonRow = new MessageActionRow()
            //  .addComponent(invitecutie)
            //!If You Want Button in the Response remove // from the the Above 6 lines
            return interaction.reply({ embeds: [responseembed], ephemeral: true })//If you want to send link button add ,component: buttonRow after the ephermeral: true declaration
        } 

but i have this error :

if (interaction.user.roles.cache.has(config.lspd_role_id)) { ^

TypeError: Cannot read properties of undefined (reading 'cache')

CodePudding user response:

User's doesn't have roles in cache, only GuildMember's have.

Instead of getting users' roles, you must fetch him as guildmember (member) and then search his roles in cache.

const user = interaction.user
const member = interaction.guild.members.fetch({ user: user })

if (member.roles.cache.has(config.lspd_role_id)) return true
// output: true

if (user.roles.cache.has(config.lspd_role_id)) return true
// expected output: true
// output: TypeError: Cannot read properties of undefined (reading 'cache')

CodePudding user response:

You must access the roles from a GuildMember object. You can get the member with BaseInteraction#member

if (interaction.member.roles.cache.has(id)) {
  // ...
}
  • Related