Tips for preserving data on a JSON file to prevent it from resetting whenever my Discord Bot disconnects

I am currently working on developing a bot that incorporates a warning system.

The way it works is that depending on the reason for the warning, users are assigned "points". Once a user accumulates 100 points, they are automatically kicked from the server.

For example, if Insults is at 15 points and Spam is at 20 points:

/warn Sappeur Insults: my warnLevel would be at 15 points

/warn Sappeur Spam: my warnLevel would be at 35 points since I already had 15.

However, this data resets whenever the bot goes offline. I am looking for a way to save this data into a JSON file named "warnLevel". As a beginner, I would appreciate any advice on how to achieve this without making it too complicated. Thank you.

Answer №1

One way to save data to a file on the system is by using the following method:

writeFile(Path, Data, Callback)

This method belongs to node.js's fsLibrary, which suggests that you are likely working with node if you are using discord.js (please correct me if I'm mistaken).

Here's an example:

// Require the fs module where the writeFile function is defined.
const fsLibrary = require('fs');
// Data to be added to the file.
let data = "Hello world.";
// Write the data to 'newfile.txt'.
fsLibrary.writeFile('newfile.txt', data, (error) => {
    // Throw an error exception in case of an error.
    if (error) throw err;
})

If you need to read from the file and load the configuration, you can utilize the following method:

readFile(Path, Options, Callback)

Answer №2

Upon implementing the code you suggested, I encountered some difficulties.

` switch (args[2]) {
                case 'Freekill': {
                    let points = "20";
                    fs.writeFile('./warnLevel.json', points, (error) => {
                        if (error) throw err;
                    })
                    break;
                }

                case 'Spam' : {
                    let points = "10";
                    fs.writeFile('./warnLevel.json', points, (error) => {
                        if (error) throw err;
                    })
                    break;

                }
            }
            break;
        } `

I faced two primary issues: 1) The command was overwriting all existing data in the JSON file rather than tracking individual users' points. 2) When I added the second case, I encountered the following error:

internal/modules/cjs/loader.js:1175
throw err;
^

