refactor: add config.py

this change adds self validation in __init__, allows to make config values with different types (not just string) and stores config values in classes for easier accessibility

Signed-off-by: mctaylors <cantsendmails@mctaylors.ru>
This commit is contained in:
Macintxsh 2025-03-26 20:29:44 +03:00
parent 768f9abdcf
commit 5262975275
Signed by: mctaylors
GPG key ID: 4EEF4F949A266EE2
5 changed files with 57 additions and 35 deletions

26
main.py
View file

@ -1,10 +1,10 @@
import configparser
import logging
import os
import requests
from telegram.ext import Application, CommandHandler, InlineQueryHandler
from config import *
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
@ -13,15 +13,8 @@ logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
config = configparser.ConfigParser()
config.read("config.ini")
hostname = config.get('App', 'HostName')
hostname = hostname if hostname != "" else config.get('App', 'Host')
def main() -> None:
validate_config()
application = Application.builder().token(get_token()).build()
import commands
@ -35,23 +28,12 @@ def main() -> None:
application.run_polling(allowed_updates=commands.Update.ALL_TYPES)
def validate_config() -> None:
# noinspection PyBroadException
try:
response = requests.get(f"http://{config.get('App', 'Host')}/status.json")
if response.status_code != 200:
raise
except:
print("Unable validate App.Host in config.ini.")
exit(1)
def get_token():
if os.getenv("BOT_TOKEN") is not None:
return os.getenv("BOT_TOKEN")
if config.get('General', 'Token') != "":
return config.get('General', 'Token')
if general.token != "":
return general.token
print("Set BOT_TOKEN environment variable or use General.Token in config.ini to set bot token.")
exit(1)