поправил отображение онлайн статуса

This commit is contained in:
2025-11-01 15:23:07 +03:00
parent ff7351d35a
commit 18e790c6cd

View File

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