Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

ABOUT ME: This question is aimed at using for a Discord bot using Discord.js I'm used to doing coding in older coding languages like C++, C#, Batch, and Game Maker Studio, but I'm still new to Discord.js

THE INTENT: I want to store some basic variables. Such as "Server Rupees" which is shared by everyone. And maybe a couple others. Nothing individual. Not a database. Not an array.

THE QUESTION: I've heard this can be done with a json file. How do I save one variable to a place I can get it back when the bot goes online again? And once I have it saved. How do I get that variable back?

WHAT I KNOW: Not a lot for Discord.js . My bot has about 20 different commands, like adding roles, recognizing a swear and deleting that message, kick/ban a user, bulk delete messages, etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
307 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes it can be done with a json file or database,

If you are gonna go with json:

Store the value inside of a json file to start of with, for example:

./my-data.json

{ "Server-Rupees": 200 }

You would get the result by requiring the file

const data = require("path-to-json.json");
console.log(data["Server-Rupees"]) 
// => 200

If you want to update the value, just update the property value and use fs.writeFile

const { writeFile } = require("fs");
const data = require("path-to-json.json");

data["Server-Rupees"] += 20;

//JSON.striginfy makes the object into a string, `null, 6` makes it prettier
writeFile("path-to-json.json", JSON.stringify(data, null, 6), err => {
   if(err) console.error(err);
})

Note: writeFile's path won't always be the same as require's path even for the same file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...