使用动态命令编码处理Better-sqlite3,并在discord.js中使用Better-sqlite3创建库存系统

时间:2020-06-24 06:53:36

标签: discord.js better-sqlite3

好的,所以我每次遇到一个问题都讨厌问一个问题,所以我会一次问多个问题。所有问题都与discord.js机器人编程和更好的sqlite3使用有关。

  1. 我的代码结构合理,因此每个命令都具有自己的.js文件(即ping命令的ping.js)。这是一个名为index.js的中央处理脚本(此代码在每次我想启动bot时都运行):

const fs = require('fs');
const Discord = require('discord.js');
const SQLite = require("better-sqlite3");
const sql = new SQLite("./money.sqlite");
const { prefix, token } = require('./config.json');

const client = new Discord.Client();
client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

client.once('ready', async () => {
    console.log('Ready!');

    const table = sql.prepare(`SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'money';`).get();
    if (!table['count(*)']) {
        // If the table isn't there, create it and setup the database correctly.
        sql.prepare(`CREATE TABLE IF NOT EXISTS money (user TEXT, bal INTEGER);`).run();
        // Ensure that the "id" row is always unique and indexed.
        sql.prepare(`CREATE UNIQUE INDEX idx_money_id ON money (bal);`).run();
        sql.pragma("synchronous = 1");
        sql.pragma("journal_mode = wal");
    }

    const guild = client.guilds.cache.get("711769157078876305"); //the bot is server dedicated so dont worry
    guild.members.cache.forEach(user => {
        if (!user.user.bot) {
            client.setScore = sql.prepare(`INSERT OR REPLACE INTO money (user, bal) VALUES (@user, @bal);`);
            client.setScore.run({
                user: user.id,
                bal: 0
            });
            //this checks if the get() function works as intended (that is returning 0) and it does
            console.log(user.user.username);
            const data = sql.prepare(`SELECT * FROM money WHERE user = ?`).get(user.id);
            console.log(data.bal);
        }
    });

    // And then we have two prepared statements to get and set the score data.
    client.getScore = sql.prepare(`SELECT * FROM money WHERE user = ?`);
    client.setScore = sql.prepare(`INSERT OR REPLACE INTO money (user, bal) VALUES (@user, @bal);`);
    sql.prepare(`INSERT OR REPLACE INTO money (bal) VALUES (0);`).run();
});

client.login(token);

client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot || message.channel.type !== 'text') return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const commandName = args.shift().toLowerCase();

    const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

    try {
        command.execute(message, args);
    }
    catch (error) {
        console.error(error);
        message.channel.send('Error, failed to execute command.');
    }
});

上面的代码有效。现在,这是单独文件上的balance命令的代码(与此无关的所有其他命令都运行良好):

const Discord = require('discord.js');
const SQLite = require("better-sqlite3");

module.exports = {
    name: 'balance',
    description: 'Shows the amount of money you have.',
    execute(message, args) {
        const sql = new SQLite("./money.sqlite"); //i suspect this line is the cause
        console.log(message.author.id);
        const data = sql.prepare(`SELECT bal FROM money WHERE user = ${message.author.id}`);
        console.log(data.bal);

        const infoScreen = new Discord.MessageEmbed()
            .setColor('#03fc24')
            .setTitle(`Money Balance of ${message.author.tag}`)
            .setDescription(`Rank: coming soon`)
            .addField("Balance:", `${data.bal}`)
            .setTimestamp();
        return message.channel.send(infoScreen);
    }
}
//Above code returns undefined instead of 0

我不知道如何解决此问题,因为我在这里查找的所有其他问题都在1个脚本中包含了所有命令代码。

  1. 我想使用更好的sqlite3创建清单系统。但是我真的不知道该怎么办。

我想这样做,以便您可以存储具有可自定义统计信息的项目,例如:

{
  name: "name",
  someArray = [3, 6, 9],
  editableStuff = "hi"
}

我也希望这样做,以便您可以根据需要使用一些命令来添加和删除项目。请注意,这些命令具有各自的脚本,就像我上面提到的一样。

哎呀,那是很多打字。欢迎回答以上列出的任何一个问题。

-Kenanny

0 个答案:

没有答案
相关问题