From 1a40d4ada83e903bc368e3fb6cccdceede34b5e6 Mon Sep 17 00:00:00 2001 From: Vermium Sifell Date: Tue, 5 Jul 2022 15:17:02 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=A5=20migrate=20from=20*.ts=20to=20.en?= =?UTF-8?q?v=20configs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/settings.json | 3 +++ package.json | 1 + src/config_example/database.ts | 3 --- src/config_example/discord.ts | 14 ---------- src/config_example/embed.ts | 17 ------------ src/config_example/encryption.ts | 5 ---- src/config_example/other.ts | 14 ---------- src/config_example/reputation.ts | 2 -- src/handlers/deployCommands/index.ts | 22 +++++++++------- src/handlers/devMode/index.ts | 15 +++++------ src/handlers/encryption/index.ts | 13 +++++----- src/helpers/embedBuilder/index.ts | 5 ++-- src/helpers/getEmbedConfig/index.ts | 22 ++++++++++++---- src/index.ts | 6 ++--- src/logger/index.ts | 4 +-- src/managers/database/index.ts | 19 ++++++++++++-- src/managers/index.ts | 1 + .../commands/reputation/modules/give/index.ts | 3 +-- .../commands/utility/modules/about/index.ts | 5 ++-- src/types/common/environment.d.ts | 26 +++++++++++++++++++ 20 files changed, 98 insertions(+), 102 deletions(-) delete mode 100644 src/config_example/database.ts delete mode 100644 src/config_example/discord.ts delete mode 100644 src/config_example/embed.ts delete mode 100644 src/config_example/encryption.ts delete mode 100644 src/config_example/other.ts delete mode 100644 src/config_example/reputation.ts create mode 100644 src/types/common/environment.d.ts diff --git a/.vscode/settings.json b/.vscode/settings.json index 38d1af9..edd979a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -22,5 +22,8 @@ "addWords": true, "scope": "workspace" } + }, + "[dotenv]": { + "editor.defaultFormatter": "foxundermoon.shell-format" } } diff --git a/package.json b/package.json index 08b0c96..3ca6361 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,7 @@ "crypto": "^1.0.1", "discord-api-types": "^0.36.0", "discord.js": "^13.6.0", + "dotenv": "^16.0.1", "i18n": "^0.15.0", "i18next": "^21.6.13", "i18next-async-backend": "^2.0.0", diff --git a/src/config_example/database.ts b/src/config_example/database.ts deleted file mode 100644 index 35e2e27..0000000 --- a/src/config_example/database.ts +++ /dev/null @@ -1,3 +0,0 @@ -// MongoDB connection string -export const url = - "mongodb+srv://username:password@server/database?retryWrites=true&w=majority"; diff --git a/src/config_example/discord.ts b/src/config_example/discord.ts deleted file mode 100644 index 7b22c28..0000000 --- a/src/config_example/discord.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Intents } from "discord.js"; // discord.js - -// Discord API token -export const token = ""; - -// Discord API id -export const clientId = ""; - -// Discord API intents -export const intents = [ - Intents.FLAGS.GUILDS, - Intents.FLAGS.GUILD_MESSAGES, - Intents.FLAGS.GUILD_MEMBERS, -]; diff --git a/src/config_example/embed.ts b/src/config_example/embed.ts deleted file mode 100644 index d6eebb1..0000000 --- a/src/config_example/embed.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Dependencies -import { ColorResolvable } from "discord.js"; - -// Color for successfully actions -export const successColor: ColorResolvable = "#22bb33"; - -// Color for waiting actions -export const waitColor: ColorResolvable = "#f0ad4e"; - -// Color for error actions -export const errorColor: ColorResolvable = "#bb2124"; - -// Footer text -export const footerText = "https://github.com/ZynerOrg/xyter"; - -// Footer icon -export const footerIcon = "https://github.com/ZynerOrg.png"; diff --git a/src/config_example/encryption.ts b/src/config_example/encryption.ts deleted file mode 100644 index 9d547f1..0000000 --- a/src/config_example/encryption.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Encryption algorithm -export const algorithm = "aes-256-ctr"; - -// Encryption secret (strictly 32 length) -export const secretKey = ""; diff --git a/src/config_example/other.ts b/src/config_example/other.ts deleted file mode 100644 index eefd62c..0000000 --- a/src/config_example/other.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Development features -export const devMode = false; - -// Development guild -export const guildId = ""; - -// Hoster name -export const hosterName = "someone"; - -// Hoster Url -export const hosterUrl = "https://xyter.zyner.org/customization/change-hoster"; - -// Winston log level -export const logLevel = "info"; diff --git a/src/config_example/reputation.ts b/src/config_example/reputation.ts deleted file mode 100644 index 064edc9..0000000 --- a/src/config_example/reputation.ts +++ /dev/null @@ -1,2 +0,0 @@ -// Timeout between repute someone (seconds) -export const timeout = 86400; // One day diff --git a/src/handlers/deployCommands/index.ts b/src/handlers/deployCommands/index.ts index 492e1ab..9491db5 100644 --- a/src/handlers/deployCommands/index.ts +++ b/src/handlers/deployCommands/index.ts @@ -1,12 +1,8 @@ -import { token, clientId } from "../../config/discord"; -import { devMode, guildId } from "../../config/other"; - import logger from "../../logger"; import { Client } from "discord.js"; import { REST } from "@discordjs/rest"; import { Routes } from "discord-api-types/v9"; import { RESTPostAPIApplicationCommandsJSONBody } from "discord-api-types/v10"; - import { ICommand } from "../../interfaces/Command"; export default async (client: Client) => { @@ -32,10 +28,10 @@ export default async (client: Client) => { throw new Error(`Could not gather command list: ${error}`); }); - const rest = new REST({ version: "9" }).setToken(token); + const rest = new REST({ version: "9" }).setToken(process.env.DISCORD_TOKEN); await rest - .put(Routes.applicationCommands(clientId), { + .put(Routes.applicationCommands(process.env.DISCORD_CLIENT_ID), { body: commandList, }) .then(async () => { @@ -45,11 +41,17 @@ export default async (client: Client) => { logger.error(`${error}`); }); - if (devMode) { + if (process.env.NODE_ENV !== "production") { await rest - .put(Routes.applicationGuildCommands(clientId, guildId), { - body: commandList, - }) + .put( + Routes.applicationGuildCommands( + process.env.DISCORD_CLIENT_ID, + process.env.DISCORD_GUILD_ID + ), + { + body: commandList, + } + ) .then(async () => logger.info(`Finished updating guild command list.`)) .catch(async (error) => { logger.error(`${error}`); diff --git a/src/handlers/devMode/index.ts b/src/handlers/devMode/index.ts index c7900a0..ba36b50 100644 --- a/src/handlers/devMode/index.ts +++ b/src/handlers/devMode/index.ts @@ -1,16 +1,13 @@ -// Dependencies import { Client } from "discord.js"; - import logger from "../../logger"; -// Configuration -import { devMode, guildId } from "../../config/other"; - export default async (client: Client) => { - if (!devMode) { - return client?.application?.commands?.set([], guildId).then(async () => { - return logger.verbose(`Development mode is disabled.`); - }); + if (process.env.NODE_ENV !== "production") { + return client?.application?.commands + ?.set([], process.env.DISCORD_GUILD_ID) + .then(async () => { + return logger.verbose(`Development mode is disabled.`); + }); } return logger.info(`Development mode is enabled.`); diff --git a/src/handlers/encryption/index.ts b/src/handlers/encryption/index.ts index 8b6512c..0e1c027 100644 --- a/src/handlers/encryption/index.ts +++ b/src/handlers/encryption/index.ts @@ -1,13 +1,14 @@ import crypto from "crypto"; - -import { secretKey, algorithm } from "../../config/encryption"; - import { IEncryptionData } from "../../interfaces/EncryptionData"; const iv = crypto.randomBytes(16); const encrypt = (text: crypto.BinaryLike): IEncryptionData => { - const cipher = crypto.createCipheriv(algorithm, secretKey, iv); + const cipher = crypto.createCipheriv( + process.env.ENCRYPTION_ALGORITHM, + process.env.ENCRYPTION_SECRET, + iv + ); const encrypted = Buffer.concat([cipher.update(text), cipher.final()]); return { @@ -18,8 +19,8 @@ const encrypt = (text: crypto.BinaryLike): IEncryptionData => { const decrypt = (hash: IEncryptionData) => { const decipher = crypto.createDecipheriv( - algorithm, - secretKey, + process.env.ENCRYPTION_ALGORITHM, + process.env.ENCRYPTION_SECRET, Buffer.from(hash.iv, "hex") ); diff --git a/src/helpers/embedBuilder/index.ts b/src/helpers/embedBuilder/index.ts index d93cc5c..6d6a51d 100644 --- a/src/helpers/embedBuilder/index.ts +++ b/src/helpers/embedBuilder/index.ts @@ -1,9 +1,8 @@ -import { footerText, footerIcon } from "../../config/embed"; import { MessageEmbed } from "discord.js"; export default new MessageEmbed() .setFooter({ - text: footerText, - iconURL: footerIcon, + text: process.env.EMBED_FOOTER_TEXT, + iconURL: process.env.EMBED_FOOTER_ICON, }) .setTimestamp(new Date()); diff --git a/src/helpers/getEmbedConfig/index.ts b/src/helpers/getEmbedConfig/index.ts index ccd3fdb..0d88716 100644 --- a/src/helpers/getEmbedConfig/index.ts +++ b/src/helpers/getEmbedConfig/index.ts @@ -1,18 +1,30 @@ import guildSchema from "../../models/guild"; -import * as embedConfig from "../../config/embed"; import { Guild } from "discord.js"; export default async (guild?: Guild | null) => { + const { + EMBED_COLOR_SUCCESS, + EMBED_COLOR_WAIT, + EMBED_COLOR_ERROR, + EMBED_FOOTER_TEXT, + EMBED_FOOTER_ICON, + } = process.env; + + const defaultEmbedConfig = { + successColor: EMBED_COLOR_SUCCESS, + waitColor: EMBED_COLOR_WAIT, + errorColor: EMBED_COLOR_ERROR, + footerText: EMBED_FOOTER_TEXT, + footerIcon: EMBED_FOOTER_ICON, + }; if (!guild) { - return { ...embedConfig }; + return defaultEmbedConfig; } const guildConfig = await guildSchema.findOne({ guildId: guild.id }); if (!guildConfig) { - return { - ...embedConfig, - }; + return defaultEmbedConfig; } return guildConfig.embeds; }; diff --git a/src/index.ts b/src/index.ts index c3661d7..a33abb5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,3 @@ -import { token, intents } from "./config/discord"; - import { Client, Collection } from "discord.js"; // discord.js import * as managers from "./managers"; @@ -8,7 +6,7 @@ import * as managers from "./managers"; const main = async () => { // Initiate client object const client = new Client({ - intents, + intents: ["GUILDS", "GUILD_MEMBERS", "GUILD_MESSAGES"], }); // Create command collection @@ -17,7 +15,7 @@ const main = async () => { await managers.start(client); // Authorize with Discord's API - await client.login(token); + await client.login(process.env.DISCORD_TOKEN); }; main(); diff --git a/src/logger/index.ts b/src/logger/index.ts index 0593ec9..a91f01d 100644 --- a/src/logger/index.ts +++ b/src/logger/index.ts @@ -1,13 +1,11 @@ import winston from "winston"; import "winston-daily-rotate-file"; -import { logLevel } from "../config/other"; - const { combine, timestamp, printf, errors, colorize, align, json } = winston.format; export default winston.createLogger({ - level: logLevel || "info", + level: process.env.LOG_LEVEL || "info", transports: [ new winston.transports.DailyRotateFile({ filename: "logs/combined-%DATE%.log", diff --git a/src/managers/database/index.ts b/src/managers/database/index.ts index c58af68..4b65e4f 100644 --- a/src/managers/database/index.ts +++ b/src/managers/database/index.ts @@ -1,6 +1,21 @@ import mongoose from "mongoose"; -import { url } from "../../config/database"; +import logger from "../../logger"; export const connect = async () => { - await mongoose.connect(url); + await mongoose + .connect(process.env.MONGO_URL) + .then(async (connection) => { + logger.info(`💾 Connected to database: ${connection.connection.name}`); + }) + .catch(async (e) => { + logger.error("💾 Could not connect to database", e); + }); + + mongoose.connection.on("error", async (error) => { + logger.error(`💾 ${error}`); + }); + + mongoose.connection.on("warn", async (warning) => { + logger.warn(`💾 ${warning}`); + }); }; diff --git a/src/managers/index.ts b/src/managers/index.ts index a1f3dad..4e74859 100644 --- a/src/managers/index.ts +++ b/src/managers/index.ts @@ -1,3 +1,4 @@ +import "dotenv/config"; import { Client } from "discord.js"; import * as database from "./database"; diff --git a/src/plugins/commands/reputation/modules/give/index.ts b/src/plugins/commands/reputation/modules/give/index.ts index f9970df..5416ee1 100644 --- a/src/plugins/commands/reputation/modules/give/index.ts +++ b/src/plugins/commands/reputation/modules/give/index.ts @@ -1,6 +1,5 @@ import { CommandInteraction } from "discord.js"; import getEmbedConfig from "../../../../../helpers/getEmbedConfig"; -import { timeout } from "../../../../../config/reputation"; import logger from "../../../../../logger"; import fetchUser from "../../../../../helpers/fetchUser"; import { SlashCommandSubcommandBuilder } from "@discordjs/builders"; @@ -53,7 +52,7 @@ export default { await noSelfReputation(optionTarget, user); // Check if user is on cooldown otherwise create one - await cooldown.command(interaction, timeout); + await cooldown.command(interaction, process.env.REPUTATION_TIMEOUT); switch (optionType) { case "positive": diff --git a/src/plugins/commands/utility/modules/about/index.ts b/src/plugins/commands/utility/modules/about/index.ts index 92af9cb..e3670b3 100644 --- a/src/plugins/commands/utility/modules/about/index.ts +++ b/src/plugins/commands/utility/modules/about/index.ts @@ -8,7 +8,6 @@ import { // Configurations import getEmbedConfig from "../../../../../helpers/getEmbedConfig"; -import { hosterName, hosterUrl } from "../../../../../config/other"; import { SlashCommandSubcommandBuilder } from "@discordjs/builders"; // Function @@ -45,10 +44,10 @@ export default { .setEmoji("💬") .setURL("https://discord.zyner.org"), new MessageButton() - .setLabel(`Hosted by ${hosterName}`) + .setLabel(`Hosted by ${process.env.BOT_HOSTER_NAME}`) .setStyle("LINK") .setEmoji("⚒️") - .setURL(`${hosterUrl}`) + .setURL(`${process.env.BOT_HOSTER_URL}`) ); const interactionEmbed = { diff --git a/src/types/common/environment.d.ts b/src/types/common/environment.d.ts new file mode 100644 index 0000000..4c1ee6c --- /dev/null +++ b/src/types/common/environment.d.ts @@ -0,0 +1,26 @@ +import { Snowflake, ColorResolvable } from "discord.js"; + +declare global { + namespace NodeJS { + interface ProcessEnv { + MONGO_URL: string; + DISCORD_TOKEN: string; + DISCORD_CLIENT_ID: Snowflake; + DISCORD_GUILD_ID: Snowflake; + DEVELOPMENT_MODE: boolean; + ENCRYPTION_ALGORITHM: string; + ENCRYPTION_SECRET: string; + EMBED_COLOR_SUCCESS: ColorResolvable; + EMBED_COLOR_WAIT: ColorResolvable; + EMBED_COLOR_ERROR: ColorResolvable; + EMBED_FOOTER_TEXT: string; + EMBED_FOOTER_ICON: string; + LOG_LEVEL: string; + REPUTATION_TIMEOUT: number; + BOT_HOSTER_NAME: string; + BOT_HOSTER_URL: string; + } + } +} + +export {};