gpt4 book ai didi

javascript - 如何使用 module.exports 从任何 .js 文件中获取值?

转载 作者:行者123 更新时间:2023-12-02 21:12:08 24 4
gpt4 key购买 nike

我对 JS 和编程都很陌生,所以请记住这一点进行解释。我知道这个问题的表述不太好,但我想不出如何更好地表述它,所以请随意编辑它。我正在使用discord.js 制作一个discord 机器人。我做了一个名为“测试”的命令。我的代码如下(在名为 test.js 的文件中):

module.exports = {
name: 'test',
description: 'Test command. Sends back "Test successful."',
prefixType: 'devPrefix',
execute(msg, args) {
if (!args.length){
msg.channel.send('Test successful.');
} else {
msg.channel.send('Test successful. You entered ' + args.length + ' argument(s).')
}
},
};

如何获取值 prefixType 并在我的主 index.js 文件中使用它?然而,该解决方案需要适用于文件夹中的任何文件(称为“命令”),而不仅仅是 test.js。

如果这有帮助,我将在主 index.js 文件中包含处理和执行命令的代码:

const Discord = require('discord.js');
const fs = require('fs'); //For commands (fs = file system)
const botClient = new Discord.Client;
const CONFIG = require('./config.json');

//Get the commands
botClient.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
botClient.commands.set(command.name, command);
}

botClient.once('ready', () => {
console.log('Bot online and ready.');
});

botClient.on('message', msg => {
if ((!msg.content.startsWith(CONFIG.prefix) && !msg.content.startsWith(CONFIG.devPrefix))
|| msg.author.bot) return;

const args = msg.content.slice(CONFIG.prefix.length).split(' ');
const commandName = args.shift().toLowerCase();

//If the command doesn't exist
if (!botClient.commands.has(commandName)){
msg.reply("That command does not exist. Do a.commands for a list of all commands");
return;
}

const command = botClient.commands.get(commandName);

try {
command.execute(msg, args);
} catch (error) {
console.error(error);
console.log('Error when trying to get and execute a command.');
msg.reply('There was an error trying to execute that command.');
}
});

谢谢

最佳答案

由于您将其导出到命令文件中(稍后需要并将其放入 botClient.commands 集合中),因此您可以在任何其他您有权访问 的地方访问 prefixType >客户端botClient.commands.get('test').prefixType 将为您提供该属性。

此外,您可以通过执行 message 从大多数 Discord.js 结构中访问 client 属性,例如 MessageUser。客户端user.client。由于您的命令集合已附加到您的客户端对象,因此您可以像上面的示例一样访问它。

关于javascript - 如何使用 module.exports 从任何 .js 文件中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61063686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com