如何保存一些变量 [英] How to save some variables

查看:59
本文介绍了如何保存一些变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于我:该问题旨在使用Discord.js将其用于Discord机器人我习惯于使用较旧的编码语言(例如C ++,C#,Batch和Game Maker Studio)进行编码,但我还是Discord.js的新手.

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.

问题:我听说这可以通过json文件完成.当机器人再次联机时,如何将一个变量保存到可以取回的位置?并且一旦我保存了它.如何获取该变量?

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?

我所知道的:对于Discord.js来说不是很多.我的机器人有大约20种不同的命令,例如添加角色,识别发誓并删除该消息,踢/禁止用户,批量删除消息等.

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.

推荐答案

是的,可以使用json文件或数据库完成

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

如果您要使用json:

If you are gonna go with json:

将值存储在开头的json文件中,例如:

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

./my-data.json

{ "Server-Rupees": 200 }

您将通过要求文件

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

如果要更新值,只需更新属性值并使用 fs.writeFile

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);
})

注意:即使对于同一文件,writeFile的路径也不总是与require的路径相同.

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

这篇关于如何保存一些变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