Skip to content

Instantly share code, notes, and snippets.

@gregzaal
Created May 12, 2020 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregzaal/d7cb6d666a3eda2163843a29429920ec to your computer and use it in GitHub Desktop.
Save gregzaal/d7cb6d666a3eda2163843a29429920ec to your computer and use it in GitHub Desktop.
Patreon refresh tokens
import json
import patreon
def read_json(fp):
with open(fp, 'r') as f:
data = json.load(f)
return data
def write_json(fp, data, indent=1):
with open(fp, 'w') as f:
json.dump(data, f, indent=indent, sort_keys=True)
def get_patreon_data():
patreon_config_path = "patreon_config.json"
patreon_config = read_json(patreon_config_path)
api_client = patreon.API(patreon_config['access_token'])
campaign_response = api_client.fetch_campaign()
if isinstance(campaign_response, dict) and campaign_response['errors']:
# Access token is out of date, get a new one
oauth_client = patreon.OAuth(patreon_config['client_id'], patreon_config['client_secret'])
tokens = oauth_client.refresh_token(patreon_config['refresh_token'], None)
if 'access_token' in tokens and tokens['access_token']:
patreon_config['access_token'] = tokens['access_token']
patreon_config['refresh_token'] = tokens['refresh_token']
write_json(patreon_config_path, patreon_config)
print("Patreon: Got a new access_token!")
else:
print("Patreon: Can't fetch new tokens. Please debug, or write in to Patreon support.\n")
print(campaign_response['errors'])
print(tokens)
return
api_client = patreon.API(patreon_config['access_token'])
campaign_response = api_client.fetch_campaign()
campaign_id = campaign_response.data()[0].id()
# Fetch all pledges
all_pledges = []
user_data = {}
rewards = {}
cursor = None
while True:
pledges_response = api_client.fetch_page_of_pledges(campaign_id, 25, cursor=cursor)
for d in pledges_response.json_data['included']:
if d['type'] == "user":
user_data[d['id']] = d
elif d['type'] == "reward":
try:
if d['relationships']['campaign']['data']['id'] == campaign_id:
rewards[d['id']] = d
except KeyError:
pass
all_pledges += pledges_response.data()
cursor = api_client.extract_cursor(pledges_response)
if not cursor:
break
all_pledges = [x.json_data for x in all_pledges]
data = {
"pledges": all_pledges,
"user_data": user_data,
"rewards": rewards,
}
write_json("patreon_data.json", data) # Optionally store pledge data for quicker cached access
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment