Skip to content

Commit

Permalink
Refactor config to use validators
Browse files Browse the repository at this point in the history
  • Loading branch information
TheReverend403 committed Feb 22, 2024
1 parent 8fd39cf commit fcd2daf
Show file tree
Hide file tree
Showing 4 changed files with 138 additions and 34 deletions.
6 changes: 4 additions & 2 deletions gentoogram/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@
#
# You should have received a copy of the GNU General Public License
# along with gentoogram-bot. If not, see <https://www.gnu.org/licenses/>.
import os

import logging
from pathlib import Path

logging.basicConfig(level=logging.INFO)

BASE_DIR = Path(__file__).parent.parent
CONFIG_DIR = os.getenv("ROOT_PATH_FOR_DYNACONF", BASE_DIR / "config")
21 changes: 6 additions & 15 deletions gentoogram/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

import httpx
import sentry_sdk
from dynaconf import Dynaconf
from telegram import Update
from telegram.error import NetworkError, TelegramError
from telegram.ext import (
Expand All @@ -32,20 +31,9 @@
filters,
)

from gentoogram import CONFIG_DIR
from gentoogram.config import config

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("gentoogram")

config = Dynaconf(
envvar_prefix="CFG",
root_path=CONFIG_DIR,
settings_files=[
"*.toml",
"*.yml",
"*.yaml",
],
)
logger = logging.getLogger(__name__)

try:
version = subprocess.check_output(
Expand Down Expand Up @@ -127,6 +115,9 @@ async def reload_config(update: Update, context: ContextTypes.DEFAULT_TYPE):


async def is_spammer(user_id: int) -> bool:
if not config.get("cas.enabled", True):
return True

try:
async with httpx.AsyncClient() as client:
response = await client.get(
Expand All @@ -139,7 +130,7 @@ async def is_spammer(user_id: int) -> bool:

if check_result.get("ok"):
offenses = check_result.get("result").get("offenses")
if offenses >= config.get("antispam.threshold", 1):
if offenses >= config.get("cas.threshold", 1):
logger.info(
f"User {user_id} failed CAS spam check with {offenses} offense(s)."
)
Expand Down
110 changes: 110 additions & 0 deletions gentoogram/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# This file is part of gentoogram-bot.
#
# gentoogram-bot is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# gentoogram-bot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with gentoogram-bot. If not, see <https://www.gnu.org/licenses/>.

import logging
import os

from dynaconf import Dynaconf, ValidationError, Validator

from gentoogram import BASE_DIR

logger = logging.getLogger(__name__)

CONFIG_DIR = os.getenv("ROOT_PATH_FOR_DYNACONF", BASE_DIR / "config")

config = Dynaconf(
envvar_prefix="CFG",
root_path=CONFIG_DIR,
settings_files=[
"*.toml",
"*.yml",
"*.yaml",
],
)

config.validators.register(
Validator(
"telegram.token",
must_exist=True,
len_min=1,
is_type_of=str,
),
Validator("telegram.chat_id", "telegram.admin_id", must_exist=True, is_type_of=int),
Validator(
"webhook.enabled",
is_type_of=bool,
default=False,
apply_default_on_none=True,
)
& Validator(
"webhook.port", is_type_of=int, default=3020, apply_default_on_none=True
)
& Validator(
"webhook.listen",
len_min=1,
is_type_of=str,
default="127.0.0.1",
apply_default_on_none=True,
)
& Validator(
"webhook.listen",
"webhook.port",
must_exist=True,
when=Validator("webhook.enabled", eq=True),
),
Validator("webhook.url_base", startswith="https://")
& Validator("webhook.url_path", default="/", apply_default_on_none=True)
& Validator(
"webhook.url_base",
"webhook.url_path",
must_exist=True,
len_min=1,
is_type_of=str,
when=Validator("webhook.enabled", eq=True),
),
Validator(
"filters.usernames",
"filters.messages",
default=[],
apply_default_on_none=True,
is_type_of=list,
),
Validator(
"sentry.dsn",
is_type_of=str,
condition=lambda v: v == "" or v.startswith("https://"),
),
Validator(
"cas.enabled",
is_type_of=bool,
default=True,
apply_default_on_none=True,
)
& Validator(
"cas.threshold",
is_type_of=int,
gt=0,
default=1,
apply_default_on_none=True,
must_exist=True,
when=Validator("cas.enabled", eq=True),
),
)

try:
config.validators.validate_all()
except ValidationError as exc:
logger.error(exc.message)
raise SystemExit(1) from exc
35 changes: 18 additions & 17 deletions gentoogram/resources/config/settings.yml
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
telegram:
token: ''
chat_id: ''
admin_id: ''
token:
chat_id:
admin_id:

webhook:
# https://github.com/python-telegram-bot/python-telegram-bot/wiki/Webhooks
enabled: false
listen: 0.0.0.0
port: 3020
url_base: https://example.com
url_path: /
## https://github.com/python-telegram-bot/python-telegram-bot/wiki/Webhooks
# webhook:
# enabled: false
# listen: "0.0.0.0"
# port: 3020
# url_base: "https://example.com"
# url_path: "/"

filters:
usernames: []
messages: []
# filters:
# usernames: []
# messages: []

sentry:
dsn: ''
# sentry:
# dsn: ""

antispam:
threshold: 1
# cas:
# enabled: true
# threshold: 1

0 comments on commit fcd2daf

Please sign in to comment.