Why is command.data undefined when all of my commands are exporting data objects in discord.js?

Viewed 44

So currently I have a bot that uses discord.js and every time I try to use my deploy-commands.js file, I get an undefined error that says Cannot read properties of undefined (reading 'name') (when reading command.data.name). This has confused me because apparently, from reading other articles similar to this one, it's usually due to someone having a file that does not export a data object in their commands folder; however, all of mine do. What can I do to fix this?

my deploy-commands.js file:

const fs = require('node:fs');
const path = require('node:path');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, token } = require('./config.json');

const rest = new REST({ version: '9' }).setToken(token);

const commands = [];
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    commands.push(command.data.toJSON());
}

const buttonCommands = [];
const buttonCommandsPath = path.join(__dirname, 'buttonCommands');
const buttonCommandFiles = fs.readdirSync(buttonCommandsPath).filter(file => file.endsWith('.js'));

for (const file of buttonCommandFiles) {
    const filePath = path.join(buttonCommandsPath, file);
    const command = require(filePath);
    buttonCommands.push(command);
}

module.exports = { buttonCommands };


(async () => {
    try {
        console.log('Started refreshing application (/) commands.');

        await rest.put(
            Routes.applicationCommands(clientId),
            { body: commands },
        );

        console.log('Successfully reloaded application (/) commands.');
    } catch (error) {
        console.error(error);
    }
})();

image of all of my commands for reference: click here

if it's needed, here is also a link to a sourcebin that shows the code for all of these commands and my index.js file: https://srcb.in/mtqWFVLAeN

2 Answers
module.exports = { buttonCommands };

It looks like here you are only exporting buttonCommands, but not commands.

This is fixed now-- the core of the problem was I just needed to make my commands not require index.js. I made a new js file and put all my variables in a class in there and just exported/required the class instead.

Related