Home > Software engineering >  TypeError: Cannot read properties of undefined (reading 'has')
TypeError: Cannot read properties of undefined (reading 'has')

Time:12-30

I'm trying to do a clear command on Discord.js v14, but it keeps telling this error:

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

Here's the code:

const { SlashCommandBuilder, Embed, EmbedBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('clear')
        .setDescription("Delete messages")
        .addIntegerOption(option => option.setName('messages').setDescription('Messages to delete').setRequired(true)),
    async execute(interaction) {
        const messages = interaction.options.getInteger('messages');
        
        if(!interaction.user.id.permissions.has(PermissionsBitField.Flags.ManageMessages)){
            interaction.reply({ content: "You can't send messages!", ephemeral: true} )
        }
        
    }
}

CodePudding user response:

interaction.user.id gives you a string containing the id of the user who ran the slash command. To check for the permissions, you need the GuildMember data of the user which you can access by using interaction.member. So, your fixed code would look like this:

const { SlashCommandBuilder, Embed, EmbedBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('clear')
        .setDescription("Delete messages")
        .addIntegerOption(option => option.setName('messages').setDescription('Messages to delete').setRequired(true)),
    async execute(interaction) {
        const messages = interaction.options.getInteger('messages');
        
        if(!interaction.member.permissions.has(PermissionsBitField.Flags.ManageMessages)){
            interaction.reply({ content: "You can't send messages!", ephemeral: true} )
        }
        
    }
}
  • Related