Created
November 27, 2023 23:33
-
-
Save Oqarshi/fae8f7d6caa20175ad310273716bc464 to your computer and use it in GitHub Desktop.
gets user data from a chess.com game link
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import re | |
from datetime import datetime | |
def extract_game_id(link): | |
# Use regular expression to extract the game ID from the link | |
match = re.search(r'/game/live/(\d+)', link) | |
if match: | |
return match.group(1) | |
else: | |
# Try another pattern for the alternative link structure | |
match = re.search(r'/analysis/game/live/(\d+)', link) | |
if match: | |
return match.group(1) | |
else: | |
return None | |
def get_game_response(game_id): | |
url = f"https://www.chess.com/callback/live/game/{game_id}" | |
response = requests.get(url) | |
return response | |
def parse_game_response(response_text): | |
data = response_text.json() | |
game_info = data.get("game", {}) | |
players_info = data.get("players", {}) | |
if game_info and players_info: | |
players = players_info.get("top", {}) | |
white_player = players.get("username") | |
players = players_info.get("bottom", {}) | |
black_player = players.get("username") | |
result = game_info.get("resultMessage", "Unknown result") | |
date_str = game_info.get("pgnHeaders", {}).get("Date", "") | |
date = datetime.strptime(date_str, "%Y.%m.%d") | |
return white_player, black_player, result, date | |
else: | |
return None | |
# Get user input for the chess.com game link | |
chess_link = input("Enter the Chess.com game link: ") | |
# Extract the game ID from the link | |
game_id = extract_game_id(chess_link) | |
if game_id: | |
# Call the function with the extracted game ID | |
response = get_game_response(game_id) | |
# Check if the request was successful (status code 200) | |
if response.status_code == 200: | |
# Parse the game response | |
game_data = parse_game_response(response) | |
if game_data: | |
white_player, black_player, result, date = game_data | |
print(f"White Player: {white_player}") | |
print(f"Black Player: {black_player}") | |
print(f"Result: {result}") | |
print(f"Date: {date.strftime('%Y-%m-%d')}") | |
else: | |
print("Failed to parse game data.") | |
else: | |
print(f"Failed to retrieve data. Status code: {response.status_code}") | |
else: | |
print("Invalid Chess.com game link. Please provide a valid link.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment