Skip to content

Commit 5457ef3

Browse files
committed
Add module responsible for loading env-variables
This module tries to load 'optional' env-variables and falls back to pre-set default values if no env-variable exists. Variables can simply be imported like `from environment import PREFIX` Loading the prefix was also moved there.
1 parent bf9adf3 commit 5457ef3

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

src/environment.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import os
2+
3+
4+
def load_env(key: str, default: str) -> str:
5+
"""
6+
os.getenv() wrapper that handles the case of None-types for not-set env-variables\n
7+
8+
:param key: name of env variable to load
9+
:param default: default value if variable couldn't be loaded
10+
:return: value of env variable or default value
11+
"""
12+
value = os.getenv(key)
13+
if value:
14+
return value
15+
print(f"Can't load env-variable for: '{key}' - falling back to DEFAULT {key}='{default}'")
16+
return default
17+
18+
19+
TOKEN = os.getenv("TOKEN") # reading in the token from config.py file
20+
21+
# loading optional env variables
22+
PREFIX = load_env("PREFIX", "b!")
23+
VERSION = load_env("VERSION", "unknown") # version of the bot
24+
OWNER_NAME = load_env("OWNER_NAME", "unknown") # owner name with tag e.g. pi#3141
25+
OWNER_ID = int(load_env("OWNER", "100000000000000000")) # discord id of the owner

src/main.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@
44
import discord
55
from discord.ext import commands
66

7-
intents = discord.Intents.all()
8-
9-
TOKEN = os.getenv("TOKEN") # reading in the token from config.py file
7+
from environment import PREFIX, TOKEN
108

119
# path for databases or config files
1210
if not os.path.exists('data/'):
@@ -33,9 +31,8 @@
3331
logger.addHandler(file_logger)
3432
logger.addHandler(console_logger)
3533

36-
prefix = "b!"
37-
38-
bot = commands.Bot(command_prefix=prefix, intents=intents)
34+
intents = discord.Intents.all()
35+
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
3936

4037

4138
# login message

0 commit comments

Comments
 (0)