【问题标题】:Error when connecting to database连接数据库时出错
【发布时间】:2019-01-12 00:49:55
【问题描述】:

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

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

机器人没有运行,我不明白问题出在哪里,我觉得一切正常。

【问题讨论】:

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


    【解决方案1】:
    sql.open('./coin.sqlite', { Promise });
    

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

    你需要做的是:

    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 对象被传递到这个函数中,所以它可以被使用。

    希望这会有所帮助!

    【讨论】:

    • SyntaxError: await 仅在异步函数中有效
    • 如果我都输入正确,我赶紧告诉你错误没有修复
    • 我的错,再次编辑了我的答案。现在应该可以了。
    • 建表,启动bot,但又出现错误
    • (node:17404) UnhandledPromiseRejectionWarning: ReferenceError: message is not defined
    猜你喜欢
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2020-09-08
    • 2012-02-02
    • 2014-06-09
    相关资源
    最近更新 更多