From 7e65d9539b3f37bb55a64a74db5d390f3c88e973 Mon Sep 17 00:00:00 2001 From: Bxio Date: Fri, 4 Apr 2025 20:24:05 +0100 Subject: [PATCH] --- src/commands/Community/testeadd.js | 133 +++++++++++++++-------------- 1 file changed, 69 insertions(+), 64 deletions(-) diff --git a/src/commands/Community/testeadd.js b/src/commands/Community/testeadd.js index a2f64fe..0d3601d 100644 --- a/src/commands/Community/testeadd.js +++ b/src/commands/Community/testeadd.js @@ -1,86 +1,91 @@ -const { SlashCommandBuilder } = require('discord.js'); +const { InteractionContextType, PermissionFlagsBits, SlashCommandBuilder, MessageFlags } = require('discord.js'); const conn = require('../../../database/db'); -console.error("--------------------- spacer ---------------------"); -async function getChoicesFromDatabase() { - const query = `SELECT name, value FROM products`; - let rows; - - try { - // Assuming conn is an object with an async method like `query` or `execute` - rows = await conn.execute(query); // Using await for async operation - } catch (err) { - console.error('Erro ao consultar o banco de dados:', err); - return []; - } - - if (!Array.isArray(rows)) { - console.error("rows is not an array:", rows); - return []; // Return empty array if data format is incorrect - } - - const choices = rows - .filter(row => row && row.name && row.value) // Filtra valores inválidos - .map(row => { - const name = String(row.name).slice(0, 100); - const value = String(row.value).slice(0, 100); - - // Filtra qualquer valor que contenha descrições como "VARCHAR(11)" ou "NOT NULL" - if (name.match(/VARCHAR\(\d+\)/) || value.match(/VARCHAR\(\d+\)/)) { - console.warn('⚠️ Valor inválido detectado:', row); - return null; // Ignora esse item - } - - return { name, value }; - }) - .filter(choice => choice !== null); // Remove os itens filtrados - - console.log(choices); - return choices; -} -async function createAddCommand() { - // Obtém as opções do banco de dados de forma assíncrona - const choices = await getChoicesFromDatabase(); - // Configura o comando /add com as opções carregadas - const data = new SlashCommandBuilder() +module.exports = { + + + + // Função que busca as opções no banco + + + + + + data: new SlashCommandBuilder() .setName('add') .setDescription('Adiciona o servidor à base de dados.') .addStringOption(option => - option - .setName('tipo_sanguinio1') + option.setName('tipo_sanguinio') + .setDescription('Arisu - Escolhe uma opção') + .setRequired(true) + .addChoices( + { name: 'Bxio', value: '0' }, + { name: 'TeixLo', value: '0' }, + { name: 'Mike', value: '1' }, + { name: 'Totem', value: '3' }, + ) + ) + .addStringOption(option => + option.setName('tipo_sanguinio1') .setDescription('Escolha uma opção do banco de dados') .setRequired(true) - .addChoices(...choices) // Passa as opções carregadas para o comando - ); + .addChoices( + { name: 'Bxio', value: '0' }, + { name: 'TeixLo', value: '0' }, + { name: 'Mike', value: '1' }, + { name: 'Totem', value: '3' }, + ) + ), - return data; -} - -module.exports = { - data: createAddCommand(), - async execute(interaction, client) { const guildId = interaction.guild.id; - const guildownerId = interaction.guild.ownerId; + const guildName = interaction.guild.name; + const guildownerId = interaction.guild.ownerId; + - await interaction.deferReply(); + console.log(`guildId: ${guildId}`); + console.log(`guildName: ${guildName}`); + console.log(`guildownerId: ${guildownerId}`); + console.log(choices); + + // Responde imediatamente para evitar timeout + await interaction.deferReply(); // público por padrão try { - const checkQuery = `SELECT * FROM Guilds WHERE guildId = ?`; - const [checkRows] = await conn.execute(checkQuery, [guildId]); + // Be very careful with this approach! This is vulnerable to SQL injection. + const query = `SELECT * FROM Guilds WHERE guildId = '${guildId}'`; + const [rows, fields] = await conn.execute(query); + + console.log('ℹ️ Primeira tentativa de acessar à base de dados.'); + console.log(rows); // Log the result + + } catch (err) { + interaction.reply('❌ Ocorreu um erro inesperado.'); + } + + try { + // Verificar se o guildId já existe na base de dados + const checkQuery = `SELECT * FROM Guilds WHERE guildId = '${guildId}'`; + const [checkRows] = await conn.execute(checkQuery); + console.log(checkRows); // Log the result if (checkRows.length > 0) { - await interaction.editReply('❌ Este guildId já está registrado.'); + // Já existe um guildId na tabela, você pode retornar uma resposta indicando a duplicação + interaction.editReply('❌ Este guildId já está registrado.'); + console.log(checkRows.length); // Log the result } else { - const insertQuery = `INSERT INTO Guilds (guildId, guildownerId) VALUES (?, ?)`; - await conn.execute(insertQuery, [guildId, guildownerId]); - await interaction.editReply('✅ GuildId registrado com sucesso!'); + // O guildId não existe, podemos prosseguir com a inserção ou outra ação + const insertQuery = `INSERT INTO Guilds (guildId,guildownerId) VALUES ('${guildId}','${guildownerId}')`; + await conn.execute(insertQuery); + + interaction.editReply('✅ GuildId registrado com sucesso!'); } } catch (err) { - console.error(err); - await interaction.editReply('❌ Ocorreu um erro inesperado.'); + interaction.editReply('❌ Ocorreu um erro inesperado.'); + console.error(err); // Logar o erro para ajudar no diagnóstico } + } -}; +};