连接数据库时出错

时间:2018-08-04 09:31:00

标签: javascript node.js sqlite bots discord.js

我正在用硬币系统做一个机器人,当您尝试将其连接到数据库时遇到此错误。
代码:

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);

错误:

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...

机器人无法运行,我不明白问题出在哪里,一切似乎对我来说都是正确的。

1 个答案:

答案 0 :(得分:0)

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

返回一个诺言,因此,当您运行db.get()时,实际上是在尝试对未解决的诺言使用该方法。

您需要做的是:

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);

    };
};

这将等待promise解析并返回db对象。有关更多详细信息,请参见https://www.npmjs.com/package/sqlite上的示例。

您还需要按照指南中的说明将代码放入不和谐客户端的消息处理程序中:https://anidiotsguide_old.gitbooks.io/discord-js-bot-guide/coding-guides/storing-data-in-an-sqlite-file.html

我还将您的大多数应用程序代码分离为一个函数,以使其易于阅读。从promise返回的db对象将传递到此函数中,以便可以使用。

希望这会有所帮助!