【发布时间】:2020-12-08 20:06:57
【问题描述】:
我正在尝试使用discord.js 编写一个 Discord 机器人。我使用official guide 在我的 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 模块中这样做时,节点崩溃并出现以下类型错误:
TypeError: Cannot read property 'ping' of undefined
我不明白为什么我的命令脚本显然无法正确访问 context.js。如果有人对如何解决这个问题有建议,我将非常感激!
【问题讨论】:
标签: javascript node.js discord discord.js