Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

discord - How to save some variables

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...