From db3e02356df15279e692ec2dbd7f3f1852fe7896 Mon Sep 17 00:00:00 2001 From: Ilya Bezrukov Date: Tue, 30 Jul 2024 03:56:00 +0300 Subject: [PATCH] Try to add webhook using flask --- Dockerfile | 4 +++- requirements.txt | 3 ++- webapp/__init__.py | 27 +++++++++++++++++++++++++++ webapp/bot.py | 16 ++++++++++++++++ 4 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 webapp/__init__.py create mode 100644 webapp/bot.py diff --git a/Dockerfile b/Dockerfile index 37c1154..14ed814 100644 --- a/Dockerfile +++ b/Dockerfile @@ -21,11 +21,11 @@ RUN --mount=type=cache,target=/root/.cache/pip \ # copy i18n files COPY --chown=bot i18n.yaml i18n/i18n.yaml -VOLUME i18n/ # copy default configs WORKDIR /app COPY --chown=bot mybot mybot +COPY --chown=bot webapp webapp # preapre environment ENV SS_TYPE=memory @@ -35,3 +35,5 @@ ENV I18N_PATH=/i18n/i18n.yaml USER bot CMD ["python3", "-m", "mybot"] + +VOLUME i18n/ diff --git a/requirements.txt b/requirements.txt index 6bda7df..674960e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ pytelegrambotapi -environs pyyaml sqlalchemy alembic psycopg +flask +gunicorn diff --git a/webapp/__init__.py b/webapp/__init__.py new file mode 100644 index 0000000..0b94f35 --- /dev/null +++ b/webapp/__init__.py @@ -0,0 +1,27 @@ +from flask import Flask, g +from telebot import TeleBot + +from mybot import create_bot +from mybot.config import load_config +from mybot.database import get_engine +from mybot.i18n import I18N + +from .bot import bp as bot_bp + + +def inject_bot(bot: TeleBot): + def inner(): + g.bot = bot + return inner + + +def create_app(): + config = load_config() + i18n = I18N(config.i18n) + engine = get_engine(config.database) + bot = create_bot(config, i18n, engine) + + app = Flask(__name__) + app.register_blueprint(bot_bp, url_prefix=f"/{config.bot.token}") + app.before_request(inject_bot(bot)) + return app diff --git a/webapp/bot.py b/webapp/bot.py new file mode 100644 index 0000000..388f500 --- /dev/null +++ b/webapp/bot.py @@ -0,0 +1,16 @@ +from flask import Blueprint, request, abort, g, Response +from telebot.types import Update + + +bp = Blueprint("bot", __name__) + + +@bp.route("/", methods=["POST"]) +def handle_updates(): + if request.headers.get("content-type") == "application/json": + json_string = request.get_data().decode("utf-8") + update = Update.de_json(json_string) + g.bot.process_new_updates([update]) + return Response("", 200) + else: + abort(403)