1

I'm making a discord bot and I have run into a run problem with database.

I have two databases: one is for keeping stats(works fine), other is configs. Whenever I run needed command and try to read data from the configs database it for some reason tries to read from the stats one. I have looked through the code and I can't seem to find the problem. When command is run, I get this in log:

SQLITE_ERROR: no such column: stats.guild_id

Here are the two files. One is for the main bot script other is command script that is run.

Main script:

const bot = new Discord.Client({disableEveryone: true});
const fs = require("fs");
const localconfig = JSON.parse(fs.readFileSync("./local-config.json", "utf8"));
const wordbanks = JSON.parse(fs.readFileSync("./modules/wordbanks.json", "utf8"));
const antilang = require("./modules/anti-lang.js");
const Sequelize = require("sequelize");

const seqStats = new Sequelize('database', 'user', 'password', {
    host: 'localhost',
    dialect: 'sqlite',
    logging: false,
    storage: './db/stats.sqlite',
});

const seqConfig = new Sequelize('database', 'user', 'password', {
    host: 'localhost',
    dialect: 'sqlite',
    logging: false,
    storage: './db/configs.sqlite',
});

const Stats = seqStats.define('stats', {
    id: {
        type: Sequelize.STRING,
        unique: true,
    primaryKey: true,
    },
    username: Sequelize.STRING,
    xp_bal: {
        type: Sequelize.INTEGER,
        defaultValue: 0,
        allowNull: false,
    },
  money_bal: {
    type: Sequelize.INTEGER,
    defaultValue: 0,
    allowNull: false,
  },
  warn_bal: {
    type: Sequelize.INTEGER,
    defaultValue: 0,
    allowNull: false,
  },
  mute_bal: {
    type: Sequelize.INTEGER,
    defaultValue: 0,
    allowNull: false,
  },
    kick_bal: {
        type: Sequelize.INTEGER,
        defaultValue: 0,
        allowNull: false,
    },
  ban_bal: {
    type: Sequelize.INTEGER,
    defaultValue: 0,
    allowNull: false,
    },
    }, {
        timestamps: false,
});

const Configs = seqConfig.define('configs', {
    server_id: {
        type: Sequelize.INTEGER,
        unique: true,
        primaryKey: true,
    },
    guild_id: {
        type: Sequelize.STRING,
        unique: true,
        allowNull: false,
    },
    prefix: {
        type: Sequelize.STRING,
        defaultValue: "$",
        allowNull: false,
    },
    configs_active: {
        type: Sequelize.STRING,
        defaultValue: "NO",
        allowNull: false,
    },
    stats_active :{
        type: Sequelize.STRING,
        defaultValue: "NO",
        allowNull: false,
    },
    defaultRole: {
        type: Sequelize.STRING,
        defaultValue: "NONE",
        allowNull: false,
    },
    modLogsChannel: {
        type: Sequelize.STRING,
        defaultValue: "NONE",
        allowNull: false,
    },
    economyLogsChannel: {
        type: Sequelize.STRING,
        defaultValue: "NONE",
        allowNull: false,
    },
    welcomeChannel: {
        type: Sequelize.STRING,
        defaultValue: "NONE",
        allowNull: false,
    },
    chatLogsChannel: {
        type: Sequelize.STRING,
        defaultValue: "NONE",
        allowNull: false,
    },
    todoChannel: {
        type: Sequelize.STRING,
        defaultValue: "NONE",
        allowNull: false,
    },
    suggestionsChannel: {
        type: Sequelize.STRING,
        defaultValue: "NONE",
        allowNull: false,
    },
    bugReportsChannel: {
        type: Sequelize.STRING,
        defaultValue: "NONE",
        allowNull: false,
        },
    }, {
    timestamps: false,
});

bot.on("ready", async () => {
    antilang(bot);
    Stats.sync();
        Configs.sync();
    console.log(`${bot.user.username} is online!`);
});

//==============Command Files Section================
bot.commands = new Discord.Collection();
bot.aka = new Discord.Collection();

fs.readdir("./commands", (err, files) => {

    if (err) console.log(err)

    let jsfile = files.filter(f => f.split(".").pop() === "js")
    if (jsfile.length <= 0) {
        return console.log("[LOGS] Couldn't Find Commands!");
    }

    jsfile.forEach((f, i) => {
        let pull = require(`./commands/${f}`);
        bot.commands.set(pull.config.name, pull);
        pull.config.aka.forEach(aka => {
            bot.aka.set(aka, pull.config.name)
        });
    });
});

//==============Bot Joins Guild Section================
bot.on("guildCreate", async (guild) => {
    console.log("Joined new guild: " + guild.name + " with ID: " + guild.id + ".");

        const configs = await Configs.findOne({where: { server_id: guild.id } });

        if (!configs){
            Configs.create({
                    server_id: guild.id,
                    guild_id: `${guild.id}`,
            });
            console.log(`No records found for ${guild.name}(${guild.id}). Created new entry.`);
        }
});

//==============Bot Leaves Guild Section================
bot.on("guildDelete", async (guild) => {
    console.log("Left guild: " + guild.name + " with ID: " + guild.id + ".");
});

