Skip to content

Commit

Permalink
add error handling for env vars; run pre-commit (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
pmayd authored Sep 8, 2020
1 parent 3544253 commit e793c8b
Showing 1 changed file with 27 additions and 6 deletions.
33 changes: 27 additions & 6 deletions src/karmabot/settings.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,44 @@
import logging
import os
import re
from pathlib import Path

from dotenv import load_dotenv
from slackclient import SlackClient


def _get_env_var(env_var: str):
env_var_value = os.environ.get(env_var)

# explicit check for None as None is returned by environ.get for non existing keys
if env_var_value is None:
raise KeyError(
f"{env_var} was not found. Please check your .karmabot file as well as the README.md."
)

if not env_var_value:
raise ValueError(
f"{env_var} was found but seems empty. Please check your .karmabot file as well as the README.md."
)

return env_var_value


dotenv_path = Path(".").resolve() / ".karmabot"
if dotenv_path.exists():
logging.info("Loading environmental variables from .karmabot.")
load_dotenv(dotenv_path)

# Environment variables
KARMABOT_ID = os.environ.get("KARMABOT_SLACK_USER")
SLACK_TOKEN = os.environ.get("KARMABOT_SLACK_TOKEN")
SLACK_INVITE_TOKEN = os.environ.get("KARMABOT_SLACK_INVITE_USER_TOKEN")
DATABASE_URL = os.environ.get("KARMABOT_DATABASE_URL")
KARMABOT_ID = _get_env_var("KARMABOT_SLACK_USER")
SLACK_TOKEN = _get_env_var("KARMABOT_SLACK_TOKEN")
SLACK_INVITE_TOKEN = _get_env_var("KARMABOT_SLACK_INVITE_USER_TOKEN")
DATABASE_URL = _get_env_var("KARMABOT_DATABASE_URL")

# Slack
GENERAL_CHANNEL = os.environ.get("KARMABOT_GENERAL_CHANNEL")
ADMINS = os.environ.get("KARMABOT_ADMINS").split(",") # type: ignore
GENERAL_CHANNEL = _get_env_var("KARMABOT_GENERAL_CHANNEL")
ADMINS = _get_env_var("KARMABOT_ADMINS")
ADMINS = ADMINS.split(",") # type: ignore
SLACK_ID_FORMAT = re.compile(r"^<@[^>]+>$")
SLACK_CLIENT = SlackClient(SLACK_TOKEN)

Expand Down

0 comments on commit e793c8b

Please sign in to comment.