首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从另一个文件节点js获取变量。

问从另一个文件节点js获取变量。
EN

Stack Overflow用户
提问于 2022-09-22 03:48:51
回答 1查看 65关注 0票数 2

我试图使用Discord.js制造一个不和谐的机器人,在文档指南中,它说要为每个命令创建一个单独的文件。

我目前遇到一个问题,在运行命令部署时,文件中的任何数据都不可用。我试过抄袭指南上的所有东西。

下面是我的代码和输出:

ping.js

代码语言:javascript
复制
const { SlashCommandBuilder } = require('discord.js');

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

deploy-commands.js

代码语言:javascript
复制
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);
    }
})();

输出

代码语言:javascript
复制
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

正如我所说的,这几乎是从他们的官方示例这里中摘取的代码的精确副本。

我不知道是什么可能导致这个问题,所以任何提示/帮助将不胜感激!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-13 19:26:35

在ping.js中,请使用:

代码语言:javascript
复制
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('ping')
    .setDescription('Replies with pong!');
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73809149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档