How to Connect Your Discord Bot to a MySQL Database

Python Modules

  • Discord: Library for building Discord bots.
  • aiomysql: An asynchronous MySQL client. It allows your Discord bot to communicate with the Cybrancee database without blocking other bot tasks.
  • python-dotenv: Loads environment variables from a .env file. Keeps sensitive data like database passwords and your bot token out of your code.
  • cryptography: Provides secure methods needed for MySQL authentication.

Creating a Database

To create a database, select the ‘Databases’ tab on the sidebar, then follow this guide to create one: How to Create a Database for Your Discord Bot


1. Login to Your Panel


2. Add Python Modules

Select the ‘Startup’ tab, then scroll to the “ADDIONAL PYTHON PACKAGES” field and paste

discord.js aiomysql python-dotenv cryptography
Cybrancee Panel in startup page, ADDIONAL PYTHON PACKAGES is highlighted

3. Create a .env File

Create a .env file in the project to store all configuration settings for the Python Discord Bot, including the Discord Bot Token and database credentials.

Example .env file:

Cybrancee Panel in the files page. DOTENV file (2)

The Code:

DISCORD_TOKEN=your_discord_bot_token

DB_HOST=your_db_host
DB_PORT=your_db_port
DB_NAME=your_db_name
DB_USER=your_db_user
DB_PASSWORD=your_db_password

4. Create an index.py File

The index.py file is the main bot file. It starts the bot, loads commands, and connects to the database using the .env settings.

Cybrancee panel in the files page, index.py file

The Code:

import discord
from discord.ext import commands
from dotenv import load_dotenv
import os
import aiomysql

# Load environment variables
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
DB_HOST = os.getenv("DB_HOST")
DB_PORT = int(os.getenv("DB_PORT"))
DB_NAME = os.getenv("DB_NAME")
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")

# Initialize bot
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)

# Connect to MySQL
async def connect_db():
    return await aiomysql.connect(
        host=DB_HOST,
        port=DB_PORT,
        user=DB_USER,
        password=DB_PASSWORD,
        db=DB_NAME
    )

# Bot ready event
@bot.event
async def on_ready():
    print(f"{bot.user} is online!")

# Run the bot
bot.run(TOKEN)

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