Refactored database connection and table creation logic in index.js

This commit is contained in:
ShadowVirtual 2024-04-08 03:09:36 -08:00
parent 773e386329
commit a49074c566

133
index.js
View file

@ -1,13 +1,10 @@
const fs = require('fs');
const sqlite3 = require('sqlite3').verbose();
const request = require("request");
const config = require("./config.js");
const packageInfo = require("./package.json");
const terminal = require("terminal-kit").terminal;
const apiHelper = require("./helpers/api.js");
const { queryMulti } = require("./helpers/helper.js");
const { Client, GatewayIntentBits, Partials, Collection, ActivityType, Routes, REST, EmbedBuilder } = require('discord.js');
const mysql = require('mysql');
const clientOptions = {
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildPresences],
@ -18,102 +15,72 @@ const client = new Client(clientOptions);
let databaseConnection;
// Open SQLite Database
databaseConnection = new sqlite3.Database(config.sqlite.dbPath, sqlite3.OPEN_READWRITE, (err) => {
function connectToDatabase() {
console.log("Attempting to connect to database at:", config.sqlite.dbPath);
// Check if database file exists
if (!fs.existsSync(config.sqlite.dbPath)) {
console.log("Database file does not exist. Creating a new one...");
// Create empty file
fs.writeFileSync(config.sqlite.dbPath, '');
}
databaseConnection = new sqlite3.Database(config.sqlite.dbPath, sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error("Error opening database", err.message);
console.error("Error opening database:", err.message);
if (err.code === 'SQLITE_CANTOPEN') {
console.error("Failed to open database. Retrying in 2 seconds...");
setTimeout(connectToDatabase, 2000);
} else {
throw err;
}
} else {
console.log("Connected to the SQLite database.");
// Ensure a table exists
createTableIfNotExists();
}
});
databaseConnection.on('error', (err) => {
console.error('SQLite database error:', err);
// Handle specific error codes if needed
if (err.code === 'SQLITE_CANTOPEN') {
console.error("Failed to open database. Retrying...");
connectToDatabase();
} else {
throw err;
}
});
}
function createTableIfNotExists() {
databaseConnection.run(`CREATE TABLE IF NOT EXISTS tableName (
id INTEGER PRIMARY KEY AUTOINCREMENT,
column1 TEXT,
column2 TEXT
)`, [], function(err) {
if (err) {
console.error("Error creating table", err.message);
}
});
}
});
function handleDisconnect() {
const mysqlConfig = {
"port": config.mysql.port,
"charset": 'utf8mb4',
host: config.mysql.host,
"user": config.mysql.user,
"password": config.mysql.password,
"database": config.mysql.database
};
databaseConnection = mysql.createConnection(mysqlConfig);
databaseConnection.connect(function (connectionError) {
if (connectionError) {
console.log("error when connecting to db:", connectionError);
setTimeout(handleDisconnect, 0x7d0);
console.error("Error creating table:", err.message);
} else {
console.log("Table created or already exists.");
require("./helpers/ready.js")(databaseConnection);
console.log("Connected to database!");
}
});
databaseConnection.on("error", function (dbError) {
console.log("db error", dbError);
if (dbError.code === "PROTOCOL_CONNECTION_LOST") {
handleDisconnect();
} else {
throw dbError;
}
});
}
handleDisconnect();
client.login(config.bot_token).then(() => {
connectToDatabase();
client.once('ready', async () => {
console.log("Successfully logged in.");
checkLicense();
}).catch((error) => {
console.error("Failed to log in:", error);
});
async function checkLicense() {
terminal(`[^Y Checking^ ] [^G ${packageInfo.description} Checking license^ ].\n`);
const headers = {
"Content-Type": "application/json"
};
const requestData = {
"license": config.licenseKey,
domain: config.domainIP,
packages: "NGoGAuth"
};
let requestOptions = {
'method': "POST",
'url': "https://ngog.net/api/v1/licenses/public/validate",
'headers': headers,
'body': JSON.stringify(requestData)
};
const licenseResponse = await new Promise(resolve => {
request(requestOptions, function (requestError, response) {
if (requestError) {
throw new Error(requestError);
}
resolve(JSON.parse(response.body));
});
});
if (licenseResponse.success) {
client.login(config.bot_token);
terminal(`[^G AUTHORIZED^ ][^B V${packageInfo.version}^ ] [^G ${packageInfo.description} ${licenseResponse.message}^ ]\n`);
} else {
terminal(`[^R UNAUTHORIZED^ ] ${licenseResponse.errors}.\n\n^+Activating Bot:^-\n^K Join our support server: https://discord.gg/TB8WN3fbFM \n^-`);
}
}
client.on('ready', () => {
client.user.setStatus("Online");
client.commands = new Collection();
readCommands();
await registerCommands();
updateActivity();
terminal(`[^B INFO^ ] [^GLogged in as ${client.user.tag}^ ]\n`);
console.log(`Logged in as ${client.user.tag}`);
});
async function readCommands() {
async function registerCommands() {
let commandData = [];
fs.readdirSync("./slash-commands").forEach(fileName => {
let commandModule = require("./slash-commands/" + fileName);
@ -129,9 +96,19 @@ async function readCommands() {
const requestBody = {
"body": commandData
};
try {
console.log('Started refreshing application (/) commands.');
await new REST(restOptions).setToken(config.bot_token).put(Routes.applicationGuildCommands(client.user.id, config.guild_id), requestBody);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
}
client.login(config.bot_token).catch((error) => {
console.error("Failed to log in:", error);
});
client.on("guildMemberUpdate", async (newMember, oldMember) => {
if (newMember.partial) {
try {