//==============Member Joins Guild Section================
bot.on("guildMemberAdd", async (member) => {
    console.log(`New member ${member.user.username} has joined guild ${member.guild.name}.`);
    const configs = await Configs.findOne({where: { server_id: member.guild.id } });
    const configs_active = configs.get("configs_active");
    if(configs_active == "YES"){
        const defaultRole = configs.get("defaultRole");
        let defRole = member.guild.roles.cache.find(r => r.name === defaultRole);
        member.roles.add(defRole);

        const guild_id = configs.get("guild_id");
        const welcomeChannel = configs.get("welcomeChannel");
        if(welcomeChannel == "NONE"){
            return;
        } else {
            bot.guilds.resolve(guild_id).channels.resolve(welcomeChannel).send(`A member has joined: ${member.user.username} :partying_face:`);
        }
    }
        const stats = await Stats.findOne({ where: { id: member.id } });
        if (!stats) {
                Stats.create({
                        id: member.id,
                        username: member.user.username,
                });
                console.log(`No records found for ${member.user.username}(${member.user.id}). Created new entry.`);
            }
});

//==============Member Leaves Guild Section================
bot.on("guildMemberRemove", async (member) => {
    if(member.id != bot.user.id){
        console.log("Member " + member.user.username + " has left the guild.");
        const configs = await Configs.findOne({where: { server_id: member.guild.id } });
        const configs_active = configs.get("configs_active");
        if(configs_active == "YES"){
            const guild_id = configs.get("guild_id");
            const welcomeChannel = configs.get("welcomeChannel");
            if(welcomeChannel == "NONE"){
                return;
            } else {
                bot.guilds.resolve(localconfig.logsguild).channels.resolve(localconfig.welcomeChannel).send(`A member has left: ${member.user.username} :disappointed_relieved:`);
            }
        }
    } else {
        return;
    }
});

//==============onMessage Section================
bot.on("message", async message => {

    if(message.author.bot){
      return;
    } else if (message.channel.type === "dm") {
        return message.channel.send("Please only speak to me in servers that I'm in.\nI'm not made to be your personal servant!");
    } else if (message.mentions.has(bot.user)){
          let index = Math.floor(Math.random() * wordbanks.tagreplies.length);
          message.channel.send(wordbanks.tagreplies[index]);
    }

  let xpAmount = Math.floor(Math.random() * (15 - 1) + 1);
  let moneyAmount = Math.floor(Math.random() * (15 - 1) + 1);

  const stats = await Stats.findOne({ where: { id: message.author.id } });
  if (!stats) {
            console.log(`Can't find any database records for ${message.author.username}(${message.author.id}).`)
  } else {
        const money_bal = stats.get("money_bal");
        const xp_bal = stats.get("xp_bal");
            if(xp_bal == "Infinity"){
                    console.log(`${message.author.username} has infinite xp.`);
                    const editMoney = await Stats.update({ money_bal: money_bal + moneyAmount }, { where: { id: message.author.id } });
            } else if(money_bal == "Infinity"){
                    console.log(`${message.author.username} has infinite money.`);
                    const editXP = await Stats.update({ xp_bal: xp_bal + xpAmount }, { where: { id: message.author.id } });
            } else if(money_bal == "Infinity" && xp_bal == "Infinity"){
                console.log(`${message.author.username} has infinite money & xp.`);
            } else {
                const editMoney = await Stats.update({ money_bal: money_bal + moneyAmount }, { where: { id: message.author.id } });
                const editXP = await Stats.update({ xp_bal: xp_bal + xpAmount }, { where: { id: message.author.id } });
            }
  }

    bot.emit('checkLang', message, Stats, Configs);
//==============Command Call Section================
    let prefix = localconfig.prefix;

    if (message.author.bot || message.channel.type === "dm") return;
    if (!message.content.startsWith(prefix)) return;
    let args = message.content.slice(prefix.length).split(' ');
    let cmd = args.shift().toLowerCase();
    let commandfile = bot.commands.get(cmd.slice(0)) || bot.commands.get(bot.aka.get(cmd.slice(0)))
    if (commandfile) commandfile.run(bot, message, args, Stats, Configs)
});

bot.login(localconfig.logintoken);

Command Script:

const Discord = require("discord.js");
const Sequelize = require("sequelize");

module.exports.run = async (bot, message, args, Configs) => {
  const configs = await Configs.findOne({where: { guild_id: message.guild.id } });
  const configs_active = configs.get("configs_active");
  const stats_active = configs.get("stats_active");
  const prefix = configs.get("prefix");
  const defRole = configs.get("defaultRole");
  const modLogsChannel = configs.get("modLogsChannel");
  const economyLogsChannel = configs.get("economyLogsChannel");
  const welcomeChannel = configs.get("welcomeChannel");
  const chatLogsChannel = configs.get("chatLogsChannel");
  const todoChannel = configs.get("todoChannel");
  const suggestionsChannel = configs.get("suggestionsChannel");
  const bugReportsChannel = configs.get("bugReportsChannel");

  let testEmbed = new Discord.MessageEmbed()
  .setTitle("BOT TEST")
  .setDescription("Config Test For Bot")
  .addField("Configs Active:", configs_active)
  .addField("Stats Active:", stats_active)
  .addField("Prefix:", prefix)
  .addField("Default Role:", defRole)
  .addField("ModLogs ID:", modLogsChannel)
  .addField("Economy ID:", economyLogsChannel)
  .addField("Welcome ID:", welcomeChannel)
  .addField("ChatLogs ID", chatLogsChannel)
  .addField("TODO ID:", todoChannel)
  .addField("Suggestions ID:", suggestionsChannel)
  .addField("Bug Reports ID:", bugReportsChannel)

  message.channel.send({embed: testEmbed});
}

module.exports.config = {
         name: "test",
         aka: ["testing"],
         usage: "$test",
         description: "Test",
         accessableby: "Anyone"
 }

Thanks for help in advance!

1
  • Why not just use 2 tables in 1 database?
    – SnowyShiro
    Jun 24, 2020 at 23:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.