简体   繁体   中英

How can I add strings to an array in a JSON using node.js?

I have a discord bot and I want to have an array that has the user ids of people who abuse the volume and music commands so that I can take away their abilities and give them back using commands like !nomusic and !musicback , but I have no idea how I would make it add or remove their ids from an array in the config file. My best guess is to use fs and have it push the member's id into the array, but I have no idea how I would go about doing this (I'm very new to node.js and especially fs , so sorry if this is a really easy thing to do and is really dumb to ask)

So far this is how far I've gotten(lots of the program not included so it's easier to read)

function readNoMusicJSON() {
    return JSON.parse(fs.readFileSync("./nomusic.json"));
}

var badmusicusers = readNoMusicJSON();

function nomusicsfoyou(badmusicusers, userId) {
    return nomusic.concat([userId]);
}

function saveNoMusicFile(badmusicusers) {
    fs.writeFileSync("./nomusic.json");
}
bot.on('message', async message => {
//some code ommited due to lack of importance
var args = message.content.slice(config.prefix.length).trim().split(/ +/g);    
var command = args.shift().toLowerCase();
switch(command){
    case"music":
        if(badmusicusers.find(id=>id == message.author.id)) return;
        // more ommitted code that don't matter
        break;
    case "nomusic":
        let sadmusicboi = message.mentions.members.first();
        badmusicusers = nomusicsfoyou((badmusicusers, sadmusicboi.id));
        saveNoMusicFile(badmusicusers);
        break;
    }
})

Suppose you have a list of bannedUsers in your config bannedUsers.json file.

["user-id-1", "user-id-2"]

On Startup of the program, you read the file into a variable:

function readBannedUsers() {
    return JSON.parse(fs.readFileSync("./bannedUsers.json"));
}

var bannedUsers = readBannedUser();

Whenever you want to ban a user:

function banUser(bannedUsers, userId) {
     return bannedUsers.concat([userId]);
}

function saveBannedUsers(bannedUsers) {
     fs.writeFileSync("./bannedUsers.json");
}

bannedUsers = banUser(bannedUsers, "user-3");
saveBannedUsers(bannedUsers);

That's all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM