我试图使用node.js
来制造一个经济上不和谐的机器人,我试图将这些命令移动到模块中,这样我就可以拥有一个通用/动态的命令处理程序。如何引用在命令模块中的主文件中创建的货币集合和模型?
index.js
文件:
const currency = new Discord.Collection();
//defining methods for the currency collection
Reflect.defineProperty(currency, 'add', {
/* eslint-disable-next-line func-name-matching */
value: async function add(id, amount) {
const user = currency.get(id);
if (user) {
user.balance += Number(amount);
return user.save();
}
const newUser = await Users.create({ user_id: id, balance: amount });
currency.set(id, newUser);
return newUser;
},
});
Reflect.defineProperty(currency, 'getBalance', {
/* eslint-disable-next-line func-name-matching */
value: function getBalance(id) {
const user = currency.get(id);
return user ? user.balance : 0;
},
});
(在子文件夹中) balance.js
module.exports = {
name: 'balance',
description: 'get balance',
execute(message, args) {
const target = message.mentions.users.first() || message.author;
return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}`);
},
};
它会引发货币错误,因为它没有定义。但是,我不知道如何引用我在index.js
中创建的货币集合,它也有为其创建的方法。
提前谢谢你。
发布于 2020-08-28 13:08:40
要做到这一点,可以将Collection
附加到Client
。有点像
Client.currency = new Discord.Collection()
每次引用集合时,您都会运行currency
,而不是执行Client.currency
。
至于跨文件访问通货对象,我会向您的execute
方法添加另一个参数,如下所示:
module.exports = {
name: 'balance',
description: 'get balance',
execute(client, message, args) { // Notice the added "client"
const target = message.mentions.users.first() || message.author;
return message.channel.send(`${target.tag} has ${client.currency.getBalance(target.id)}`); // Added "client." in front of "currency", because currency is a property of your client now
},
};
然后,在执行execute
方法时,将运行execute(Client, message, arguments);
。然后,您的客户端将被传递到命令中,并在其中可用。
https://stackoverflow.com/questions/63640666
复制相似问题