0

I have a command that I want to be a "counter" for each user: I've tried adding a new property directly to the User object, but that didn't work. Here's my current code:

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 + ".")
}
Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
Okna
  • 29
  • 1
  • 1
  • 4

1 Answers1

0

You can't directly store it into the User object, but you can create a different object/map where you store it.

You first need to initialize an empty object somewhere in your code:

var counters = {};

Then, every time the command is used, you store a number associated to the id of the user:

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 + ".");
}

Please note that the objects gets re-built every time the bot starts: if you want to keep it over time you'll need to store it in a database or a JSON file.


How can I save and load a JSON file?

To load an existing file into a variable called counters you can do as follows:

// 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, '{}');
}

Every time you want to increment a counteryou can do as I previously wrote: you increase the number property in the counters object by one.
In order to save the file you need to use:

fs.writeFileSync(filePath, JSON.stringify(counters));

It's up to you when to run it: you could both run it periodically or, if you want to be sure stuff gets saved immediately, you can add it at the end of your command:

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));
}
Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
  • yeah, that was what I meant, i just want the counter to keep the numbers when the bot starts but I don't know how to do it, the counter as it actually is works fine for each user – Okna Apr 29 '19 at 19:01