【问题标题】:Json file updates but bot reads the old file?Json文件更新但不读取旧文件?
【发布时间】:2021-06-25 17:28:56
【问题描述】:

所以我创建了一个简单地从 JSON 文件中添加或删除 ID 的命令。这个 JSON 只是白名单用户的一个小型数据库。

该命令运行良好,并且 JSON 文件得到更新,但每次调用该命令再次对其进行编辑时,它都不会读取新版本,而是读取未编辑的旧版本。

所以我猜我需要为机器人更新它,但我不知道该怎么做。

任何人都知道这是如何发生或为什么会发生并有解决方案吗?这是命令代码:

else if (command === 'whitelist') {
    const user = msg.mentions.users.first();
    if (!user) return msg.reply('Please mention a user!')
    const tester = require('./whitelist.json')
    const test = Object.values(tester.newdata).find(object => object.ID === msg.author.id)
    if (!test) return msg.reply("Sorry you can't use this!");
    if (test) {
        const json = require('./whitelist.json')
        const item = Object.values(json.newdata).find(object => object.ID === user.id)
        if (item) {
            msg.reply("Remove mentioned user from whitelist?")
            msg.react('????').then(r => {
                msg.react('????');
            });
            msg.awaitReactions((reaction, user) => user.id == msg.author.id && (reaction.emoji.name == '????' || reaction.emoji.name == '????'), {
                max: 1,
                time: 30000
            }).then(collected => {
                if (collected.first().emoji.name == '????') {
                    let rawdata = fs.readFileSync('./whitelist.json');
                    let data = JSON.parse(rawdata);
                    delete data.newdata[user]
                    fs.writeFileSync("./whitelist.json", JSON.stringify(data, null, 2), (err) => {
                        if (err)
                            embed = new Discord.MessageEmbed()
                            .setTitle('Error report')
                            .addField(`Logged error:`, err, false)
                            .addField(`Server:`, `${msg.guild}`, false)
                            .addField(`Command:`, `${command} ${commandArgs}`, false)
                            .setColor('#0099ff');
                        webhookClient.send(embed)
                    })
                    msg.reply("Removed user!")
                } else
                    msg.reply('Operation canceled.');
            }).catch(() => {
                msg.reply('No reaction after 30 seconds, operation canceled');
            });
            return
        }
        if (!item) {
            let rawdata = fs.readFileSync('./whitelist.json');
            msg.reply("Add mentioned user to whitelist?")
            msg.react('????').then(r => {
                msg.react('????');
            });
            msg.awaitReactions((reaction, user) => user.id == msg.author.id && (reaction.emoji.name == '????' || reaction.emoji.name == '????'), {
                max: 1,
                time: 30000
            }).then(collected => {
                if (collected.first().emoji.name == '????') {
                    let data = JSON.parse(rawdata);
                    data.newdata[user] = {
                        "ID": user.id
                    }
                    fs.writeFileSync("./whitelist.json", JSON.stringify(data, null, 2), (err) => {
                        if (err)
                            embed = new Discord.MessageEmbed()
                            .setTitle('Error report')
                            .addField(`Logged error:`, err, false)
                            .addField(`Server:`, `${msg.guild}`, false)
                            .addField(`Command:`, `${command} ${commandArgs}`, false)
                            .setColor('#0099ff');
                        webhookClient.send(embed)
                    })
                    msg.reply("Whitelisted user!")
                } else
                    msg.reply('Operation canceled.');
            }).catch(() => {
                msg.reply('No reaction after 30 seconds, operation canceled');
            });
            return
        }
    }
}

【问题讨论】:

  • 如果你有办法改进我的代码,我很高兴听到它
  • 你应该缩进你的代码
  • 这对你来说可能有用,但我更喜欢如果它全部排好不要杀了我 o.o
  • 你真的喜欢这种“缩进”吗?
  • 我的意思是我做 lmao

标签: javascript node.js json discord discord.js


【解决方案1】:

我不熟悉JSon,但是如果文件更新了,那么bot如何读取早期版本?

尝试所有提交、保存、刷新等。这是确保更改或更新不会回滚的唯一方法。检查与任何缓存的冲突。

