【发布时间】:2021-06-01 07:02:50
【问题描述】:
我正在使用 javascript (discord.js) 编写一个不和谐机器人。
我使用 json 文件来存储我的数据,当然总是需要最新的数据。
我执行以下步骤:
- 我启动机器人
- 我运行一个函数,每次发送消息时都需要 config.json 文件
- 我增加了用户从他发送的消息中获得的 xp
- 我在 config.json 中更新了用户 xp
- 我记录数据
所以现在在第一次记录之后(也就是发送第一条消息),我在启动机器人之前获得了 json 文件中的数据(有意义)。但是在发送第二条消息后,我预计 xp 值会比以前更高,因为数据应该已经更新,文件新加载并再次记录数据。
(是的,我每次都会更新文件。当我自己查看文件时,数据总是最新的)
那么第二次要求文件后没有更新文件有什么原因吗?不需要重新加载文件吗?
这是我的代码:
function loadJson() {
var jsonData = require("./config.json")
//here I navigate through my json file and end up getting to the ... That won't be needed I guess :)
return jsonData
}
//edits the xp of a user
function changeUserXP(receivedMessage) {
let xpPerMessage = getJsonData(receivedMessage)["levelSystemInfo"].xpPerMessage
jsonReader('./config.json', (err, data) => {
if (err) {
console.log('Error reading file:',err)
return
}
//increase the users xp
data.guilds[receivedMessage.guild.id].members[receivedMessage.author.id].xp += Number(xpPerMessage)
data.guilds[receivedMessage.guild.id].members[receivedMessage.author.id].stats.messagesSent += 1
fs.writeFile('./test_config.json', JSON.stringify(data, null, 4), (err) => {
if (err) console.log('Error writing file:', err)
})
})
}
client.on("message", (receivedMessage) => {
changeUserXP(receivedMessage)
console.log(loadJson(receivedMessage))
});
我希望代码有帮助:)
如果我的问题不够准确,或者您还有其他问题,请随时发表评论
感谢您的帮助
【问题讨论】:
-
我强烈建议不要使用 JSON 来保存用户数据,它会经常擦除自己并且不稳定。我强烈推荐使用 SQL 或 MongoDB
-
@JoeMoore 是的,我知道这不是最好的解决方案 :(
-
嗯非常好!如果你愿意,我可以加你,当我有任何问题时,我会问你。但首先我会尝试自己进入它,以免浪费您的时间
-
当然,很乐意提供帮助 - 我的不和谐在我的个人资料中
标签: javascript json discord.js require