0

I have a question. How can I let my DiscordBot write and read a JSON file? I have already programmed something but have only error. Can someone help me out? I would appreciate any help.

const Discord = require("discord.js")
const botconfig = require("../botconfig.json");
const colours = require("../colours.json");
const superagent = require("superagent");
const { report } = require("superagent");
const usedCommand = new Set();

module.exports.run = async(bot, message, args) => {
    message.delete();

    if (usedCommand.has(message.author.id)) {
        message.reply("du kannst diesen Command erst in 15 Sekunden wieder verwenden.").then(msg => msg.delete({ timeout: "10000" }));
    } else {
        let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])

        let reason = args.slice(1).join(" ");
        if (!reason) message.reply("Bitte gebe einen Beweis in Form von einem Link (Video: Youtube, Bild: prnt.sc) an!")

        var fs = require("fs");
        var sampleObject = {
            username: member,
            proof: reason
        };

        fs.writeFile('../rpp.json', JSON.stringify(sampleObject, null, 4), (err) => {
            if (err) {
                console.error(err);
                return;
            };
            console.log("File has been created");
        });

        usedCommand.add(message.author.id);
        setTimeout(() => {
            usedCommand.delete(message.author.id);
        }, 15000);
    }
}

module.exports.config = {
    name: "rpp",
    description: "Bans a user from the guild!",
    usage: "+ban",
    accessableby: "Members",
    aliases: ["proofwrite"]
}

I want my Discord bot to enter the tagged user and a reason into the JSON file using the "writerrp" command. After that I want the bot to read the data of a user with the "readrrp" command.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Beyazz
  • 1
  • 1
  • 1
  • 3
    What is the error you are getting? – DenverCoder9 Jan 18 '21 at 10:21
  • Does this answer your question? [Using Node.JS, how do I read a JSON file into (server) memory?](https://stackoverflow.com/questions/10011011/using-node-js-how-do-i-read-a-json-file-into-server-memory) – Blieque Jan 18 '21 at 10:58

1 Answers1

0

here is an example of reading from a .json file.

Set up the json file correctly, using the right syntax.

{
  "token": "<a token goes here>" //in your local json file - called config.json in this case
}
client.login(config.token) //reads from the config.json file as an obj, which calls the token param

When reading from the json file, you need the fs package

const fs = require('fs');
//assuming your bot has args
let reason = args.slice(1,2) //removes the command and the @
let user = message.mentions.users.first()

//create a new obj
var obj = {
   table: []
};

//add some data to it e.g.
obj.table.push({reason: `${reason}`, user:`${user.username}`});

//convert it to json using the json#stringify() method
var json = JSON.stringify(obj);

//write to the json file
fs.writeFile('myjsonfile.json', json, 'utf8', callback);

//if you want to append, do this:
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
    if (err){
        console.log(err);
    } else {
    obj = JSON.parse(data); //now it an object
    obj.table.push({id: 2, square:3}); //add some data
    json = JSON.stringify(obj); //convert it back to json
    fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
}});

credit for the above goes to @kailniris here

Joe Moore
  • 2,031
  • 2
  • 8
  • 29