This commit is contained in:
parent
232b8e3dc9
commit
7e65d9539b
@ -1,86 +1,91 @@
|
|||||||
const { SlashCommandBuilder } = require('discord.js');
|
const { InteractionContextType, PermissionFlagsBits, SlashCommandBuilder, MessageFlags } = require('discord.js');
|
||||||
const conn = require('../../../database/db');
|
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
|
module.exports = {
|
||||||
const data = new SlashCommandBuilder()
|
|
||||||
|
|
||||||
|
|
||||||
|
// Função que busca as opções no banco
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
data: new SlashCommandBuilder()
|
||||||
.setName('add')
|
.setName('add')
|
||||||
.setDescription('Adiciona o servidor à base de dados.')
|
.setDescription('Adiciona o servidor à base de dados.')
|
||||||
.addStringOption(option =>
|
.addStringOption(option =>
|
||||||
option
|
option.setName('tipo_sanguinio')
|
||||||
.setName('tipo_sanguinio1')
|
.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')
|
.setDescription('Escolha uma opção do banco de dados')
|
||||||
.setRequired(true)
|
.setRequired(true)
|
||||||
.addChoices(...choices) // Passa as opções carregadas para o comando
|
.addChoices(
|
||||||
);
|
{ name: 'Bxio', value: '0' },
|
||||||
|
{ name: 'TeixLo', value: '0' },
|
||||||
return data;
|
{ name: 'Mike', value: '1' },
|
||||||
}
|
{ name: 'Totem', value: '3' },
|
||||||
|
)
|
||||||
module.exports = {
|
),
|
||||||
data: createAddCommand(),
|
|
||||||
|
|
||||||
async execute(interaction, client) {
|
async execute(interaction, client) {
|
||||||
const guildId = interaction.guild.id;
|
const guildId = interaction.guild.id;
|
||||||
|
const guildName = interaction.guild.name;
|
||||||
const guildownerId = interaction.guild.ownerId;
|
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 {
|
try {
|
||||||
const checkQuery = `SELECT * FROM Guilds WHERE guildId = ?`;
|
// Be very careful with this approach! This is vulnerable to SQL injection.
|
||||||
const [checkRows] = await conn.execute(checkQuery, [guildId]);
|
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) {
|
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 {
|
} else {
|
||||||
const insertQuery = `INSERT INTO Guilds (guildId, guildownerId) VALUES (?, ?)`;
|
// O guildId não existe, podemos prosseguir com a inserção ou outra ação
|
||||||
await conn.execute(insertQuery, [guildId, guildownerId]);
|
const insertQuery = `INSERT INTO Guilds (guildId,guildownerId) VALUES ('${guildId}','${guildownerId}')`;
|
||||||
await interaction.editReply('✅ GuildId registrado com sucesso!');
|
await conn.execute(insertQuery);
|
||||||
|
|
||||||
|
interaction.editReply('✅ GuildId registrado com sucesso!');
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
interaction.editReply('❌ Ocorreu um erro inesperado.');
|
||||||
await interaction.editReply('❌ Ocorreu um erro inesperado.');
|
console.error(err); // Logar o erro para ajudar no diagnóstico
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user