File size: 1,309 Bytes
641009d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import json
import requests
import os

HEADERS = {'User-Agent': 'My Python Application. Contact me at [email protected]'}

def fetch_and_save_chess_data(username, filename):
    """Fetch chess games data from Chess.com API for a specified username and save to a JSON file."""
    if os.path.exists(filename):
        print(f"Loading data from {filename}")
        with open(filename, 'r') as file:
            return json.load(file)

    archives_url = f"https://api.chess.com/pub/player/{username}/games/archives"
    response = requests.get(archives_url, headers=HEADERS)

    if response.status_code != 200:
        print(f"Error fetching archives for user {username}: {response.status_code}")
        return []

    archives = response.json().get('archives', [])
    games = []

    # Fetch game data for each archive URL
    for archive_url in archives:
        response = requests.get(archive_url, headers=HEADERS)
        if response.status_code == 200:
            games.extend(response.json().get('games', []))
        else:
            print(f"Failed to fetch games for {archive_url}")

    # Save the data to a JSON file
    with open(filename, 'w') as file:
        json.dump(games, file, indent=4)
        print(f"Data saved to {filename}")

    return games