Passage en fichier .env/variables d'environnement

This commit is contained in:
Melaine Gérard 2024-10-30 13:27:59 +01:00
parent 9393a0aed1
commit f5879c849e
7 changed files with 36 additions and 6 deletions

2
.env.example Normal file
View File

@ -0,0 +1,2 @@
TOKEN="BOT_TOKEN"
GUILD_ID="1234567890"

5
.gitignore vendored
View File

@ -6,5 +6,6 @@ dist/
*.iml
tsconfig.tsbuildinfo
data/*.json
!data/*.example.json
.env
.env.*
!.env.example

View File

@ -1,3 +0,0 @@
{
"token": "YOUR_DISCORD_TOKEN"
}

13
package-lock.json generated
View File

@ -10,6 +10,7 @@
"license": "ISC",
"dependencies": {
"discord.js": "^14.16.2",
"dotenv": "^16.4.5",
"glob": "^11.0.0",
"typescript": "^5.6.2"
}
@ -312,6 +313,18 @@
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/dotenv": {
"version": "16.4.5",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz",
"integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/eastasianwidth": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",

View File

@ -14,6 +14,7 @@
"license": "ISC",
"dependencies": {
"discord.js": "^14.16.2",
"dotenv": "^16.4.5",
"glob": "^11.0.0",
"typescript": "^5.6.2"
}

View File

@ -4,6 +4,7 @@ import {Client, Collection, GatewayIntentBits} from "discord.js";
import {Handler} from "./Handler";
import {Command} from "./Command";
import {SubCommand} from "./SubCommand";
import {Config} from "./LoadConfig";
export class CustomClient extends Client implements ICustomClient {
config: IConfig;
@ -18,8 +19,11 @@ export class CustomClient extends Client implements ICustomClient {
return GatewayIntentBits[a as keyof typeof GatewayIntentBits];
}),
})
// On ajoute le support de dotenv pour la config plutôt qu'un fichier JSON
require('dotenv').config();
this.config = require(`${process.cwd()}/data/config.json`);
// On charge dynamiquement la config
this.config = Config.load();
this.handler = new Handler(this);
this.commands = new Collection();
this.subCommands = new Collection();

View File

@ -0,0 +1,12 @@
import dotenv from 'dotenv';
import type { IConfig } from '../interfaces/IConfig';
export class Config {
public static load(): IConfig {
dotenv.config();
return new Proxy<IConfig>({} as IConfig, {
get: (_, prop: string): string | undefined =>
process.env[prop.split(/(?=[A-Z])/).join('_').toUpperCase()]
});
}
}