【发布时间】:2018-03-20 01:36:38
【问题描述】:
所以我一直在使用 Discord.JS 库开发 Discord 机器人,但遇到了问题。很确定这个问题与 Javascript 和 Discord.JS 更相关,所以我会在这里询问并希望得到一些帮助。
我有一个名为 commandManager.js 的文件,其中包含我所有的基本命令功能。其中之一是从 /commands/ 文件夹中自动加载命令,并根据它们的类别将它们分配给一个数组(通过导出在命令中指定)。
global.userCommands = {};
global.modCommands = {};
global.adminCommands = {};
global.ownerCommands = {};
exports.init = function(bot)
{
fs.readdir("./commands/", (error, files) =>
{
if (error)
{
logger.error(error);
}
files.forEach(file =>
{
let commandFile = require(`../commands/${file}`);
let commandName = file.split(".")[0];
if (commandFile.info.category == "User")
{
userCommands[commandName] = commandFile;
}
else if (commandFile.info.category == "Mod")
{
modCommands[commandName] = commandFile;
}
else if (commandFile.info.category == "Admin")
{
adminCommands[commandName] = commandFile;
}
else if (commandFile.info.category == "Owner")
{
ownerCommands[commandName] = commandFile;
}
else
{
logger.warn("Could not add the command " + commandName + " to any of the categories");
}
});
logger.info("Loaded " + files.length + " command(s)");
});
}
然后在此之后,我可以在消息位上使用实际机器人中的命令,如下所示:
exports.run = function(bot, msg)
{
const args = msg.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
const cleanCommand = command.slice(config.prefix.length);
if (msg.author.bot)
{
return;
}
else if (msg.content.indexOf(config.prefix) !== 0)
{
return;
}
else if (has.call(userCommands, cleanCommand))
{
msg.reply("user");
}
else if (has.call(modCommands, cleanCommand))
{
}
else if (has.call(adminCommands, cleanCommand))
{
}
else if (has.call(ownerCommands, cleanCommand))
{
}
else
{
msg.reply(`that command does not even exist! You can say ${config.prefix}help for a list of commands!`);
}
}
所以当我说命令例如“ping”时,它应该用 msg.reply("user") 回复,但它却说它根本不存在。我声明 has 是一个像这样的全局变量,以防你好奇。
global.has = Object.prototype.hasOwnProperty;
如果你想查看命令如下:
exports.info =
{
name: "Ping",
permission: 10,
category: "User",
about: "Makes the bot respond with pong, useful to see if the bot is working."
};
exports.run = function(msg)
{
msg.channel.send("Pong!");
}
100% 欢迎任何提示、参考、示例或只是简单的勺子喂食。另外,如果您想分享一些更好的技术来做我正在做的事情,请告诉我,因为我只是 JS 的初学者。
【问题讨论】:
-
为什么不
userCommands[cleanCommand]??类别应该有什么用处? -
好吧,如果我以后要做一个命令列表,类别是我将它们分开的想法。不知道为什么不对你诚实。那么对于类别有什么更好的想法,或者我可以做些什么来获得相同的结果?
标签: javascript discord