javascriptnode.jsdiscord.jsnulldiscord-interactions

Discord.js slash commands .getMember() and .getChannel() are returning null even though the options are required


EDIT/SOLUTION: The Guild Members intent needs to be enabled on the developer portal and your bot's client must log in with const client = new Client({ intents: [..., GatewayIntentBits.GuildMembers] });

I have a Discord.js bot with this command definition:

const { SlashCommandBuilder } = require("discord.js");

module.exports = {
    data: new SlashCommandBuilder()
        .setName('removerole')
        .setDescription("Remove a role from a user. Officer use only.")
        .addUserOption(option =>
            option.setName('target')
                .setDescription("The user whose role should be removed.")
                .setRequired(true))
        .addChannelOption(option =>
            option.setName('gamechannel')
                .setDescription("The channel that is associated with the role to be removed.")
                .setRequired(true)),


    async execute(interaction) {
        await interaction.deferReply({ ephemeral: true });

        //collect member
        const member = interaction.options.getMember('target');
        console.log(`member is ${member}`);
        console.log(`user is ${interaction.options.getUser('target')}`);
        
        //rest of function...
    }
}

When I input this...

enter image description here

...this is printed:

member is null
user is null

And the rest of this function that relies on these variables throws an error because it's trying to read a value of a null. The slash command options are required, so they should have a value, but getUser() and getMember() are still returning null. I know I am missing something but I've changed it to be as close to the guide as possible which should work.

Why are the values null?


Solution

  • Make sure you enable the required intents, namely the GuildMembers and whichever other data you are using.

    Which intents are available

    What are intents