0

I'm quite new to discord.js and js in general. I haven't been able to figure out how to let a user execute a command to query a MySQL database.

In my index.js file, I've been able to successfully connect js to my local MySQL database and it runs a quick test on the table 'users' on startup.

require('dotenv/config');
const {Client, IntentsBitField} = require('discord.js');
const {CommandHandler} = require('djs-commander');
const path = require('path');
const mysql = require('mysql');

const client = new Client({
    intents: [
        IntentsBitField.Flags.Guilds, //lets us get info on servers
        IntentsBitField.Flags.GuildMembers, //info on users
        IntentsBitField.Flags.GuildMessages,
        IntentsBitField.Flags.MessageContent,
    ],
});

//lets us write events/commands etc to the other folders to keep this file clean
new CommandHandler({
    client, 
    eventsPath: path.join(__dirname, 'events'),
    commandsPath: path.join(__dirname, 'commands'),
});

//mysql connection
var pool = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASE,
    port: process.env.DB_PORT
})

var connection = pool.getConnection((err, con) => {
    if (err) {
        console.log("Error DB connect: " + err);
        throw err;
    }
    else {
        connection = con;
        console.log("Connection established.");

        connection.query('SELECT points FROM users',(err, result) => {
            console.log(result);
            //interaction.reply({content: `Result:${result}`})
        });
    }

});

client.login(process.env.TOKEN);

I've also been able to create a separate names.js file that executes /names in Discord, albeit, it only produces text.

module.exports = {
    data: {
        name: 'names',
        description: 'gets all the names',
    },

    run: ({interaction}) => {
        //connection.query('SELECT username FROM users',(err, result) => {
        //    console.log(result);
        //    interaction.reply({content: `Result:${result}`})
        //});
        interaction.reply('collecting data');
    },
}

Does anyone know how I can incorporate a query into the result of a /command? In this example, the /names command would return a message with the usernames from the database.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.