【讨论】:

  • 我不知道当机器人重新启动时它是如何正常工作的。因此它可以编辑文件,但只能在重新启动后读取编辑内容
  • 您的代码中似乎有几个条件。创建一个测试,您可以在其中执行一次简单的写入和读取。如果机器人工作正常,那么您就会知道问题出在您的条件上。
  • meh 我只在机器人宕机时使用 json 来尝试帮助 doe
【解决方案2】:

好吧,所以我解决了我的问题,只需在我的代码中添加一个变量并与 Json 一起更新它,这样当机器人重新启动时,它会从 Json 获取数据到变量中,我可以解决这个问题

var wl = [];



client.once('ready', async () => {
client.user.setActivity('Starting up ...')
let rawdata = fs.readFileSync('./whitelist.json');
let data = JSON.parse(rawdata);
wl = data
console.log('Conected!')
console.log(`Logged in as ${client.user.tag}!`);
});



else if (command === 'whitelist') { 
const user = msg.mentions.users.first();
if (!user) return msg.reply('Please mention a user!');
if (user.id === msg.author.id) return msg.reply("I'm questioning why you're trying to remove your own permissions?");
if (user.id === "361511417800556546") return msg.reply("Sorry buddy that user is untouchable!")
const test = Object.values(wl.newdata).find(object => object.ID === msg.author.id)
if(!test)return msg.reply("Sorry you can't use this!");
if(test){
const item = Object.values(wl.newdata).find(object => object.ID === user.id)
if (item){
msg.reply("Remove mentioned user from whitelist?")
msg.react('?').then(r => {
msg.react('?');});
msg.awaitReactions((reaction, user) => user.id == msg.author.id && (reaction.emoji.name == '?' || reaction.emoji.name == '?'),
{ max: 1, time: 30000 }).then(collected => {if (collected.first().emoji.name == '?') {
let rawdata = fs.readFileSync('./whitelist.json');
let data = JSON.parse(rawdata);
delete data.newdata [user]
fs.writeFileSync("./whitelist.json", JSON.stringify(data, null, 2), (err) => { if (err) 
embed = new Discord.MessageEmbed()
.setTitle('Error report')
.addField(`Logged error:`, err, false)
.addField(`Server:`, `${msg.guild}`, false)
.addField(`Command:`, `${command} ${commandArgs}`, false)
.setColor('#0099ff');
webhookClient.send(embed)
})
wl = data;
msg.reply("Removed user!")}
else
msg.reply('Operation canceled.');
}).catch(() => {msg.reply('No reaction after 30 seconds, operation canceled');});
return
}
if (!item){ 
let rawdata = fs.readFileSync('./whitelist.json');
msg.reply("Add mentioned user to whitelist?")
msg.react('?').then(r => {
msg.react('?');});
msg.awaitReactions((reaction, user) => user.id == msg.author.id && (reaction.emoji.name == '?' || reaction.emoji.name == '?'),
{ max: 1, time: 30000 }).then(collected => {if (collected.first().emoji.name == '?') {
let data = JSON.parse(rawdata);
data.newdata [user] = {"ID": user.id}
fs.writeFileSync("./whitelist.json", JSON.stringify(data, null, 2), (err) => {
if (err) 
embed = new Discord.MessageEmbed()
.setTitle('Error report')
.addField(`Logged error:`, err, false)
.addField(`Server:`, `${msg.guild}`, false)
.addField(`Command:`, `${command} ${commandArgs}`, false)
.setColor('#0099ff');
webhookClient.send(embed)
})
wl = data;
msg.reply("Whitelisted user!")}
else
msg.reply('Operation canceled.');
}).catch(() => {msg.reply('No reaction after 30 seconds, operation canceled');});
return}}
}

【讨论】:

    【解决方案3】:

    修复了这个问题,但只是不主动使用 Json 并且回头看这是一个愚蠢的选择 只需使用 Json 来保存每隔一个小时和/或当你以这种方式关闭你的机器人时,你仍然可以保存数据,但不要过度使用文件。小例子:

    const UseThisToEdit = [];
    
    //start up
    client.once('ready', async () => {
        let FileData = fs.readFileSync('./MyJsonFile.json');
        let Data = JSON.parse(FileData );
        UseThisToEdit = Data 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-29
      • 2022-01-26
      • 2019-09-14
      • 1970-01-01
      • 2011-06-01
      • 2021-01-06
      • 1970-01-01
      相关资源
      最近更新 更多