How to Use SQLite For Your NodeJS Discord Bot

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


Packages:

  • discord.js: A Node.js library for building bots and applications that interact with Discord.
  • sqlite3: A Node.js library for working with SQLite databases using SQL queries.

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.js then paste the following code.

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

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

const sqlite3 = require('sqlite3').verbose();

const conn = new sqlite3.Database("database.db");

conn.run(`
CREATE TABLE IF NOT EXISTS users (
    user_id INTEGER PRIMARY KEY,
    points INTEGER DEFAULT 0
)
`);

conn.close();

4. 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, Events } = require('discord.js');
require('./database');

const sqlite3 = require('sqlite3').verbose();

function getDb() {
  return new sqlite3.Database('database.db');
}

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

client.on(Events.MessageCreate, async (message) => {
  if (!message.content.startsWith('!') || message.author.bot) return;

  const args = message.content.slice(1).trim().split(/ +/);
  const command = args.shift().toLowerCase();

  if (command === 'addpoints') {
    const amount = parseInt(args[0]);
    if (isNaN(amount)) return;

    const db = getDb();
    db.run(`INSERT OR IGNORE INTO users (user_id, points) VALUES (?, 0)`, [message.author.id]);
    db.run(`UPDATE users SET points = points + ? WHERE user_id = ?`, [amount, message.author.id]);
    db.close();
    message.channel.send(`${message.author} gained ${amount} points!`);
  }

  if (command === 'points') {
    const db = getDb();
    db.get(`SELECT points FROM users WHERE user_id = ?`, [message.author.id], (err, row) => {
      const points = row ? row.points : 0;
      db.close();
      message.channel.send(`${message.author} has ${points} points!`);
    });
  }
});

client.login("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