Created
December 25, 2023 14:41
-
-
Save danielcwq/924426528ee7134dc823567d4f20008f to your computer and use it in GitHub Desktop.
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
from oauth2client.service_account import ServiceAccountCredentials | |
import gspread | |
import pytz | |
from datetime import datetime | |
import requests | |
import json | |
import time | |
import os | |
from datetime import datetime | |
# Get the current time in UTC and convert to local time | |
# Replace 'Asia/Singapore' with the appropriate timezone from the pytz library if you are not in Singapore | |
local_timezone = pytz.timezone('Asia/Singapore') | |
# Get the current time in UTC | |
current_utc_time = datetime.now(pytz.utc) | |
# Convert the current time to local time | |
local_time = current_utc_time.astimezone(local_timezone) | |
current_timestamp = local_time.strftime("%Y-%m-%d %H:%M:%S") | |
# Function to refresh access token | |
def refresh_access_token(client_id, client_secret, refresh_token): | |
auth_url = "https://www.strava.com/oauth/token" | |
payload = { | |
'client_id': client_id, | |
'client_secret': client_secret, | |
'grant_type': 'refresh_token', | |
'refresh_token': refresh_token | |
} | |
response = requests.post(auth_url, data=payload) | |
if response.status_code == 200: | |
new_tokens = response.json() | |
return new_tokens['access_token'], new_tokens['refresh_token'], new_tokens['expires_at'] | |
else: | |
raise Exception("Failed to refresh token: {}".format(response.text)) | |
# Add your client ID, client secret, and refresh token here | |
client_id = os.environ.get('CLIENT_ID') | |
client_secret = os.environ.get('CLIENT_SECRET') | |
refresh_token = os.environ.get('REFRESH_TOKEN') | |
expires_at = 0 # Initialize with 0 or get this value from your saved configuration | |
# Google Sheets setup | |
scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"] | |
creds = ServiceAccountCredentials.from_json_keyfile_name('YOUR_JSON_FILE', scope) | |
client = gspread.authorize(creds) | |
sheet = client.open('YOUR_SHEET').sheet1 | |
existing_activities = sheet.get_all_records() # Gets all existing data from the sheet | |
# Check if the access token needs to be refreshed | |
if time.time() > expires_at: | |
access_token, refresh_token, expires_at = refresh_access_token(client_id, client_secret, refresh_token) | |
# Here you should save the new refresh token and expiration time back to a persistent store | |
# Now you have a valid access token and can proceed with your Strava API request | |
headers = {'Authorization': 'Bearer ' + access_token} | |
url = f'https://www.strava.com/api/v3/clubs/CLUB_ID/activities' | |
response = requests.get(url, headers=headers) | |
#Get new data from Strava | |
if response.status_code == 200: | |
new_activities = json.loads(response.text) | |
new_data = [] | |
for activity in new_activities: | |
athlete = activity['athlete'] | |
row = [ | |
athlete.get('firstname', 'N/A'), | |
athlete.get('lastname', 'N/A'), | |
activity.get('name', 'N/A'), | |
activity.get('distance', 0), | |
activity.get('moving_time', 0), | |
activity.get('elapsed_time', 0), | |
activity.get('total_elevation_gain', 0), | |
activity.get('type', 'N/A'), | |
activity.get('sport_type', 'N/A'), | |
activity.get('workout_type', 'N/A'), | |
current_timestamp | |
] | |
new_data.append(row) | |
# Compare and identify new data | |
# (This assumes that each activity can be uniquely identified by a combination of fields, like name and distance) | |
existing_set = {(row['Activity Name'], row['Distance (m)']) for row in existing_activities} | |
new_entries = [row for row in new_data if (row[2], row[3]) not in existing_set] | |
# Update Google Sheet with new data only | |
if new_entries: | |
# Fetch all existing data | |
all_data = sheet.get_all_values() | |
header = all_data.pop(0) # Remove the header | |
# Combine new entries with existing data | |
combined_data = new_entries + all_data | |
# Clear the sheet and write combined data | |
sheet.clear() | |
sheet.append_rows([header] + combined_data, value_input_option='USER_ENTERED') | |
print ("New activities added. Check Google Sheets.") | |
else: | |
print("No new activities to add.") | |
else: | |
print('Failed to fetch data:', response.status_code) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment