0

So I'm using discord.js and am trying to get a block command to store its value in an array. In other words, when I do /block It will ignore that person, but I want it to store it in a file so it stays after restarting. My current code is below:

//at the top
var { blockedUsers } = require('./blocked.json')

//in the command listener
if (command == 'block') {
    let user = message.mentions.users.first();
    if (user && !blockedUsers.includes(user.id)) blockedUsers.push(user.id);
    message.channel.send(`blocked!`)
}

blocked.json:

{
"blockedUsers": []
}

This works fine, but after restarting the bot, the blocked list clears. How can I get it to store it in the file so that it stays after restarting?

1

1 Answer 1

1

By using require on a JSON file, you are evaluating the file content as a JavaScript object, which lives independently of the JSON source file.

For persisting the modifications in the file, use this:

const fs = require('fs');

fs.writeFile("./blocked.json", JSON.stringify({ blockedUsers }), function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved!");
}); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.