Search code examples
javascriptdiscord.jstypeerror

"Cannot read properties of null" Following official DiscordJS (v14) guide


I am attempting to create a slash command for banning a user. I first tried simply porting my prefix command, however this didn't work. So I decided to check out the DiscordJS guide. On the guide website I found this : https://discordjs.guide/slash-commands/parsing-options.html#command-options

Now, I basically copied and pasted it to test out whether this would work or not, but it didn't. This is what my ban command's file looks like (src/Commands/Slash/Moderation/Ban.js) :

const { SlashCommandBuilder, PermissionFlagsBits } = require('discord.js');
const Logger = require('@utils/Logger');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ban')
        .setDescription('Select a member and ban them.')
        .addUserOption(option =>
            option
                .setName('target')
                .setDescription('The member to ban')
                .setRequired(true))
        .addStringOption(option =>
            option
                .setName('reason')
                .setDescription('The reason for banning'))
        .setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
        .setDMPermission(false),

    async execute(interaction) {
        try {
            const target = interaction.options.getUser('target');
            const reason = interaction.options.getString('reason') ?? 'No reason provided';

            await interaction.reply(`Banning ${target.username} for reason: ${reason}`);
        } catch (error) {
            Logger.error(error);
            await interaction.reply({
                content: 'An error occurred while attempting to execute this command! Please report this to the developers.',
                ephemeral: true,
            });
        }
    },
};

This should work in theory, but for some reason it returns an error : [11:47:07] [ERROR] TypeError: Cannot read properties of null (reading 'username')

I have tried to fix it, and I have also made sure this isn't an issue because of incorrect intents. Please help!


Solution

  • I was able to fix the issue, and turns out it wasn't a problem with the code, as changing the token fixed it. The other application has the same guild permissions and the same intents, and in the end I don't really know what was causing it in the first place.

    Hope this helps anyone else who might be facing this issue!