diff --git a/get_data.py b/get_data.py index 3bfdb4d..da66eaf 100644 --- a/get_data.py +++ b/get_data.py @@ -33,8 +33,8 @@ if not os.path.exists("logs"): os.makedirs("logs") telegram_bot_token = "7639240596:AAH0YtdQoWZSC-_R_EW4wKAHHNLIA0F_ARY" -telegram_chat_id = 228977654 -# telegram_chat_id = -4803699526 +# telegram_chat_id = 228977654 +telegram_chat_id = -4803699526 log_config = { "version": 1, "handlers": { @@ -134,7 +134,13 @@ def start_offline_threads(season, game_id): stop_live_threads() # 🔹 очищаем latest_data безопасно, чтобы не ломать структуру - keep_keys = {"game", "pregame", "pregame-full-stats", "actual-standings", "calendar"} + keep_keys = { + "game", + "pregame", + "pregame-full-stats", + "actual-standings", + "calendar", + } for key in list(latest_data.keys()): if key not in keep_keys: del latest_data[key] @@ -292,8 +298,6 @@ def stop_offline_threads(): logger.info("[threads] OFFLINE threads stopped") - - # Функция запускаемая в потоках def get_data_from_API( name: str, url: str, sleep_time: float, stop_event: threading.Event @@ -317,9 +321,13 @@ def get_data_from_API( value = {"error": str(ex)} # Проверяем, нет ли явного статуса ошибки в JSON - if isinstance(value, dict) and str(value.get("status", "")).lower() in ("error", "fail", "no-status"): - logger.warning(f"[{name}] API вернул статус '{value.get('status')}'") - + if isinstance(value, dict) and str(value.get("status", "")).lower() in ( + "error", + "fail", + "no-status", + ): + logger.warning(f"[{name}] API вернул статус '{value.get('status')}'") + ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] results_q.put({"source": name, "ts": ts, "data": value}) logger.debug(f"[{ts}] name: {name}, status: {value.get('status', 'no-status')}") @@ -383,7 +391,9 @@ def results_consumer(): game["data"]["result"]["game"]["fullScore"] = payload["result"][ "fullScore" ] - game["data"]["result"]["game"]["score"] = f'{payload["result"]["teams"][0]["total"]["points"]}:{payload["result"]["teams"][1]["total"]["points"]}' + game["data"]["result"]["game"][ + "score" + ] = f'{payload["result"]["teams"][0]["total"]["points"]}:{payload["result"]["teams"][1]["total"]["points"]}' for team in game["data"]["result"]["teams"]: if team["teamNumber"] != 0: box_team = [ @@ -471,7 +481,7 @@ def results_consumer(): except Exception as e: logger.warning( - "results_consumer: live-status postprocess error:", e + f"results_consumer: live-status postprocess error: {e}" ) else: @@ -609,6 +619,7 @@ def extract_game_datetime(game_item: dict) -> datetime | None: except Exception: return None + def build_pretty_status_message(): """ Собирает одно красивое сообщение про текущее состояние онлайна. @@ -627,7 +638,6 @@ def build_pretty_status_message(): result = game_data.get("result") or {} game_info = result.get("game") or {} - team1_name = result["team1"]["name"] team2_name = result["team2"]["name"] @@ -640,9 +650,7 @@ def build_pretty_status_message(): if isinstance(full_score, str) and full_score: quarters = full_score.split(",") - q_text = " | ".join( - f"Q{i+1} {q}" for i, q in enumerate(quarters) if q - ) + q_text = " | ".join(f"Q{i+1} {q}" for i, q in enumerate(quarters) if q) if q_text: lines.append(f"🧱 By quarters: {q_text}") @@ -652,10 +660,7 @@ def build_pretty_status_message(): ls = latest_data.get("live-status", {}) ls_raw = ls.get("data") or {} ls_status = ( - ls_raw.get("status") - or ls_raw.get("gameStatus") - or ls_raw.get("state") - or "—" + ls_raw.get("status") or ls_raw.get("gameStatus") or ls_raw.get("state") or "—" ) lines.append(f"🟢 LIVE status: {ls_status}") @@ -724,7 +729,6 @@ def status_broadcaster(): time.sleep(1) - @asynccontextmanager async def lifespan(app: FastAPI): global STATUS, GAME_ID, SEASON, GAME_START_DT, GAME_TODAY, GAME_SOON @@ -772,7 +776,7 @@ async def lifespan(app: FastAPI): daemon=True, ) thread_result_consumer.start() - + thread_status_broadcaster = threading.Thread( target=status_broadcaster, daemon=True, @@ -832,7 +836,7 @@ async def lifespan(app: FastAPI): args=( "live-status", URLS["live-status"].format(host=HOST, game_id=game_id), - .5, + 0.5, stop_event, ), daemon=True, @@ -842,7 +846,7 @@ async def lifespan(app: FastAPI): args=( "box-score", URLS["box-score"].format(host=HOST, game_id=game_id), - .5, + 0.5, stop_event, ), daemon=True, @@ -978,6 +982,7 @@ async def game(): @app.get("/status") async def status(request: Request): + global STATUS # будем его править, если live-status свежее def color_for_status(status_value: str) -> str: """Подбор цвета статуса в HEX""" status_value = str(status_value).lower()