Add support for loading config values from environment variables

master
Dragory 2019-12-03 02:40:50 +02:00
parent 1007dc0dd1
commit 8dd6513ca3
3 changed files with 34 additions and 7 deletions

View File

@ -4,6 +4,8 @@
* **Change default configuration format to .ini**
* Existing `config.json` files will continue to work and will not be deprecated
* This makes the default configuration format for the bot much more approachable than JSON
* Config values can now also be loaded from environment variables
(see [Configuration](docs/configuration.md#environment-variables) for more details)
* New rewritten instructions for setting up and using the bot
* New easy-to-use `start.bat` file for Windows
* Update several package dependencies

View File

@ -7,6 +7,7 @@ Haven't set up the bot yet? Check out [Setting up the bot](setup.md) first!
- [Required options](#required-options)
- [Other options](#other-options)
- [config.ini vs config.json](#configini-vs-configjson)
- [Environment variables](#environment-variables)
## Configuration file
All bot options are saved in a configuration file in the bot's folder.
@ -313,3 +314,23 @@ by escaping the newline with a backslash (`\ `):
This is the second line of the greeting."
}
```
## Environment variables
Config options can be passed via environment variables.
To get the name of the corresponding environment variable for an option, convert the option to SNAKE_CASE with periods
being replaced by two underscores and add `MM_` as a prefix. If adding multiple values for the same option, separate the
values with two pipe characters: `||`.
Examples:
* `mainGuildId` -> `MM_MAIN_GUILD_ID`
* `commandAliases.mv` -> `MM_COMMAND_ALIASES__MV`
* From:
```ini
inboxServerPermission[] = kickMembers
inboxServerPermission[] = manageMessages
```
To:
`MM_INBOX_SERVER_PERMISSION=kickMembers||manageMessages`
The `port` option also accepts the environment variable `PORT` without a prefix, but `MM_PORT` takes precedence.

View File

@ -137,17 +137,21 @@ for (const [key, value] of Object.entries(process.env)) {
.replace(/([a-z])_([a-z])/g, (m, m1, m2) => `${m1}${m2.toUpperCase()}`)
.replace('__', '.');
userConfig[configKey] = process.env[key];
userConfig[configKey] = value.includes('||')
? value.split('||')
: value;
loadedEnvValues++;
}
if (process.env.PORT && !process.env.MM_PORT) {
// Special case: allow common "PORT" environment variable without prefix
userConfig.port = process.env.PORT;
loadedEnvValues++;
}
if (loadedEnvValues > 0) {
console.log(`Loaded ${loadedEnvValues} values from environment variables`);
}
if (process.env.PORT) {
// Special case: allow common "PORT" environment variable without prefix
userConfig.port = process.env.PORT;
console.log(`Loaded ${loadedEnvValues} ${loadedEnvValues === 1 ? 'value' : 'values'} from environment variables`);
}
// Convert config keys with periods to objects