user13524876
user13524876

Reputation:

Get variables from another file node js

I'm trying to make a Discord bot using Discord.js, and in the guide in the documentation it says to create a separate file for each command.

I'm currently having an issue where none of the data in the files are available when I run the command deployment. I have tried copying everything from the guide.

Here is my code and output:

ping.js

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

const data = new SlashCommandBuilder()
    .setName('ping')
    .setDescription('Replies with pong!')

deploy-commands.js

const { REST, Routes } = require('discord.js');
require('dotenv').config();
const fs = require('node:fs');
const { ClientID, GuildID } = require("./config.json");

const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

console.log("Hello World!")

// This is where the error happens
for (const file of commandFiles) {
    console.log(file)
    const command = require(`./commands/${file}`);
    console.log(command); // I dont know why this is empty
    console.log(command.data); // command.data should not be undefined
    commands.push(command.data.toJSON());
}

const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);

(async () => {
    try {
        console.log(`Started refreshing ${commands.length} application (/) commands.`);

        const data = await rest.put(
            Routes.applicationGuildCommands(ClientID, GuildID),
            { body: commands },
        );

        console.log(`Successfully reloaded ${data.length} application (/) commands.`);
    } catch (error) {
        console.error(error);
    }
})();

Output

Hello World!
echo.js
{}
undefined
C:\Users\danho\Coding\node\DiscordBot\deploy-commands.js:16
        commands.push(command.data.toJSON());
                                   ^

TypeError: Cannot read properties of undefined (reading 'toJSON')
    at Object.<anonymous> (C:\Users\danho\Coding\node\DiscordBot\deploy-commands.js:16:29)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47

As I said, this is almost an exact copy of the code taken from their official example here

I have no clue what could be causing this issue, so any tips/help would be much appreciated!

Upvotes: 2

Views: 91

Answers (1)

akpi
akpi

Reputation: 197

In ping.js, use:

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

module.exports = {
  data: new SlashCommandBuilder()
    .setName('ping')
    .setDescription('Replies with pong!');
};

Upvotes: 0

Related Questions