0

I have my current Discord Bot project using JavaScript however i cannot find a way to store the value itself when done through a command such as !setname ___ hoping for a response of that being repeated back when I use !myname.

I know how to do it by storing it temporarily through:

bot.on('message', function (user, userID, channelID, message, evt) {
     if(message == "!myname") {
     bot.sendMessage({
                    to: channelID,
                    message: 'Your name is  ' + user.username; 
                });
    }
}

However i cant figure out how to do it through the ability to call for it whenever you want rather than getting an immediate response. For example setting my name now but being able to have it output when i use the command instead of having command that sets the value then outputs it in an immediate string

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
alank_ok
  • 13
  • 6

1 Answers1

1

Would recommend a simple key-value dictionary style in the current instance.
(Though you could store it to a text-file or database later if you prefer the data to be persistent across different sessions.)

Instance based:

Based on this post on stackoverflow...

You can create a global dictionary at the top
var usernameChangeDict = {};

Whenever the user invokes !setname, just do:
usernameChangeDict[user.id] = Their_new_name_here

Fetch it back using usernameChangeDict[user.id], should return null or empty if they did not set their name before.

Persistent data:

Could either store it in a text file on your local computer, or do a database as Zooly mentioned.
(Though personally, a database would be an overkill if your bot is not going to be used by a wide range of people.)

Text file

Read from this post, it contains details on how to write onto a text file.
This post talks about reading from a text file.

I would recommend storing it in a JSON format to make your life easier, since JSON.parse exists.

Most likely you would end up storing in a format like this:
{ "23125167744": "someone", "USER_ID": "username" }

Access it by parsedJson["USER_ID"].

SQLite

This tutorial would probably explain how to set your SQLite for javascript better than I do.

Once its all setup, just store the userID and username, you can just do:
SELECT username FROM yourTable WHERE userID = ?;
and
INSERT INTO yourTable (username, userID) VALUES (?, ?);
For inserting and selecting into database respectively.

WQYeo
  • 3,973
  • 2
  • 17
  • 26