![](/img/trans.png)
[英]How to get value of a module.exports description in another file [Discord.js]
[英]How to get a value from any .js file with module.exports?
我是 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
集合中,因此您可以在任何其他可以訪問您的client
的地方訪問prefixType
。 botClient.commands.get('test').prefixType
將為您提供該屬性。
此外,您可以通過執行message.client
或user.client
從大多數 Discord.js 結構(如Message
或User
)訪問client
屬性。 由於您的命令集合已附加到您的客戶端 object,因此您可以像上面的示例一樣訪問它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.