Created
October 4, 2023 20:35
-
-
Save mkirlin/3eaf157f2ebc97196f1cdbb168a489a5 to your computer and use it in GitHub Desktop.
ChatGPT script for pulling transactions from Yahoo fantasy sports API
This file contains 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 | |
from urllib.parse import urlencode | |
import gspread | |
from oauth2client.service_account import ServiceAccountCredentials | |
# Define your API credentials | |
client_id = "YOUR_CLIENT_ID" | |
client_secret = "YOUR_CLIENT_SECRET" | |
redirect_uri = "YOUR_REDIRECT_URI" # You set this when registering your app | |
access_token = None | |
# Define the base API URL | |
base_url = "https://fantasysports.yahooapis.com/fantasy/v2" | |
# Function to authenticate your application and obtain an access token | |
def authenticate_app(): | |
global access_token | |
# Generate the authorization URL | |
auth_url = "https://api.login.yahoo.com/oauth2/request_auth" | |
auth_params = { | |
"client_id": client_id, | |
"redirect_uri": redirect_uri, | |
"response_type": "code", | |
"scope": "fspt-w", | |
} | |
auth_url_with_params = f"{auth_url}?{urlencode(auth_params)}" | |
print(f"Visit the following URL in your browser and grant access to your Yahoo Fantasy account:") | |
print(auth_url_with_params) | |
# After the user grants access, you will receive an authorization code at your redirect_uri | |
authorization_code = input("Enter the authorization code from the URL: ") | |
# Exchange the authorization code for an access token | |
token_url = "https://api.login.yahoo.com/oauth2/get_token" | |
token_data = { | |
"client_id": client_id, | |
"client_secret": client_secret, | |
"redirect_uri": redirect_uri, | |
"code": authorization_code, | |
"grant_type": "authorization_code", | |
} | |
# Make a POST request to get the access token | |
response = requests.post(token_url, data=token_data) | |
if response.status_code == 200: | |
access_token_data = response.json() | |
access_token = access_token_data["access_token"] | |
print(f"Access token obtained successfully: {access_token}") | |
else: | |
print(f"Error getting access token: {response.status_code} - {response.text}") | |
# Function to retrieve transactions and handle pagination | |
def get_transactions(url): | |
transactions = [] | |
while url: | |
headers = { | |
"Authorization": f"Bearer {access_token}", | |
} | |
# Make a request to get transactions | |
response = requests.get(url, headers=headers) | |
if response.status_code == 200: | |
transaction_data = response.json() | |
# Process the data for the current page | |
transactions.extend(transaction_data['fantasy_content']['league'][1]['transactions']) | |
# Check if there are more pages of transactions | |
next_page = transaction_data['fantasy_content']['league'][0]['transactions']['next'] | |
url = next_page if next_page else None | |
else: | |
print(f"Error: {response.status_code} - {response.text}") | |
break | |
return transactions | |
# Authenticate your application | |
authenticate_app() | |
# Step 2: Fetch the league ID of the specific basketball league | |
league_id = "YOUR_LEAGUE_ID" # Replace with the league you want to access | |
# Step 3: Retrieve transactions for each year from 2017 to 2022 | |
for year in range(2017, 2023): | |
transaction_url = f"{base_url}/league/{league_id}/transactions;year={year}" | |
# Get transactions for the current year and handle pagination | |
transactions = get_transactions(transaction_url) | |
# Format: JSON format of Google Sheets API credentials | |
# Replace 'your-credentials.json' with the path to your Google Sheets API credentials JSON file | |
# Example format: | |
# { | |
# "type": "service_account", | |
# "project_id": "your-project-id", | |
# "private_key_id": "your-private-key-id", | |
# "private_key": "-----BEGIN PRIVATE KEY-----\nYOUR-PRIVATE-KEY\n-----END PRIVATE KEY-----\n", | |
# "client_email": "your-client-email", | |
# "client_id": "your-client-id", | |
# "auth_uri": "https://accounts.google.com/o/oauth2/auth", | |
# "token_uri": "https://accounts.google.com/o/oauth2/token", | |
# "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", | |
# "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/your-client-email" | |
# } | |
creds_json_path = 'your-credentials.json' | |
# Initialize Google Sheets API credentials | |
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] | |
creds = ServiceAccountCredentials.from_json_keyfile_name(creds_json_path, scope) | |
client = gspread.authorize(creds) | |
# Create or open a Google Sheet | |
sheet = client.open('Fantasy Transactions') | |
# Select the first worksheet (assuming it exists) | |
worksheet = sheet.get_worksheet(0) | |
# Write transactions to the Google Sheet with formatted player names | |
for transaction in transactions: | |
date = transaction['transaction']['timestamp'] | |
team1_owner = transaction['transaction']['teams'][0]['name'] | |
team2_owner = transaction['transaction']['teams'][1]['name'] | |
players_team1 = ', '.join([f"{player['name']} ({player['position']}, {player['team']})" for player in transaction['transaction']['teams'][0]['players']]) | |
players_team2 = ', '.join([f"{player['name']} ({player['position']}, {player['team']})" for player in transaction['transaction']['teams'][1]['players']]) | |
formatted_transaction_team1 = f"{team1_owner} trades {players_team1} to {team2_owner}" | |
formatted_transaction_team2 = f"{team2_owner} trades {players_team2} to {team1_owner}" | |
# Append data to the sheet | |
worksheet.append_table([date, formatted_transaction_team1]) | |
worksheet.append_table(['', formatted_transaction_team2]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment