Skip to content

Instantly share code, notes, and snippets.

@meeuw
Created January 25, 2021 20:03
Show Gist options
  • Save meeuw/b4d9b84ca031e7c92effcc8dc338057a to your computer and use it in GitHub Desktop.
Save meeuw/b4d9b84ca031e7c92effcc8dc338057a to your computer and use it in GitHub Desktop.
get activities from strava.com using API and post to google form
import requests_oauthlib
import click
import json
import datetime
import requests
def token_updater(tok):
with open("token.json", "w") as f:
json.dump(tok, f)
def auth(client_id, client_secret):
oauth = requests_oauthlib.OAuth2Session(
client_id, redirect_uri="https://localhost", scope=["activity:read_all"]
)
authorization_url, state = oauth.authorization_url(
"https://www.strava.com/oauth/authorize",
access_type="offline",
approval_prompt="force",
)
print(
"Please go to %s and authorize access. Copy the http://localhost url and confirm with enter."
% authorization_url
)
authorization_response = input()
oauth.fetch_token(
"https://www.strava.com/api/v3/oauth/token",
authorization_response=authorization_response,
include_client_id=True,
client_secret=client_secret,
)
oauth_token = oauth.refresh_token(
"https://www.strava.com/api/v3/oauth/token",
client_id=client_id,
client_secret=client_secret,
)
token_updater(oauth_token)
def activities(client_id):
with open("token.json", "r") as f:
oauth_token = json.load(f)
oauth = requests_oauthlib.OAuth2Session(
client_id,
token=oauth_token,
auto_refresh_url="https://www.strava.com/api/v3/oauth/token",
token_updater=token_updater,
)
r = oauth.get("https://www.strava.com/api/v3/athlete/activities")
print(json.dumps(r.json(), indent=4))
def post(__Secure_3PSID, form_url, exercise_in_minutes_options, params, activity):
exercise_in_minutes = activity["elapsed_time"] / 60
for exercise_in_minutes_option in exercise_in_minutes_options:
if exercise_in_minutes > exercise_in_minutes_option:
break
d = datetime.datetime.fromisoformat(activity["start_date_local"][:-1])
r = requests.get(
form_url,
cookies={"__Secure-3PSID": __Secure_3PSID},
params={
params["duration"]: exercise_in_minutes_option,
params["year"]: d.year,
params["month"]: d.month,
params["day"]: d.day,
params["type"]: activity["type"],
},
)
print(len(r.text))
@click.command()
@click.argument("action")
def main(action):
with open("config.json") as f:
config = json.load(f)
if action == "auth":
auth(config["client_id"], config["client_secret"])
elif action == "activities":
activities(config["client_id"])
elif action == "post":
with open("activities.json") as f:
activities = json.load(f)
for activity in activities:
post(
config["__Secure-3PSID"],
config["form_url"],
config["exercise_in_minutes_options"],
config["params"],
activity,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment