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 fs = require('fs');
|
||||||
const sqlite3 = require('sqlite3').verbose();
|
const sqlite3 = require('sqlite3').verbose();
|
||||||
const request = require("request");
|
|
||||||
const config = require("./config.js");
|
const config = require("./config.js");
|
||||||
const packageInfo = require("./package.json");
|
const packageInfo = require("./package.json");
|
||||||
const terminal = require("terminal-kit").terminal;
|
|
||||||
const apiHelper = require("./helpers/api.js");
|
const apiHelper = require("./helpers/api.js");
|
||||||
const { queryMulti } = require("./helpers/helper.js");
|
const { queryMulti } = require("./helpers/helper.js");
|
||||||
const { Client, GatewayIntentBits, Partials, Collection, ActivityType, Routes, REST, EmbedBuilder } = require('discord.js');
|
const { Client, GatewayIntentBits, Partials, Collection, ActivityType, Routes, REST, EmbedBuilder } = require('discord.js');
|
||||||
const mysql = require('mysql');
|
|
||||||
|
|
||||||
const clientOptions = {
|
const clientOptions = {
|
||||||
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildPresences],
|
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildPresences],
|
||||||
|
@ -18,102 +15,72 @@ const client = new Client(clientOptions);
|
||||||
let databaseConnection;
|
let databaseConnection;
|
||||||
|
|
||||||
// Open SQLite Database
|
// Open SQLite Database
|
||||||
databaseConnection = new sqlite3.Database(config.sqlite.dbPath, sqlite3.OPEN_READWRITE, (err) => {
|
function connectToDatabase() {
|
||||||
if (err) {
|
console.log("Attempting to connect to database at:", config.sqlite.dbPath);
|
||||||
console.error("Error opening database", err.message);
|
|
||||||
} else {
|
// Check if database file exists
|
||||||
console.log("Connected to the SQLite database.");
|
if (!fs.existsSync(config.sqlite.dbPath)) {
|
||||||
// Ensure a table exists
|
console.log("Database file does not exist. Creating a new one...");
|
||||||
databaseConnection.run(`CREATE TABLE IF NOT EXISTS tableName (
|
// Create empty file
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
fs.writeFileSync(config.sqlite.dbPath, '');
|
||||||
column1 TEXT,
|
|
||||||
column2 TEXT
|
|
||||||
)`, [], function(err) {
|
|
||||||
if (err) {
|
|
||||||
console.error("Error creating table", err.message);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
function handleDisconnect() {
|
databaseConnection = new sqlite3.Database(config.sqlite.dbPath, sqlite3.OPEN_READWRITE, (err) => {
|
||||||
const mysqlConfig = {
|
if (err) {
|
||||||
"port": config.mysql.port,
|
console.error("Error opening database:", err.message);
|
||||||
"charset": 'utf8mb4',
|
if (err.code === 'SQLITE_CANTOPEN') {
|
||||||
host: config.mysql.host,
|
console.error("Failed to open database. Retrying in 2 seconds...");
|
||||||
"user": config.mysql.user,
|
setTimeout(connectToDatabase, 2000);
|
||||||
"password": config.mysql.password,
|
} else {
|
||||||
"database": config.mysql.database
|
throw err;
|
||||||
};
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
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.user.setStatus("Online");
|
||||||
client.commands = new Collection();
|
client.commands = new Collection();
|
||||||
readCommands();
|
await registerCommands();
|
||||||
updateActivity();
|
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 = [];
|
let commandData = [];
|
||||||
fs.readdirSync("./slash-commands").forEach(fileName => {
|
fs.readdirSync("./slash-commands").forEach(fileName => {
|
||||||
let commandModule = require("./slash-commands/" + fileName);
|
let commandModule = require("./slash-commands/" + fileName);
|
||||||
|
@ -129,9 +96,19 @@ async function readCommands() {
|
||||||
const requestBody = {
|
const requestBody = {
|
||||||
"body": commandData
|
"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) => {
|
client.on("guildMemberUpdate", async (newMember, oldMember) => {
|
||||||
if (newMember.partial) {
|
if (newMember.partial) {
|
||||||
try {
|
try {
|
||||||
|
@ -224,4 +201,4 @@ async function updateActivity() {
|
||||||
activities: [activityDetails]
|
activities: [activityDetails]
|
||||||
};
|
};
|
||||||
client.user.setPresence(activityOptions);
|
client.user.setPresence(activityOptions);
|
||||||
}
|
}
|
Loading…
Reference in a new issue