javascript - 在 node.js / discord.js 中导出/导入
问题描述
我目前正在使用 discord.js 制作一个不和谐的机器人,因为在我发现使用多个 js 文件非常困难之前,我还没有在没有 html 文件的情况下进行编程。起初我认为使用导入和导出会起作用,但 Node 尚不支持它。我做了一些窥探,这就是我决定做的:
索引.js
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();
}
});
}
命令.js
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');
}
}
botconfig.json
"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,只需检查该属性是否存在于命令对象中,:
const commands = require('./commands.js');
function execCommand(command) {
if(commands[command]) {
commands[command]();
} else {
commands.fail();
}
}
PS:全局变量 ( cmd
, arg
) 是一个非常非常糟糕的主意,您应该将值作为参数传递。
推荐阅读
- flutter - 颤振我如何改变水龙头上容器的颜色?
- css - 如何仅使用 CSS 覆盖一个元素上的父类?
- firebase - 我应该使用 Firebase 匿名登录来保护我的数据吗?
- java - 如何在 Spring Boot 中捕获 HikariPool 初始化期间发生的异常?
- highcharts - 屏幕阅读器无法访问 Highcharts 圆环图
- vue.js - VueJS (CDN) 在 Safari 浏览器上无法正常工作
- javascript - discord.js 'guildMemberAdd' 事件在打开 Intents 后仍不起作用
- snowflake-cloud-data-platform - 存储过程 SQL 编译错误中的执行错误:Statement.execute 中的标识符“TEST3”无效
- php - Laravel 在服务中使用路由助手
- php - 如何为 paypal 沙盒帐户设置 webhook?