【发布时间】:2020-07-18 16:20:06
【问题描述】:
我是 JS 和一般编程的新手,所以请记住这一点。我知道这个问题的表述不是很好,但我想不出如何更好地表述它,所以随意编辑它。我正在用 discord.js 制作一个不和谐的机器人。我做了一个名为“测试”的命令。 我的代码如下(在名为 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.');
}
});
谢谢
【问题讨论】:
-
require('test.js').prefixType? -
或
const { prefixType } = require('test') -
@terrymorse 谢谢,但这需要适用于任何文件,而不仅仅是 test.js(就像我在问题中所说的那样)。
-
@terrymorse 你确定吗?能不能不用类似
require(`./commands/${file}`);的东西@ -
@cs09 你是对的,你可以用字符串变量指定需要的路径。所以
const { prefixType } = require(filePath)会起作用。
标签: javascript node.js visual-studio-code discord.js