"""Transport offers: local JSON feed, durable notification queue, optional Telegram sink.""" import argparse import json import os import sqlite3 import time import urllib.request from contextlib import closing FIELDS = ("id", "origin", "destination", "body") def init(path): with closing(sqlite3.connect(path)) as db, db: db.execute("""CREATE TABLE IF NOT EXISTS jobs( offer_id TEXT PRIMARY KEY, notification TEXT NOT NULL, delivered INTEGER DEFAULT 0)""") def ingest(path, records, rule): if not isinstance(records, list): raise ValueError("Ожидается массив заявок.") count = 0 with closing(sqlite3.connect(path, timeout=30)) as db, db: for item in records: if not isinstance(item, dict) or any( not isinstance(item.get(k), str) or not item[k].strip() for k in FIELDS ) or type(item.get("rate")) is not int or item["rate"] < 0: raise ValueError("У заявки должны быть id, origin, destination, body и целая ставка rate ≥ 0.") if any( str(rule.get(k, "")).strip().casefold() not in ("", item[k].strip().casefold()) for k in ("origin", "destination", "body") ) or item["rate"] < rule.get("minimum", 0): continue text = (f"{item['id']} · {item['origin']} → {item['destination']}\n" f"{item['body']} · {item['rate']:,} ₽".replace(",", " ")) count += db.execute( "INSERT OR IGNORE INTO jobs(offer_id, notification) VALUES(?,?)", (item["id"].strip(), text), ).rowcount return count def drain(path, deliver): count = 0 with closing(sqlite3.connect(path, timeout=30)) as db: while True: # One worker at a time; a killed process releases the lock and leaves the row queued. with db: db.execute("BEGIN IMMEDIATE") row = db.execute("SELECT offer_id, notification FROM jobs WHERE delivered=0 ORDER BY rowid LIMIT 1").fetchone() if row is None: return count deliver(row[1]) db.execute("UPDATE jobs SET delivered=1 WHERE offer_id=?", (row[0],)) count += 1 def telegram_sink(): token = os.environ.get("TELEGRAM_BOT_TOKEN") chat = os.environ.get("TELEGRAM_CHAT_ID") if not token or not chat: raise SystemExit("Для --telegram задайте TELEGRAM_BOT_TOKEN и TELEGRAM_CHAT_ID.") def deliver(text): request = urllib.request.Request( f"https://api.telegram.org/bot{token}/sendMessage", data=json.dumps({"chat_id": chat, "text": text}).encode(), headers={"Content-Type": "application/json"}, ) with urllib.request.urlopen(request, timeout=15) as response: if not json.load(response).get("ok"): raise OSError("Telegram отклонил уведомление.") return deliver def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--db", default="monitor.sqlite") sub = parser.add_subparsers(dest="mode", required=True) for action in ("ingest", "watch"): ingest_parser = sub.add_parser(action) ingest_parser.add_argument("feed", help="Локальный JSON-файл от одного поставщика") ingest_parser.add_argument("--origin", default="") ingest_parser.add_argument("--destination", default="") ingest_parser.add_argument("--body", default="") ingest_parser.add_argument("--minimum", type=int, default=0) if action == "watch": ingest_parser.add_argument("--every", type=int, default=60) ingest_parser.add_argument("--telegram", action="store_true") sub.add_parser("drain").add_argument("--telegram", action="store_true") sub.add_parser("status") args = parser.parse_args() init(args.db) if args.mode == "status": with closing(sqlite3.connect(args.db)) as db: for key, flag in (("В очереди", 0), ("Доставлено", 1)): print(key, db.execute("SELECT COUNT(*) FROM jobs WHERE delivered=?", (flag,)).fetchone()[0]) return deliver = telegram_sink() if getattr(args, "telegram", False) else print if args.mode == "watch" and args.every < 1: parser.error("--every должно быть положительным") while True: try: if args.mode in ("watch", "ingest"): with open(args.feed, encoding="utf-8") as stream: added = ingest(args.db, json.load(stream), vars(args)) print(f"Новых совпадений: {added}", flush=True) if args.mode in ("watch", "drain"): print(f"Уведомлений передано: {drain(args.db, deliver)}", flush=True) except (OSError, ValueError, sqlite3.Error) as err: # Never print an HTTPError URL containing a bot token. if args.mode != "watch": raise SystemExit(f"Операция прервана ({type(err).__name__}); проверьте файл или канал доставки.") print(f"Цикл прерван ({type(err).__name__}); повтор после паузы.", flush=True) if args.mode != "watch": break time.sleep(args.every) if __name__ == "__main__": main()