/
zimaaadev
/
Parser
Обзор
Документация
Войти
/
zimaaadev
/
Parser
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
bot/webhook_async.py
72 строки
2 KB
zimaaadev
bot
16 дек 2025, 20:42
16 дек 2025, 20:42
fec0f2b
Код
Авторство
О чём код?
# bot/webhook_async.py from aiohttp import web import asyncio from telegram import Bot from telegram.constants import ParseMode from database import get_db_connection from config import TELEGRAM_BOT_TOKEN routes = web.RouteTableDef() notification_queue = asyncio.Queue() bot = None @routes.post("/notify") async def notify_handler(request): item = await request.json() if not item: return web.json_response({"error": "No data"}, status=400) await notification_queue.put(item) return web.json_response({"status": "ok"}) async def notification_worker(): global bot bot = Bot(token=TELEGRAM_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}") async def start_webhook(): app = web.Application() app.add_routes(routes) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, '0.0.0.0', 5002) await site.start() print("🔔 Вебхук запущен: http://0.0.0.0:5002/notify") # Запуск async def run_webhook(): worker_task = asyncio.create_task(notification_worker()) server_task = asyncio.create_task(start_webhook()) await asyncio.gather(worker_task, server_task)