0
votes

I'm trying to place the id and name of each Guild a Discord chat bot is handling into a PGSQL database table. I'm using the Discord.js module and its client.guilds which is a JS Map object and the forEach method to repeat each PGSQL query of each server name and id. I'm using PGadmin to render the table after I've run the process (I'm doing this by deploying the Heroku app my bot is running on) query that is written in my GitHub file (my github is linked to heroku deploy).

Here is my code:

client.guilds.forEach(function (value, key) {
  con.query('INSERT INTO Servers (name, id) VALUES (\'' + value.name.toString() + '\', ' + key.valueOf() + ');', (err, res) => {
    console.log(res);
    console.log(err);
  });
});

My problem is that each discord server name and ID will not be inserted into their respective columns after I have deployed my app.

1

1 Answers

0
votes

I have fixed my problem by inserting this code to after the bot has logged into Discord. Because the bot cannot retrive any information until it is connected with the Discord API, the query would not be loaded in the first place because client can not access the guilds information. I decided to place this in my client.ready event and it worked!

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
  client.guilds.forEach(function (value, key) {
    con.query('INSERT INTO Servers (name, id) VALUES (\'' + value.toString() + '\', ' + key.valueOf() + ');', (err, res) => {
      console.log(res);
      console.log(err);
    });
  });
  con.end();
});