我觉得好像我不正确地将Currency导入/导出到Balance.js中。
我找到了一篇文章:-Discord.js currency to command handler
在我看来,我已经正确地遵循了,但是仍然出现getBalance未定义错误。
在过去的四天里,我一直在尝试各种方法,但是我却一无所获。
我相信这是由于我如何导出/导入货币集合
任何帮助将不胜感激,谢谢。
App.JS
const fs = require('fs');
const Discord = require('discord.js');
const { Prefix, Token } = require('./config.json');
const { Characters, CurrencyShop } = require('./dbObjects');
const { Op } = require('sequelize');
const client = new Discord.Client();
const currency = new Discord.Collection();
Reflect.defineProperty(currency, 'add', {
value: async function add(id, amount) {
const user = currency.get(id);
if (user) {
user.balance += Number(amount);
return user.save();
}
const newUser = await Characters.create({ character_id: id, balance: amount });
currency.set(id, newUser);
return newUser;
},
});
Reflect.defineProperty(currency, 'getBalance', {
value: function getBalance(id) {
const user = currency.get(id);
return user ? user.balance : 0;
},
});
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
};
client.once('ready', async () => {
const storedBalances = await Characters.findAll();
storedBalances.forEach(b => currency.set(b.user_id, b));
console.log(` Logged in as ${client.user.tag}!`);
});
client.on('message', async message => {
if (message.author.bot) return;
currency.add(message.author.id, 1);
return currency;
if (!message.content.startsWith(Prefix)|| message.author.bot) return;
const args = message.content.slice(Prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName);
if (!command) return;
try {
await command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
module.exports = { currency }
client.login(`${Token}`);
process.on('unhandledRejection', error => {
console.error('Unhandled promise rejection:', error);
})
Balance.JS
const Discord = require('discord.js');
const { Characters, CurrencyShop } = require('../dbObjects');
const { currency } = require('../app.js');
module.exports = {
name: "balance",
args: false,
async execute (message) {
const target = message.mentions.users.first() || message.author;
return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}`);
},
};
错误
TypeError: Cannot read property 'getBalance' of undefined
at Object.execute (C:\Users\Unknown\Bot\commands\balance.js:9:62)
at Client.<anonymous> (C:\Users\Unknown\Bot\app.js:54:17)
at Client.emit (events.js:310:20)
at MessageCreateAction.handle
(C:\Users\Unknown\node_modules\discord.js\src\
client\actions\MessageCreate.js:31:14)at Object.module.exports [as
MESSAGE_CREATE]
(C:\Users\Unknown\node_modules\discord.js\src\
client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket
(C:\Users\Unknown\node_modules\discord.js\src\
client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket
at WebSocketShard.onMessage (C:\Users\Unknown\node_modules\discord.js\src\
client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\Users\Unknown\node_modules\ws\lib\event-
target.js:125:16)
at WebSocket.emit (events.js:310:20)
at Receiver.receiverOnMessage
(C:\Users\Unknown\node_modules\ws\lib\websocket.js:800:20)
at Receiver.emit (events.js:310:20)
at Receiver.dataMessage
(C:\Users\Unknown\node_modules\ws\lib\receiver.js:436:14)
at Receiver.getData
(C:\Users\Unknown\node_modules\ws\lib\receiver.js:366:17)
at Receiver.startLoop
(C:\Users\Unknown\node_modules\ws\lib\receiver.js:142:22)
at Receiver._write
(C:\Users\Unknown\node_modules\ws\lib\receiver.js:77:10)
at doWrite (_stream_writable.js:403:12)
at writeOrBuffer (_stream_writable.js:387:5)
at Receiver.Writable.write (_stream_writable.js:318:11)
at TLSSocket.socketOnData
(C:\Users\Unknown\node_modules\ws\lib\websocket.js:875:35)
at TLSSocket.emit (events.js:310:20)
at addChunk (_stream_readable.js:286:12)
答案 0 :(得分:1)
好吧,花了一段时间后重现了环境...
我发现的问题是,在app.js
中声明module.exports之前,您正在“要求”命令/模块。这意味着balance.js
在“必填”时会得到一个空的映射,而不是{currency: currency}
。
在下面的示例中,此操作与您的“中断”代码相同。要解决此问题,您需要将require("./test2")
移至start()
,因为start()
是在module.exports
之后执行的。
test.js
const Discord = require('discord.js');
const currency = new Discord.Collection();
const test2 = require("./test2");
function start() {
test2.test();
}
module.exports = { currency: currency };
start();
test2.js
const { currency } = require("./test");
module.exports = {
test: () => {
console.log(require("./test"));
console.log(currency);
}
}
修复
要将其转换到您的环境中:您应将所有代码(除了require,常量和模块导出除外)移至以下位置:
const a = ....
const b = ....
const client = ...
// etc....
client.on("ready" () => {
// Put (almost) everything here
// code here will run after module.exports because client.login is executed after
});
module.exports = { currency }
client.login(`${Token}`);
process.on('unhandledRejection', error => {
console.error('Unhandled promise rejection:', error);
希望这会有所帮助:)