I'm trying to build a simple Discord.js bot, but I'm having trouble adding user input to an array stored within a json file.
I'd like to have a single json file that will store information the bot can draw on, including an array of quotes that is also able to be added to by users. Currently, the settings.json file looks like this:
{ "token" : , //connection token here
"prefix" : "|", //the prefix within messages that identifies a command
"quotes" : [] //array storing a range of quotes
}
I can then draw information from the array, choosing a random quote from those currently stored, as shown below:
const config = require("./settings.json");
var quotes = config.quotes;
function randomQuote() {
return quotes[Math.floor(Math.random() * quotes.length)];
};
if(message.content.toLowerCase() === prefix + "quote") {
message.channel.send(randomQuote());
}
This all works as intended, but I can't for the life of me work out how to allow users to add a quote to the array (it'd use a command something like |addquote). I know that, for writing data to a json file, I'd use something like this:
var fs = require('fs');
let test = JSON.parse(fs.readFileSync("./test.json", "utf8"));
if(message.content.toLowerCase() === 'test') {
test++;
fs.writeFile("./test.json", JSON.stringify(test), (err) => {
if (err) console.error(err)
});
}
But what for what I'm trying to do now - target a specific array within an existing json file that contains other data separate to the array, and add a new entry rather than overwrite what's there - I'm pretty much stumped. I've looked around a lot, but either I haven't found what I'm looking for, or I couldn't understand it when I found it. Could anyone help me out here?