【发布时间】:2021-01-29 05:08:04
【问题描述】:
所以我正在尝试设置一个命令来使用存储在 json 文件中的信息来查看您拥有的糖果数量。它似乎没有正确读取信息。
这里是命令文件
const fs = require('fs');
const candyAmount = JSON.parse(fs.readFileSync('./candyheld.json', {encoding:'utf8'}));
const { prefix } = require('../../config.json');
module.exports = {
name: 'candy',
description: 'Displays the amount of candy the user has.',
execute (message, args) {
if (!candyAmount[message.author.id]) return message.channel.send(`You haven\'t started the event yet! Type ${prefix}trickortreat to start!`);
const { candyStored } = candyAmount[message.author.id].candyStored;
message.channel.send(`You have ${candyStored} pieces of candy!`);
},
};
这是 json 文件包含信息时的样子
{"ID":{"candyStored":5}}
我已经删除了实际的 ID 号,并将其替换为只是为了这一刻的单词。实际数字在代码中。
trickortreat 命令文件
const fs = require('fs');
const candyAmount = JSON.parse(fs.readFileSync('./candyheld.json', {encoding:'utf8'}));
module.exports = {
name: 'trickortreat',
description: 'Special Halloween command',
execute(message, args) {
if (!candyAmount[message.author.id]) {
candyAmount[message.author.id] = {
candyStored: 5
}
fs.writeFile('./candyheld.json', JSON.stringify(candyAmount), err => {
if (err) console.error(err);
});
return message.channel.send('For starting the event, you have been given 5 pieces of candy!');
}
// Stores a random number of candy from 1-3
let candy = Math.floor(Math.random() * 3 + 1);
// Sets the possible messages to be received
let trickortreatmessage = [
'The scarecrow standing behind you jumps out at you and makes you drop all your candy!',
`${message.guild.members.cache.random()} was nice enough to give you Candy! You got ${candy} pieces of candy!`,
`Oh no you asked ${message.guild.members.cache.random()} for Candy and they decided to egg you instead!`
]
// Store one of the random messages
const trickortreat = trickortreatmessage[Math.floor(Math.random() * trickortreatmessage.length)];
if (trickortreat == trickortreatmessage[0]) {
candyAmount[message.author.id].candyStored = 0;
} else if (trickortreat == trickortreatmessage[1]) {
candyAmount[message.author.id].candyStored = candyAmount[message.author.id].candyStored + candy;
}
fs.writeFile('./candyheld.json', JSON.stringify(candyAmount), err => {
if (err) console.error(err);
});
message.channel.send(trickortreat);
},
};
【问题讨论】:
-
您是否尝试过像使用
config.json一样要求candyheld.json? -
这表明什么是错误的?
-
@ericgio 这样做后,我得到“你有未定义的糖果!”。
-
@kmoser 它没有更新它看到的内容。文件中的数字在它应该改变的时候发生了变化,但代码没有读取它。例如,如果那里没有信息,则会弹出说使用 /trickortreat 开始。之后,json 文件会更新以显示我在上面粘贴的信息。但是当我之后再次使用 /candy 命令时,它仍然告诉我必须使用该命令才能启动。如果我用 5 块糖果启动机器人并添加 1 块,它仍然说只有 5 块
-
@QuazArxx:那是因为你在对对象进行解构和索引。尝试
const { candyStored } = candyAmount[message.author.id];或const candyStored = candyAmount[message.author.id].candyStored;
标签: javascript node.js json discord discord.js