[英]discord.js and node.js module not exporting correctly? returned statement not working
[英]Exporting/importing in node.js / discord.js
我目前正在用discord.js做一个discord机器人,因为在发现使用多个js文件非常困难之前,我没有没有html文件就没有编程过。 起初我以为可以使用进出口,但是Node还不支持。 我做了一些窥探,这就是我决定要做的事情:
const commandFunctions = require('./commands.js')();
const botconfig = require('./botconfig.json');
bot.on('message', async message => {
if (message.author.bot) { return; }
if (message.channel.type === 'dm') { return; }
messageArray = message.content.split(' ');
cmd = messageArray[0];
arg = messageArray.slice(1);
if (cmd.charAt(0) === prefix) {
checkCommands(message);
} else {
checkForWord(message);
}
});
function checkCommands(message) {
botconfig.commands.forEach(command => {
if (arg === command) {
commandFunctions.ping();
}
});
}
module.exports = function() {
this.botinfo = function(message, bot) {
let bicon = bot.user.displayAvatarURL;
let botembed = new Discord.RichEmbed()
.setColor('#DE8D9C')
.setThumbnail(bicon)
.addField('Bot Name', bot.user.username)
.addField('Description', 'Inject the memes into my bloodstream')
.addField('Created On', bot.user.createdAt.toDateString());
return message.channel.send(botembed);
}
this.roll = function(message) {
let roll = Math.floor(Math.random() * 6) + 1;
return message.channel.send(`${message.author.username} rolled a ${roll}`);
}
this.ping = function() {
return message.channel.send('pong');
}
}
"prefix": "+",
"commands": [
"botinfo",
"roll",
"ping"
]
我的目标是通过仅在json文件中添加一个单词以及在commands.js中与其连接的函数来使代码具有适应性。 在checkCommand函数中,它还应该以与命令相同的名称来触发该函数,现在我已将其设置为无论使用什么命令都触发ping,因为我在参数方面遇到了麻烦。 问题是命令功能根本没有被触发,请确保checkCommand函数出了问题。
对于this
指向返回对象的函数里面你必须使用调用它new
运营商:
const commandFunctions = new require('./commands.js')();
但是,这很违反直觉,因此您仅从“ commands.js”中导出对象即可:
module.exports = {
ping: function() { /*...*/ }
//...
};
然后可以轻松导入:
const commandFunctions = require('./commands.js');
commandFunctions.ping();
要执行命令,您无需加载json,只需检查该属性是否存在于commands对象中,即可:
const commands = require('./commands.js');
function execCommand(command) {
if(commands[command]) {
commands[command]();
} else {
commands.fail();
}
}
PS:全局变量( cmd
, arg
)是一个非常糟糕的主意,相反,您应该将值作为参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.