SyntaxError: C:\Users\ACER\Desktop\PobWarn\warnLevel.json: Unexpected end of JSON input  
at parse (<anonymous>)
?[90m    at Object.Module._extensions..json (internal/modules/cjs/loader.js:1172:22)?[39m
?[90m    at Module.load (internal/modules/cjs/loader.js:986:32)?[39m
?[90m    at Function.Module._load (internal/modules/cjs</answer2>
<exanswer2><div class="answer" i="62289185" l="4.0" c="1591715287" a="U2FwcGV1cg==" ai="13713775">
<p>So I experimented with the commands you mentioned.</p>

<pre><code>` switch (args[2]) {
                case 'Freekill': {
                    let data = "20";
                    fs.writeFile('./warnLevel.json', data, (error) => {
                        if (error) throw err;
                    })
                    break;
                }

                case 'Spam' : {
                    let data = "10";
                    fs.writeFile('./warnLevel.json', data, (error) => {
                        if (error) throw err;
                    })
                    break;

                }


            }
            break;
        } `

I encountered two main obstacles: 1) The command kept replacing all contents in the JSON file instead of maintaining different users' points. 2) Adding the second case resulted in this error message:

internal/modules/cjs/loader.js:1175
throw err;
^

SyntaxError: C:\Users\ACER\Desktop\PobWarn\warnLevel.json: Unexpected end of JSON            input  
at parse (<anonymous>)
?[90m    at Object.Module._extensions..json (internal/modules         /cjs/loader.js:1172:22)?[39m
?[90m    at Module.load (internal/modules/cjs/loader.js:986:32)?[39m
?[90m    at Function.Module._load (internal/modules/cjs/loader.js:879:14)?[39m
?[90m    at Module.require (internal/modules/cjs/loader.js:1026:19)?[39m
?[90m    at require (internal/modules/cjs/helpers.js:72:18)?[39m
at Object.<anonymous> (C:\Users\ACER\Desktop\PobWarn\index.js:6:19)
?[90m    at Module._compile (internal/modules/cjs/loader.js:1138:30)?[39m
?[90m    at Object.Module._extensions..js (internal/modules                                        /cjs/loader.js:1158:10)?[39m
?[90m    at Module.load (internal/modules/cjs/loader.js:986:32)?[39m 

Additionally, I am uncertain about the purpose and parameters to be used for the `readFile` command, including options and callback functions. Apologies for any inconvenience caused.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selecting all the li elements inside a ul with a jQuery selector

When creating a menu, I want to apply the .active class only to child elements when clicked on li children, not the parent li. (Utilizing the enfold WordPress theme) $('#mobile-advanced li.menu-item-has-children').on('click', functi ...

Display a message after serializing JSON in my cakePHP application

Is there a way to append something at the conclusion of the cakePHP json/xml output? This is necessary for incorporating JSONP capability (Since I must insert the callback at the start and ');' at the end) This is how the controller is set up: ...

Service in Angular2+ that broadcasts notifications to multiple components and aggregates results for evaluation

My objective is to develop a service that, when invoked, triggers an event and waits for subscribers to return data. Once all subscribers have responded to the event, the component that initiated the service call can proceed with their feedback. I explore ...

Attempting to showcase a list of 4 concatenated items in a dropdown menu sourced from the database

I am attempting to concatenate and display 4 items in a dropdown list using AJAX. For example, the value in the dropdown list should appear as (127, CoilWt, 1, KGS) from the database. In the database, I am selecting select CODE_VALUE, CODE_DESC, CODE_SUB ...

Ways to address a buffered data problem in Websocket Rxjs. When trying to send a message, it is not being received by the server and instead is being stored in a

Currently, I am utilizing Websocket Rxjs within my application. The connection is successfully established with the server, and upon subscribing to it, all data is received in an array format. However, when attempting to send data back to the server, it se ...

Failure of the controller in a different module

Hello, I'm currently facing an issue with setting up my child controller. I have developed two modules - one for managing directives and controllers, and another for handling Gmail functionalities. //js file 1 var gmailMod = angular.module('gm ...

Having trouble retrieving the value of the second dropdown in a servlet through request.getParameter

I am facing an issue with storing the value of the second dropdown in a servlet after utilizing an ajax call in Java to populate it based on the selection made in the first dropdown. While I was able to successfully store the value of the first dropdown ...

Clear the token from SAPUI5 multi input field while maintaining data binding

In my SAPUI5 application, I am facing an issue with the Multi Input Field and JSON Model integration. Whenever a token is deleted by clicking the "x" button next to it, the token disappears from the input field but reappears when a new token is added. How ...

Calculating the length of an Observable in an Angular 4 MEAN stack application

In my Angular 4 application, I utilize a service function to fetch data from the MongoDB/Express.js backend: getArticles() { return this.http.get('api/articles').map(res => res.json()); } Is there a way for me to determine the length of th ...

Overloading the server with over 50,000 results causes the Laravel 5.8 system to crash

Currently, I am facing an issue while attempting to retrieve 400,000 results from a database using Laravel. The problem arises when the server returns a 500 error code, however, it does not generate a log file for further analysis. Interestingly, when I ...

"Exploring the use of regular expressions in JSON with Struts

I am looking to integrate jQPlot with Struts and I have a JSON output from a struts action that looks like this: { "jqPlotJSONFormat": "['18-03-2010',56],['19-03-2010',43],['17-03-2010',84]" } However, I would li ...

Python's nested classes require the document to be an instance of either dict, bson.son.SON, or bson.raw_bson.RawBSONDocument

I'm struggling to serialize this data for MongoDB using PyMongo. I have a toJSON() method in the Categories class that outputs JSON correctly, but when trying to save it using insertOne(), it doesn't work. class Categories: def __init__(self ...

Combining and serializing a JavaScript object

Combining nested JavaScript objects was straightforward when dealing with a single object. However, as the number of objects has increased, I require a more dynamic approach to merge the address key and serialize my object. var old = {account: "100000 ...

Exporting JSON data from Blender for use in Three.js

Whenever I try to export some obj models from Blender to json using the three.js plugin, it always seems to result in javascript errors on my web page. The specific error message that pops up is: TypeError: vertices is undefined This error occurs at th ...

Validation of JSON Failed

Encountered a 400 Bad Request error while attempting to POST an answer using Postman, it appears to be a validator issue. Despite multiple attempts, I have yet to resolve this issue. Below are details of the JSON data being sent in the POST request along w ...

Obtaining [Symbol(Response internals)] through a JSON response

I am currently utilizing the library isomorphic-unfetch to retrieve JSON data from a Rest API. Here is my approach for making the request: const res = await fetch( `url` ); To extract the body, I simply do: const response = await res.j ...

Is there a way to retrieve the id of every post on my page?

Is it possible to send multiple post ids in JavaScript? I have successfully sent the first post id, but now I need to figure out how to send each individual post id. When inspecting the elements, I see something like this: <div data-id="post_1">< ...

Why is PHP unable to locate the index sent in the JSON data?

Why can't PHP seem to locate my index, myPostData? Utilizing jQuery/AJAX $('a').on("click", function(){ $.ajax({ type: "POST", url: "../image_view.php", data: {myPostData : {"lastName":"Sperrow", "firstName":"J ...

Querying data in SQL Server to retrieve all rows as a JSON object and display them next to other columns - a comprehensive guide

I am dealing with the following data: https://i.sstatic.net/axp7r.png My desired query result should look like this: https://i.sstatic.net/G9VjA.png This is the code I have: SELECT PML_CODE ,PML_NAME_ENG ,( SELECT PML_ ...

Setting the root position of a div: How can it be done?

Imagine a scenario where a div element is designed to follow the mouse cursor on the screen. This functionality is achieved by manipulating the document's `mousemove` event and adjusting the div's `left` and `top` positions based on the event dat ...