feat(config): config service

This commit is contained in:
Slincnik 2024-12-11 15:11:28 +03:00
parent 9a00f82d03
commit b634d9347d
No known key found for this signature in database
7 changed files with 96 additions and 55 deletions

2
.gitignore vendored
View file

@ -3,7 +3,7 @@
Thumbs.db Thumbs.db
# Bot Configuration # Bot Configuration
/config.js /config.json
# DB # DB
/giveaways.json /giveaways.json

View file

@ -1,50 +0,0 @@
export default {
/* The token of your Discord Bot */
token: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
/* UserID of your Discord Bot */
userId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
/* The URL of the MongoDB database */
mongoDB: "mongodb://127.0.0.1:27017/discordbot",
/* Set to true for production */
/* If set to false, commands only will be registered on the support.id server */
production: true,
/* Spotify */
spotify: {
clientId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
clientSecret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
},
/* YouTube Cookie */
youtubeCookie: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
/* Support server */
support: {
id: "123456789098765432", // The ID of the support server
logs: "123456789098765432", // The channel's ID for logs on the support server (when bot joins or leaves a guild)
invite: "https://discord.gg/discord", // Invite link to the support server
},
/* Dashboard configuration */
/* dashboard: {
enabled: false, // Whether the dashboard is enabled or not
maintanceKey: "letmein", // Maintance key
port: 80, // Dashboard port
domain: "http://localhost", // The base URL of the dashboard without / at the end
secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX", // Your Bot's Client Secret
logs: "123456789098765432", // The channel ID for logs
}, */
/* Embeds defaults */
embed: {
color: "#00FF00", // Color
footer: {
text:
"My Discord Bot | v" +
import("./package.json", {
with: { type: "json" },
}).version, // Footer text
},
},
/* Bot's owner informations */
owner: {
id: "123456789098765432", // The ID of the bot's owner
},
/* Add your own API keys here */
apiKeys: {},
};

26
config.sample.json Normal file
View file

@ -0,0 +1,26 @@
{
"token": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"userId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"mongoDB": "mongodb://127.0.0.1:27017/discordbot",
"production": true,
"spotify": {
"clientId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"clientSecret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
},
"youtubeCookie": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"support": {
"id": "123456789098765432",
"logs": "123456789098765432",
"invite": "https://discord.gg/discord"
},
"embed": {
"color": "#00FF00",
"footer": {
"text": "My Discord Bot | v1.0.0"
}
},
"owner": {
"id": "123456789098765432"
},
"apiKeys": {}
}

View file

@ -10,7 +10,6 @@ import { promises as fs } from "fs";
import { setTimeout } from "timers/promises"; import { setTimeout } from "timers/promises";
import mongoose from "mongoose"; import mongoose from "mongoose";
import config from "../../config.js";
import * as emojis from "../../emojis.json"; import * as emojis from "../../emojis.json";
import langs from "../languages/language-meta.js"; import langs from "../languages/language-meta.js";
import logger from "../helpers/logger.js"; import logger from "../helpers/logger.js";

View file

@ -1,3 +1,4 @@
import path from "node:path"; import path from "node:path";
export const PROJECT_ROOT = path.join(import.meta.dirname, ".."); export const PROJECT_ROOT = path.join(import.meta.dirname, "..");
export const CONFIG_PATH = path.join(PROJECT_ROOT, "..", "config.json");

View file

@ -0,0 +1,63 @@
import fs from "fs";
import { CONFIG_PATH } from "../../constants/index.js";
import logger from "../../helpers/logger.js";
class ConfigService {
constructor() {
this.config = this.#loadConfig();
}
/**
*
* @param {string} key - key of the config
* @returns {*} - value of the config
*/
get(key) {
const keys = key.split(".");
return keys.reduce((config, k) => (config && config[k] !== undefined ? config[k] : undefined), this.config);
}
/**
* Set a config value.
* @param {string} key - key of the config to set
* @param {*} value - value to set
*/
set(key, value) {
const keys = key.split(".");
keys.reduce((config, k, i) => {
if (i === keys.length - 1) {
config[k] = value;
} else {
config[k] = config[k] || {};
}
return config[k];
}, this.config);
this.#saveConfig();
}
/**
* Load the config from the file.
* @returns {Config} - loaded config
*/
#loadConfig() {
if (fs.existsSync(CONFIG_PATH)) {
return JSON.parse(fs.readFileSync(CONFIG_PATH, "utf-8"));
} else {
logger.error("Config file not found");
process.exit(1);
}
}
/**
* Save the config to the file.
*/
#saveConfig() {
try {
fs.writeFileSync(CONFIG_PATH, JSON.stringify(this.config, null, 4), "utf-8");
} catch (e) {
logger.error("Failed to save config: ", e);
}
}
}
export default ConfigService;

View file

@ -1,9 +1,9 @@
import { Client } from "discord.js"; import { Client } from "discord.js";
import { config } from "../../config.js";
import MongooseAdapter from "../adapters/database/MongooseAdapter.js"; import MongooseAdapter from "../adapters/database/MongooseAdapter.js";
import { init as initCommands } from "../handlers/command-handler/index.js"; import { init as initCommands } from "../handlers/command-handler/index.js";
import { init as initEvents } from "../handlers/event-handler/index.js"; import { init as initEvents } from "../handlers/event-handler/index.js";
import logger from "../helpers/logger.js"; import logger from "../helpers/logger.js";
import configService from "../services/config/index.js";
export class ExtendedClient extends Client { export class ExtendedClient extends Client {
/** /**
@ -11,14 +11,16 @@ export class ExtendedClient extends Client {
*/ */
constructor(options) { constructor(options) {
super(options); super(options);
this.adapter = new MongooseAdapter(config.mongoDB);
this.configService = new configService();
this.adapter = new MongooseAdapter(this.configService.get("mongoDB"));
} }
async init() { async init() {
try { try {
await this.adapter.connect(); await this.adapter.connect();
return this.login(config.token) return this.login(this.configService.get("token"))
.then(async () => await Promise.all([initCommands(), initEvents()])) .then(async () => await Promise.all([initCommands(), initEvents()]))
.catch(console.error); .catch(console.error);
} catch (error) { } catch (error) {