Ad

Error When Connecting To Database

I'm doing a bot with the coin system and when you try to connect it to database gets this error.
Code:

const Discord = require("discord.js");
const bot = new Discord.Client({disableEveryone: true});
const sql = require("sqlite");
const db = sql.open('./coin.sqlite', { Promise });

db.get(`SELECT * FROM coins WHERE userId = [message.author.id]`).then(row => {
  if (!row) { // Can't find the row.
    db.run("INSERT INTO coins (userId, coins) VALUES (?, ?)", [message.author.id, 0]);
  } else {  // Can find the row.
    let curAmt = Math.floor(Math.random() * 5) +0.3 (row.coins + curAmt);
    if (curAmt > row.coins) {
      row.coins = curAmt;
      db.run(`UPDATE coins SET coins = ${row.coins + curAmt}, WHERE userId = [message.author.id]`);
    }
    db.run(`UPDATE coins SET coins = ${row.coins + curAmt} WHERE userId = [message.author.id]`);
  }
}).catch(() => {
  console.error; // Log those errors.
  db.run("CREATE TABLE IF NOT EXISTS coins (userId TEXT, coins INTEGER)").then(() => {
    db.run("INSERT INTO scores (userId, coins) VALUES (?, ?)", [message.author.id, 0]);
  });
});

bot.login(tokenfile.token);

Error:

db.get(`SELECT * FROM coins WHERE userId = [message.author.id]`).then(row => {
   ^

TypeError: db.get is not a function
    at Object.<anonymous> (C:\Users\Илья\Desktop\JyxoBot\Jyxo\index.js:54:4)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3
[nodemon] app crashed - waiting for file changes before starting...

The bot doesn't run, I don't understand what is the problem, everything seems right to me.

Ad

Answer

sql.open('./coin.sqlite', { Promise });

Returns a promise, so when you run db.get(), you are actually trying to use that method on an unresolved promise.

What you need to do is:

const Discord = require("discord.js");
const bot = new Discord.Client({disableEveryone: true});
const sql = require("sqlite");
const db = sql.open('./coin.sqlite', { Promise });

sql.open('./coin.sqlite', { Promise })
    .then((db) => {
        runApp(db);               
    }).catch((err) => {
        console.log(err);
        process.exit(1);
    });

const runApp = (db) => {
    client.on("message", message => {
        if (message.author.bot) return;
        if (message.channel.type !== "text") return;
        if (message.content.startsWith("ping")) {
            message.channel.send("pong!");
        }
        db.get(`SELECT * FROM coins WHERE userId = ${message.author.id}`).then(row => {
            if (!row) { // Can't find the row.
                db.run("INSERT INTO coins (userId, coins) VALUES (?, ?)", [message.author.id, 0]);
            } else {  // Can find the row.
                let curAmt = Math.floor(Math.random() * 5) +0.3 (row.coins + curAmt);
                if (curAmt > row.coins) {
                    row.coins = curAmt;
                    db.run(`UPDATE coins SET coins = ${row.coins + curAmt}, WHERE userId = ${message.author.id}`);
                }
                db.run(`UPDATE coins SET coins = ${row.coins + curAmt} WHERE userId = ${message.author.id}`);
            }
       }).catch(() => {
           console.error; // Log those errors.
           db.run("CREATE TABLE IF NOT EXISTS coins (userId TEXT, coins INTEGER)").then(() => {
               db.run("INSERT INTO scores (userId, coins) VALUES (?, ?)", [message.author.id, 0]);
           });
       });

       bot.login(tokenfile.token);

    };
};

This will wait for the promise to resolve and return the db object. See the examples at: https://www.npmjs.com/package/sqlite for more details.

You also needed to put the code in the discord client's message handler as shown in the guide: https://anidiotsguide_old.gitbooks.io/discord-js-bot-guide/coding-guides/storing-data-in-an-sqlite-file.html

I also separated out most of your app code into a function just to make it easier to read. The db object returned from the promise is passed into this function so it can be used.

Hope this helps!

Ad
source: stackoverflow.com
Ad