Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

72
Visualizações
Creating a profile in mySQL database and using it right after to display what's inside it Discord.js

I'm creating my Discord bot, and I saw that with the hosting provider I bought came with a mySQL database, so I'm using it. I connected to it with the mySQL NPM package:

export const con = mysql.createConnection({
  host: process.env.MYSQL_HOST,
  port: process.env.MYSQL_PORT,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DB,
});

and it works fine. I created a table in the database, with 3 parameters:
id: Discord user id
bananas: My toy currency
deposit: The currency deposit
I set it up that on the interactionCreate event, whenever a user uses an interaction, it checks the database, if there is a profile, it does nothing, else, it creates the profile in the database. Code:

  async checkDB(int: CommandInteraction | MessageComponentInteraction) {
    await con.query(
      `SELECT * FROM profileSchema WHERE id = '${int.user.id}'`,
      async (e: Error, rows: any) => {
        if (e) throw e;
        if (!rows[0]) {
          await con.query(
            `INSERT INTO profileSchema (id, bananas, deposit) VALUES ('${int.user.id}', 100, 0)`
          );
        }
      }
    );
  },

this code works fine, the problem is that if a user does not have a profile in the database, and they use a currency related command, like the one that shows their balance, the bot crashes because their credits in the database result nonexistent, even though the profile gets created and the second time they use the command it works properly! How can I code so that if the user is not in the database and uses a command, it creates and displays at the same time? Here's the code that checks the currency balance:

    await con.query(
      `SELECT * FROM profileSchema WHERE id = ${interaction.user.id}`,
      async (e: Error, rows: any[]) => {
        if (e) throw e;
        let wallet: {
          bananas: number;
          deposit: number;
        };
        try {
          wallet = {
            bananas: rows[0].bananas,
            deposit: rows[0].deposit,
          };
        } catch (e) {
          throw e
          return;
        }
    )
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So unless it is really needed, you don 't need the async/await components in this but the simple answer you are looking for is to change if (!rows[0]) to if (!rows.length) but that works when you set up your query like such:

con.query(`SELECT * FROM profileSchema WHERE id = '${int.user.id}'`, (err, rows) => {
    if (err) throw err;
    if (!rows.length) {
        con.query(`INSERT INTO profileSchema (id, bananas, deposit) VALUES ('${int.user.id}', 100, 0)`, (err) => {
            if (err) throw err;
        });
    } else {
        let wallet = {
            bananas: rows[0].bananas,
            deposit: rows[0].deposit,
        }
    }
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda