Refactored database connection and table creation logic in index.js
This commit is contained in:
parent
773e386329
commit
a49074c566
1 changed files with 67 additions and 90 deletions
157
index.js
157
index.js
|
@ -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) => {
|
||||
if (err) {
|
||||
console.error("Error opening database", err.message);
|
||||
} else {
|
||||
console.log("Connected to the SQLite database.");
|
||||
// Ensure a table exists
|
||||
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 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, '');
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
} else {
|
||||
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(() => {
|
||||
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);
|
||||
databaseConnection = new sqlite3.Database(config.sqlite.dbPath, sqlite3.OPEN_READWRITE, (err) => {
|
||||
if (err) {
|
||||
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;
|
||||
}
|
||||
resolve(JSON.parse(response.body));
|
||||
});
|
||||
} else {
|
||||
console.log("Connected to the SQLite database.");
|
||||
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;
|
||||
}
|
||||
});
|
||||
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', () => {
|
||||
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);
|
||||
} else {
|
||||
console.log("Table created or already exists.");
|
||||
require("./helpers/ready.js")(databaseConnection);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
connectToDatabase();
|
||||
|
||||
|
||||
|
||||
client.once('ready', async () => {
|
||||
console.log("Successfully logged in.");
|
||||
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
|
||||
};
|
||||
await new REST(restOptions).setToken(config.bot_token).put(Routes.applicationGuildCommands(client.user.id, config.guild_id), requestBody);
|
||||
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 {
|
||||
|
@ -224,4 +201,4 @@ async function updateActivity() {
|
|||
activities: [activityDetails]
|
||||
};
|
||||
client.user.setPresence(activityOptions);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue