/
zimaaadev
/
Parser
Обзор
Документация
Войти
/
zimaaadev
/
Parser
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
bot/webhook.py
80 строк
3 KB
zimaaa
Функционал "что рядом"
15 дек 2025, 19:35
15 дек 2025, 19:35
f834d38
Код
Авторство
О чём код?
# bot/webhook.py from flask import Flask, request, jsonify import asyncio from telegram import Bot from telegram.constants import ParseMode import threading import os from database import get_db_connection app = Flask(__name__) notification_queue = asyncio.Queue() bot_token = None loop = None # === Асинхронный воркер === async def notification_worker(): bot = Bot(token=bot_token) async with bot: while True: item = await notification_queue.get() if item is None: break await send_to_subscribers(item, bot) notification_queue.task_done() async def send_to_subscribers(item, bot): conn = get_db_connection() users = conn.execute(""" SELECT chat_id, min_price, max_price, notify_new FROM users WHERE subscribed = 1 AND notify_new = 1 """).fetchall() conn.close() for user in users: if user["min_price"] <= item["price"] <= user["max_price"]: text = ( f"🆕 <b>Новое объявление</b>\n\n" f"🏠 <a href='{item['url']}'>{item['title']}</a>\n" f"📍 {item['location']}\n" f"💵 {item['price']:,.0f} ₽ | {item['price_per_m2']}\n" f"🏢 {'Новостройка' if item['is_new'] else 'Вторичка'}" ) try: await bot.send_message( chat_id=user["chat_id"], text=text, parse_mode=ParseMode.HTML, disable_web_page_preview=False ) except Exception as e: print(f"❌ Не удалось отправить {user['chat_id']}: {e}") @app.route("/notify", methods=["POST"]) def notify_new_listing(): item = request.json if not item: return jsonify({"error": "No data"}), 400 asyncio.run_coroutine_threadsafe(notification_queue.put(item), loop) return jsonify({"status": "ok"}), 200 def run_webhook(host="0.0.0.0", port=5002): global bot_token, loop bot_token = os.getenv("TELEGRAM_BOT_TOKEN") if not bot_token: print("❌ Не задан TELEGRAM_BOT_TOKEN — вебхук не запущен") return loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) bot_task = loop.create_task(notification_worker()) # Запуск Flask в отдельном потоке thread = threading.Thread( target=app.run, kwargs={"host": host, "port": port, "use_reloader": False, "debug": False}, daemon=True ) thread.start() print(f"🔔 Вебхук запущен: http://{host}:{port}/notify")