我正在尝试用Discord.js编写一个Discord bot。我使用官方指南在我的index.js文件中设置了动态命令处理。您可以在此处读取命令处理程序:
const fs = require('fs');
const lobby = require('./scripts/lobby');
const context = require('./context');
const { token, prefix } = require('./context');
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(
message,
args,
client,
lobby,
context
);
} catch (error) {
console.error(error);
message.reply('There was an error executing that command.');
}
});
命令作为JavaScript模块存储在单独的文件中。一个简单的示例是ping命令:
module.exports = {
name: 'ping',
description: 'Ping!',
execute(message, context) {
console.log(context.activeLang.ping[0]);
},
};
当我在index.js文件中将console.log(context.activelang.ping[0])
记录到控制台时,它会记录正确的值。当我在ping模块中执行此操作时,node崩溃,出现以下TypeError:
TypeError:无法读取未定义的属性“ping”
我不明白为什么我的命令脚本显然不能正确地访问context.js。如果有人对如何解决这个问题有建议,我会非常感激!
现在,context
实际上正在填充args
参数。参数名(在本例中为message
和context
)只是对应参数的占位符。它们的价值不是按它们的名字计算的,而是按它们出现的顺序计算的。
null
// example:
// this function, command, will trigger the given
// function and pass the argument b (1)
function command(func) {
var b = 1
func(b)
};
command((a, b, c) => {
// even though the arguments name was b, it's value is still tied to a
console.log(a)
});