discord.js / node / mysql:如何等待查询返回结果

时间:2019-12-13 21:15:38

标签: node.js discord.js node-mysql

我目前正在尝试为多个Discord服务器编写一个机器人。 问题是,代码不等待数据库返回结果。在当前情况下,我正在尝试检查消息的作者ID是否已在mysql数据库中。

我阅读了一些有关异步/等待的内容,但是我需要您的帮助以了解如何将这些内容链接在一起!

const Discord = require('discord.js');
var mysql = require('mysql');
// Discord client
const client = new Discord.Client();
// Load config file
const config = require('./config.json');
client.config = config;
// Database config
const connection = mysql.createConnection({
  host: config.mysqlHost,
  user: config.mysqlUser,
  password: config.mysqlPassword,
  database: config.mysqlDatabase
});

// Check if ownerId is already in database
function checkOwnerId(authorId) {
  var query = connection.query(
    'SELECT * FROM guilds WHERE ownerId = ?', 
    authorId, 
    function (error, results, fields) {
      // Handle error after the release.
      if (error) throw error;
      // Debug
      console.log(query.sql);
      // If match
      if (results.length > 0) return "verified";
      else return "not_verified";
  });
}

/*
 * Event will run on every single message received, from any channel or DM.
 */
client.on('message', async msg => {
  // Ignore any message that does not start with prefix and ignore itself
  if (!msg.content.startsWith(config.prefix) || msg.author.bot) return;
  // Verify in database if the author.id is already saved
  if (checkOwnerId(msg.author.id) === "not_verified") {
    // Delete the command line
    msg.delete();
    // Send pm to author with error
    msg.author.send( 
      {embed: {
        color: 15934014,
        description: 'No permission to use the bot'
      }
    });
    console.log("NOT VERIFIED");
    return;
  }
  else {
    // Continue
  }

});

// Discord bot token
client.login(config.token);

如何在数据库中验证作者ID是否已保存以及让他使用某些命令之后?预先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作,这也将允许您进行进一步的SQL查询并处理结果:

const Discord = require('discord.js');
var mysql = require('mysql');
// Discord client
const client = new Discord.Client();
// Load config file
const config = require('./config.json');
client.config = config;
// Database config
const connection = mysql.createConnection({
    host: config.mysqlHost,
    user: config.mysqlUser,
    password: config.mysqlPassword,
    database: config.mysqlDatabase
});

// Check if ownerId is already in database
function sqlQuery(query, params) {
    return new Promise((resolve, reject) => {
        connection.query(
            query, params,
            (error, results) => {
                if (error) return reject(error);
                return resolve(results);
            });
    });
}

/*
 * Event will run on every single message received, from any channel or DM.
 */
client.on('message', msg => {
    // Ignore any message that does not start with prefix and ignore itself
    if (!msg.content.startsWith(config.prefix) || msg.author.bot) return;
    // Verify in database if the author.id is already saved
    sqlQuery('SELECT * FROM guilds WHERE ownerId = ?', msg.author.id,)
        .then(results => {
            if (results.length > 0) {
                //do stuff with verified user
            } else {
                msg.delete();
                // Send pm to author with error
                msg.author.send(
                    {embed: {
                            color: 15934014,
                            description: 'No permission to use the bot'
                        }
                    });
            }
        })
        .catch(error => {
            //handle error
        });
});

// Discord bot token
client.login(config.token);