我有一个命令要成为每个用户的“计数器”:我试图将一个新属性直接添加到User对象,但这没有用。这是我当前的代码:
if (command == "f") {
if (!message.author.counter) message.author.counter = 0
message.author.counter++
message.channel.send(message.author + " paid respects.\nC'est le F numéro " + message.author.counter + " de " + message.author + ".")
}
答案 0 :(得分:0)
您不能将其直接存储到User对象中,但是可以在存储它的地方创建一个不同的对象/地图。
您首先需要在代码中的某个地方初始化一个空对象:
var counters = {};
然后,每次使用该命令时,您都会存储一个与用户ID相关的数字:
if (command == "f") {
if (!counters[message.author.id]) counters[message.author.id] = 0;
counters[message.author.id]++;
message.channel.send(message.author + " paid respects.\nC'est le F numéro " + counters[message.author.id] + " de " + message.author + ".");
}
请注意,每次启动bot时都会重新构建对象:如果要随时间推移保留它,则需要将其存储在数据库或JSON文件中。
如何保存和加载JSON文件?
要将现有文件加载到名为counters
的变量中,可以执行以下操作:
// You need to require fs (there's no need to install it though)
const fs = require('fs');
// You can set the name of the file you want to save the counters in
const filePath = './counters.json';
var counters;
try {
// If the file already exists, you can load that into counters
let file = require(filePath);
counters = file;
} catch {
// If you can't load the file it means you should create one
counters = {};
fs.writeFileSync(path, '{}');
}
每次您要增加计数器时,都可以像我之前写的那样进行操作:将counters
对象中的number属性增加一。
为了保存文件,您需要使用:
fs.writeFileSync(filePath, JSON.stringify(counters));
由您决定何时运行:您都可以定期运行它,或者,如果要确保立即保存内容,可以在命令末尾添加它:
if (command == "f") {
if (!counters[message.author.id]) counters[message.author.id] = 0;
counters[message.author.id]++;
message.channel.send(message.author + " paid respects.\nC'est le F numéro " + counters[message.author.id] + " de " + message.author + ".");
fs.writeFileSync(filePath, JSON.stringify(counters));
}