创建可在模块中编辑的集合



我正在尝试创建一个不和游戏机器人。

我正在尝试制作一个集合,将用户的id存储为密钥,将其银行余额存储为值。但由于某种原因,它不起作用。我不知道为什么,

这是main.js

.....
const userValues = new Discord.Collection();
.....
client.on('message', message => {
var userid = message.author.id;
var messager = userValues.find(userid);

if (messager === false){
userValues.set(userid, 0);
};
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();

if(command === 'explore'){
client.commands.get('explore').execute(message, args, userValues);
}
});

这是explore.js

var currentBalance = userValues.get(userid);
userValues.set(userid, currentBalance + coins);
message.reply("n" + 'You searched a ' + choice + ' and found $' + coins);

好吧,我在您的代码中看到了一个主要问题。除此之外,您的代码中可能还有更多问题,但我将解决主要问题,因为我无法判断其他潜在问题是否只是您提供的代码的实际问题。

您正在执行userValues.find("a key"),这是对.find()方法的错误使用。.find()用于根据项的属性(如果项是对象(查找集合中的元素。但是在集合中,项目(值(本身是整数,因为它们代表用户的余额。您可以使用.get("a key").has("a key")来正确检查密钥是否在Collection中,但我将使用.has(),因为这就是它的目的。

你可能应该做什么:

const userValues = new Discord.Collection();
.....
client.on('message', message => {
var userid = message.author.id;

if (!userValues.has(userid)){
//Do this if userValues DOESN'T contain the user's ID and balance
userValues.set(userid, 0);
}
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();

if(command === 'explore'){
client.commands.get('explore').execute(message, args, userValues);
}
});

我建议在你的问题中更具描述性,而不是简单地说";它不起作用";。它怎么不起作用,你说的";不工作";?这是一个错误吗?它是否为每个用户保持0的平衡?如果没有这样重要的信息,我们怎么知道你遇到了什么问题?

相关资源:
https://discord.js.org/#/docs/collection/master/class/Collection?scrollTo=has

最新更新