From 9257726737ddbae76d1e71d8c46ee8b41c3c4219 Mon Sep 17 00:00:00 2001 From: ITQ Date: Wed, 19 Feb 2025 14:38:22 +0300 Subject: [PATCH] feat(telegram_bot): added boilerplate code --- solution/services/telegram_bot/.env.template | 6 + solution/services/telegram_bot/.gitignore | 170 ++++++++++++++++++ solution/services/telegram_bot/config.py | 14 ++ solution/services/telegram_bot/main.py | 67 +++++++ solution/services/telegram_bot/pyproject.toml | 115 ++++++++++++ 5 files changed, 372 insertions(+) create mode 100644 solution/services/telegram_bot/.env.template create mode 100644 solution/services/telegram_bot/.gitignore create mode 100644 solution/services/telegram_bot/config.py create mode 100644 solution/services/telegram_bot/main.py create mode 100644 solution/services/telegram_bot/pyproject.toml diff --git a/solution/services/telegram_bot/.env.template b/solution/services/telegram_bot/.env.template new file mode 100644 index 0000000..56922d2 --- /dev/null +++ b/solution/services/telegram_bot/.env.template @@ -0,0 +1,6 @@ +# Change all vars before going to production and remove all comments (!) +# Below all environment variables and default values + +AIOGRAM_BOT_TOKEN= +AIOGRAM_BACKEND_ADDRESS=http://localhost:8080 +REDIS_URI=redis://localhost:6379 diff --git a/solution/services/telegram_bot/.gitignore b/solution/services/telegram_bot/.gitignore new file mode 100644 index 0000000..b96e392 --- /dev/null +++ b/solution/services/telegram_bot/.gitignore @@ -0,0 +1,170 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +.idea/ + +# PyPI configuration file +.pypirc + +# Ruff files +.ruff_cache diff --git a/solution/services/telegram_bot/config.py b/solution/services/telegram_bot/config.py new file mode 100644 index 0000000..11a434e --- /dev/null +++ b/solution/services/telegram_bot/config.py @@ -0,0 +1,14 @@ +import os +from pathlib import Path + +from dotenv import load_dotenv + +BASE_DIR = Path(__file__).resolve().parent + +load_dotenv(BASE_DIR / ".env") + +BOT_TOKEN = os.getenv("AIOGRAM_BOT_TOKEN", None) + +API_ENDPOINT = os.getenv("AIOGRAM_BACKEND_URL", "http://localhost:8080") + +REDIS_URI = os.getenv("REDIS_URI", "redis://localhost:6379") diff --git a/solution/services/telegram_bot/main.py b/solution/services/telegram_bot/main.py new file mode 100644 index 0000000..bf65f42 --- /dev/null +++ b/solution/services/telegram_bot/main.py @@ -0,0 +1,67 @@ +import asyncio +import logging + +from aiogram import Bot, Dispatcher +from aiogram.client.default import DefaultBotProperties +from aiogram.fsm.storage.redis import DefaultKeyBuilder, RedisStorage +from aiogram_dialog import setup_dialogs + +import config +from commands.campaigns import campaigns_router +from commands.logout import logout_router +from commands.start import start_router +from commands.stats import stats_router +from dialogs.campaigns import campaigns_dialog +from dialogs.start import start_dialog +from middlewares.auth import AuthMiddleware +from middlewares.throttling import ThrottlingMiddleware + +logger = logging.getLogger(__name__) + + +async def main() -> None: + logging.basicConfig( + level=logging.INFO, + format=( + "%(levelname)-8s %(filename)s:%(lineno)d" + " [%(asctime)s] - %(name)s - %(message)s" + ), + ) + logger.info("Starting bot...") + + bot: Bot = Bot( + config.BOT_TOKEN, default=DefaultBotProperties(parse_mode="HTML") + ) + dp: Dispatcher = Dispatcher( + storage=RedisStorage.from_url( + config.REDIS_URI, + key_builder=DefaultKeyBuilder(with_destiny=True), + ), + ) + + dp.message.middleware(ThrottlingMiddleware(0.5)) + dp.message.outer_middleware(AuthMiddleware()) + + dp.include_routers( + start_router, + campaigns_router, + stats_router, + logout_router, + ) + dp.include_routers(start_dialog, campaigns_dialog) + + setup_dialogs(dp) + + await bot.delete_webhook(drop_pending_updates=True) + try: + await dp.start_polling(bot) + finally: + await dp.storage.close() + await bot.session.close() + + +if __name__ == "__main__": + try: + asyncio.run(main()) + except (KeyboardInterrupt, SystemExit): + logger.info("Stopping bot...") diff --git a/solution/services/telegram_bot/pyproject.toml b/solution/services/telegram_bot/pyproject.toml new file mode 100644 index 0000000..bad8265 --- /dev/null +++ b/solution/services/telegram_bot/pyproject.toml @@ -0,0 +1,115 @@ +[project] +name = "adnova-telegram_bot" +version = "0.1.0" +readme = "README.md" +requires-python = ">=3.10,<3.12" +dependencies = [ + "aiogram-dialog>=2.3.1", + "aiogram>=3.17.0", + "cachetools>=5.5.1", + "httpx>=0.28.1", + "openapi-python-client>=0.23.1", + "python-dotenv>=1.0.1", + "redis>=5.2.1", +] + +[dependency-groups] +dev = [ + "ruff>=0.9.6", +] + +[tool.ruff] +builtins = [] +cache-dir = ".ruff_cache" +exclude = [ + ".bzr", + ".direnv", + ".eggs", + ".git", + ".git-rewrite", + ".hg", + ".mypy_cache", + ".nox", + ".pants.d", + ".pytype", + ".ruff_cache", + ".svn", + ".tox", + ".venv", + "__pypackages__", + "_build", + "buck-out", + "dist", + "migrations", + "node_modules", + "venv", +] +extend-exclude = [] +extend-include = [] +fix = false +fix-only = false +force-exclude = true +include = ["*.py", "*.pyi", "*.ipynb", "**/pyproject.toml"] +indent-width = 4 +line-length = 79 +namespace-packages = [] +output-format = "full" +preview = false +required-version = ">=0.8.4" +respect-gitignore = true +show-fixes = true +src = [".", "src"] +target-version = "py310" +unsafe-fixes = false + +[tool.ruff.analyze] +detect-string-imports = true +direction = "Dependencies" +exclude = [] +include-dependencies = {} +preview = false + +[tool.ruff.format] +docstring-code-format = true +docstring-code-line-length = 79 +exclude = [] +indent-style = "space" +line-ending = "lf" +preview = false +quote-style = "double" +skip-magic-trailing-comma = false + +[tool.ruff.lint] +allowed-confusables = ["ℹ"] +dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" +exclude = ["tests.py"] +explicit-preview-rules = false +extend-fixable = [] +extend-per-file-ignores = {} +extend-safe-fixes = [] +extend-select = [] +extend-unsafe-fixes = [] +external = [] +fixable = ["ALL"] +ignore = [ + "ARG", + "D", + "ANN401", + "COM812", + "DJ001", + "FBT001", + "FBT002", + "N813", + "RUF001", + "TC002", +] +logger-objects = [] +per-file-ignores = {} +preview = false +select = ["ALL"] +task-tags = ["TODO", "FIXME", "HACK", "WORKOUT"] +typing-modules = [] +unfixable = [] + +[tool.ruff.lint.pylint] +max-args = 6