How to Use SQLite For Your Python Discord Bot

SQLite is a simple database that saves data in a single file. You can use it to store and get information easily.


1. Login to Your Panel


2. Select the ‘Files’ tab

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

3. Create the Database File

Create a new file called database.py then paste the following code.

This file will create the tables in your database (in the future, you can create as many tables as you need).

Pterodactyl Panel, Create File dialog. Enter File Name

import sqlite3

conn = sqlite3.connect("database.db")

cursor = conn.cursor()

cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
    user_id INTEGER PRIMARY KEY,
    points INTEGER DEFAULT 0
)
""")

conn.commit()
conn.close()

4. Create Your Main Bot’s File

Create a new file called index.py and 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).

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

import database
import discord
from discord.ext import commands
import sqlite3

intents = discord.Intents.default()
intents.message_content = True 

bot = commands.Bot(command_prefix="!", intents=intents)

def get_db():
    return sqlite3.connect("database.db")

@bot.command()
async def addpoints(ctx, amount: int):
    conn = get_db()
    c = conn.cursor()
    c.execute("INSERT OR IGNORE INTO users (user_id, points) VALUES (?,0)", (ctx.author.id,))
    c.execute("UPDATE users SET points = points + ? WHERE user_id = ?", (amount, ctx.author.id))
    conn.commit()
    conn.close()
    await ctx.send(f"{ctx.author.mention} gained {amount} points!")

@bot.command()
async def points(ctx):
    conn = get_db()
    c = conn.cursor()
    c.execute("SELECT points FROM users WHERE user_id=?", (ctx.author.id,))
    result = c.fetchone()
    conn.close()
    await ctx.send(f"{ctx.author.mention} has {result[0] if result else 0} points!")

bot.run("YOUR_BOT_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