144 lines
5.1 KiB
Python
144 lines
5.1 KiB
Python
#!/usr/bin/env python3
|
||
"""Скрипт для проверки недавних игр пользователя через Lichess API"""
|
||
|
||
import requests
|
||
import json
|
||
from datetime import datetime, timedelta
|
||
import sys
|
||
|
||
def get_recent_games(username: str, minutes: int = 30):
|
||
"""Получить игры за последние N минут"""
|
||
|
||
# Вычисляем временные метки
|
||
now = datetime.now()
|
||
since_time = now - timedelta(minutes=minutes)
|
||
|
||
since_ms = int(since_time.timestamp() * 1000)
|
||
until_ms = int(now.timestamp() * 1000)
|
||
|
||
print(f"🔍 Проверяем игры для {username}")
|
||
print(f"⏰ Период: с {since_time.strftime('%Y-%m-%d %H:%M:%S')} до {now.strftime('%Y-%m-%d %H:%M:%S')}")
|
||
print(f"📅 Timestamps: since={since_ms}, until={until_ms}")
|
||
print()
|
||
|
||
# Делаем запрос к Lichess API
|
||
url = f"https://lichess.org/api/games/user/{username}"
|
||
params = {
|
||
'since': since_ms,
|
||
'until': until_ms,
|
||
'max': 1000,
|
||
'rated': 'true' # Только рейтинговые
|
||
}
|
||
|
||
headers = {
|
||
'Accept': 'application/x-ndjson'
|
||
}
|
||
|
||
try:
|
||
response = requests.get(url, params=params, headers=headers, timeout=30)
|
||
|
||
if response.status_code == 404:
|
||
print(f"❌ Пользователь {username} не найден (404)")
|
||
return []
|
||
elif response.status_code != 200:
|
||
print(f"❌ Ошибка API: {response.status_code} - {response.text[:200]}")
|
||
return []
|
||
|
||
# Парсим NDJSON
|
||
games = []
|
||
content = response.text.strip()
|
||
|
||
if content:
|
||
for line in content.split('\n'):
|
||
if line.strip():
|
||
try:
|
||
game = json.loads(line)
|
||
games.append(game)
|
||
except json.JSONDecodeError as e:
|
||
print(f"⚠️ Ошибка парсинга JSON: {e}")
|
||
continue
|
||
|
||
return games
|
||
|
||
except Exception as e:
|
||
print(f"❌ Ошибка при запросе: {e}")
|
||
return []
|
||
|
||
def format_game_time(created_at_ms: int) -> str:
|
||
"""Форматирует время создания игры"""
|
||
dt = datetime.fromtimestamp(created_at_ms / 1000)
|
||
return dt.strftime('%Y-%m-%d %H:%M:%S')
|
||
|
||
def main():
|
||
username = sys.argv[1] if len(sys.argv) > 1 else "vrubelroman"
|
||
minutes = int(sys.argv[2]) if len(sys.argv) > 2 else 40
|
||
|
||
games = get_recent_games(username, minutes)
|
||
|
||
if not games:
|
||
print("❌ Игры не найдены")
|
||
return
|
||
|
||
print(f"✅ Найдено игр: {len(games)}")
|
||
print()
|
||
print("=" * 80)
|
||
|
||
now = datetime.now()
|
||
|
||
for i, game in enumerate(games, 1):
|
||
game_id = game.get('id', 'N/A')
|
||
created_at_ms = game.get('createdAt', 0)
|
||
speed = game.get('speed', 'unknown')
|
||
rated = game.get('rated', False)
|
||
|
||
# Результат
|
||
white = game.get('players', {}).get('white', {})
|
||
black = game.get('players', {}).get('black', {})
|
||
white_user = white.get('user', {}).get('name', 'N/A')
|
||
black_user = black.get('user', {}).get('name', 'N/A')
|
||
winner = game.get('winner')
|
||
|
||
# Определяем результат для пользователя
|
||
if white_user == username:
|
||
result = "Победа" if winner == "white" else ("Поражение" if winner == "black" else "Ничья")
|
||
opponent = black_user
|
||
elif black_user == username:
|
||
result = "Победа" if winner == "black" else ("Поражение" if winner == "white" else "Ничья")
|
||
opponent = white_user
|
||
else:
|
||
result = "N/A"
|
||
opponent = "N/A"
|
||
|
||
game_time = format_game_time(created_at_ms)
|
||
time_ago = now - datetime.fromtimestamp(created_at_ms / 1000)
|
||
minutes_ago = int(time_ago.total_seconds() / 60)
|
||
|
||
print(f"\n🎮 Игра #{i}")
|
||
print(f" ID: {game_id}")
|
||
print(f" Время: {game_time} ({minutes_ago} минут назад)")
|
||
print(f" Скорость: {speed}")
|
||
print(f" Рейтинговая: {'Да' if rated else 'Нет'}")
|
||
print(f" Соперник: {opponent}")
|
||
print(f" Результат: {result}")
|
||
|
||
# Рейтинг
|
||
if white_user == username:
|
||
rating_change = white.get('ratingDiff', 0)
|
||
final_rating = white.get('rating', 0)
|
||
elif black_user == username:
|
||
rating_change = black.get('ratingDiff', 0)
|
||
final_rating = black.get('rating', 0)
|
||
else:
|
||
rating_change = 0
|
||
final_rating = 0
|
||
|
||
if rating_change != 0 or final_rating != 0:
|
||
print(f" Рейтинг: {final_rating} ({rating_change:+d})")
|
||
|
||
print()
|
||
print("=" * 80)
|
||
print(f"\n📊 Всего игр за последние {minutes} минут: {len(games)}")
|
||
|
||
if __name__ == "__main__":
|
||
main()
|
||
|