How to Connect Your Node.js Discord Bot to MySQL

Requirements


1. Log In to Your Panel


2. Select the ‘Files’ Tab

Cybrancee Panel in the files page, "Files" tab on the sidebar is highlighted

3. Create Your Main Bot’s File

Create a new file called index.js.

Pterodactyl Panel, Create File dialog. Enter File Name (index.js)

Paste the following code. This file will start your bot and connect it to the database, allowing you to add, remove, or retrieve data (In the following code, there are two commands shown just as an example for adding and retrieving data).

const { Client, GatewayIntentBits } = require('discord.js');
const mysql = require('mysql2/promise');

const client = new Client({
    intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]
});

// Database connection
const pool = mysql.createPool({
    host: 'localhost',
    user: 'your_username',
    password: 'your_password',
    database: 'your_database_name'
});

client.once('ready', async () => {
    console.log(`Bot ${client.user.tag} is online!`);
    
    // Create table for our data
    await pool.execute(`
        CREATE TABLE IF NOT EXISTS user_items (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id VARCHAR(255),
            item_name VARCHAR(255),
            quantity INT
        )
    `);
});

client.on('messageCreate', async (message) => {
    if (message.author.bot) return;

    // Command: !additem <item> <quantity>
    if (message.content.startsWith('!additem')) {
        const args = message.content.split(' ');
        const itemName = args[1];
        const quantity = parseInt(args[2]) || 1;

        await pool.execute(
            'INSERT INTO user_items (user_id, item_name, quantity) VALUES (?, ?, ?)',
            [message.author.id, itemName, quantity]
        );

        message.reply(`Added ${quantity} ${itemName}(s) to your inventory!`);
    }

    // Command: !myitems
    if (message.content.startsWith('!myitems')) {
        const [items] = await pool.execute(
            'SELECT item_name, quantity FROM user_items WHERE user_id = ?',
            [message.author.id]
        );

        if (items.length === 0) {
            message.reply('Your inventory is empty!');
        } else {
            const itemList = items.map(item => `${item.item_name} (x${item.quantity})`).join('\n');
            message.reply(`Your items:\n${itemList}`);
        }
    }
});

client.login('your_bot_token_here');

Make sure to modify these according to your MySQL configuration.

const pool = mysql.createPool({
    host: 'localhost',
    user: 'your_username',
    password: 'your_password',
    database: 'your_database_name'
});

Discord Bot Hosting

Starts at $1.49

External link icon
Was this article helpful?
Please Share Your Feedback
How Can We Improve This Article?
Table of Contents