|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import logging |
| 4 | +import os |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +from typing import Optional |
| 8 | +from telegram import Update |
| 9 | +from telegram.ext import Application |
| 10 | + |
| 11 | +from tg import build_app |
| 12 | + |
| 13 | +logging.basicConfig(level=logging.INFO) |
| 14 | + |
| 15 | +# Global application and event loop for Yandex Cloud Functions |
| 16 | +_application: Optional[Application] = None |
| 17 | +_app_initialized: bool = False |
| 18 | +_loop: Optional[asyncio.AbstractEventLoop] = None |
| 19 | + |
| 20 | + |
| 21 | +def _get_loop() -> asyncio.AbstractEventLoop: |
| 22 | + global _loop |
| 23 | + if _loop is None or _loop.is_closed(): |
| 24 | + _loop = asyncio.new_event_loop() |
| 25 | + asyncio.set_event_loop(_loop) |
| 26 | + return _loop |
| 27 | + |
| 28 | + |
| 29 | +def _get_application(): |
| 30 | + """Create and initialize the Telegram Application once per cold start.""" |
| 31 | + global _application, _app_initialized |
| 32 | + |
| 33 | + if _application is None: |
| 34 | + _application = build_app( |
| 35 | + tg_token=os.getenv("TELEGRAM_BOT_TOKEN"), |
| 36 | + folder_id=os.getenv("YC_FOLDER_ID"), |
| 37 | + script=Path("../terraform/metadata.yml").absolute(), |
| 38 | + chat_whitelist=get_whitelist() |
| 39 | + ) |
| 40 | + |
| 41 | + if not _app_initialized: |
| 42 | + loop = _get_loop() |
| 43 | + loop.run_until_complete(_application.initialize()) |
| 44 | + _app_initialized = True |
| 45 | + |
| 46 | + return _application |
| 47 | + |
| 48 | + |
| 49 | +def get_whitelist(): |
| 50 | + whitelist = os.getenv("TELEGRAM_CHAT_WHITELIST") |
| 51 | + return list(map(int, whitelist.split(","))) |
| 52 | + |
| 53 | + |
| 54 | +def telegram_webhook(event: dict, context: dict): |
| 55 | + try: |
| 56 | + if event["httpMethod"] != "POST": |
| 57 | + logging.error("Received request with method %s", event["httpMethod"]) |
| 58 | + return "Method Not Allowed", 405 |
| 59 | + |
| 60 | + try: |
| 61 | + data = json.loads(event["body"]) |
| 62 | + except json.JSONDecodeError: |
| 63 | + logging.error("Received request with no JSON payload") |
| 64 | + return "Bad Request: no JSON payload", 400 |
| 65 | + |
| 66 | + application = _get_application() |
| 67 | + update = Update.de_json(data, application.bot) |
| 68 | + |
| 69 | + loop = _get_loop() |
| 70 | + loop.run_until_complete(application.process_update(update)) |
| 71 | + |
| 72 | + return "", 204 |
| 73 | + |
| 74 | + except Exception as e: |
| 75 | + logging.exception("Error handling webhook: %s", e) |
| 76 | + return "", 204 |
| 77 | + |
| 78 | + |
| 79 | +if __name__ == '__main__': |
| 80 | + from dotenv import load_dotenv |
| 81 | + load_dotenv() |
| 82 | + |
| 83 | + logging.basicConfig(level=logging.INFO) |
| 84 | + |
| 85 | + app = build_app( |
| 86 | + tg_token=os.getenv("TELEGRAM_BOT_TOKEN"), |
| 87 | + yc_token=os.getenv("YC_OAUTH_TOKEN"), |
| 88 | + folder_id=os.getenv("YC_FOLDER_ID"), |
| 89 | + script=Path("../terraform/metadata.yml"), |
| 90 | + chat_whitelist=get_whitelist() |
| 91 | + ) |
| 92 | + |
| 93 | + app.run_polling() |
0 commit comments