Last active
September 9, 2017 19:29
-
-
Save fxchen/f86239b52ddc3488a222e8c634bd8115 to your computer and use it in GitHub Desktop.
A legible timezone friendly parser for Foursquare. Allows for fetching and showing with a date format
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: https://gist.github.com/rootulp/8c57bffd539bf238f4c4812dcabc6677 | |
# Before running this script execut the following command: <pip install requests> | |
import requests, json, datetime, operator, argparse, sys, os | |
# CONSTANTS | |
URL_TEMPLATE = 'https://api.foursquare.com/v2/users/self/checkins?limit=250&oauth_token={}&v=20131026&offset={}' | |
DEFAULT_DAYS = 30 | |
JSON_FILE = 'foursquare.json' | |
TEXT_FILE = 'foursquare.txt' | |
OAUTH_TOKEN = "<>" | |
parser = argparse.ArgumentParser(description='A legible timezone friendly parser for Foursquare. Allows for fetching and showing with a date format') | |
parser.add_argument('-f', '--fetch', action='store_true', | |
help='Grab checkins from Foursquare API') | |
parser.add_argument('-s', '--show', type=int, metavar="n", nargs='?', const=DEFAULT_DAYS, | |
help='Shows formatted <n> days (default: ' + str(DEFAULT_DAYS) +' days)') | |
args = parser.parse_args() | |
if not (args.fetch or args.show): | |
parser.error('No action requested {--help, --fetch, --show}') | |
# GLOBALS | |
formatted_dates={} | |
foursquare_data = {} | |
def fetch(): | |
global JSON_FILE | |
# We set this offset for request size | |
offset = 0 | |
# Saves your foursquare to foursquare.json | |
print "GRABBING CHECKINS!" | |
with open(JSON_FILE, 'w') as f: | |
while True: | |
response = requests.get(URL_TEMPLATE.format(OAUTH_TOKEN, offset)) | |
if len(response.json()['response']['checkins']['items']) == 0: | |
break | |
for item in response.json()["response"]["checkins"]["items"]: | |
foursquare_data[item["createdAt"] + item["timeZoneOffset"] * 60] = item | |
offset += 250 | |
f.write(json.dumps(foursquare_data, sort_keys=True, indent=4, separators=(',', ': '))) | |
f.close() | |
def show(numdays): | |
global JSON_FILE | |
DAY_FORMAT = '%Y %b %d %a' | |
TIME_FORMAT = '%I:%M %p' | |
# Grab dates from json | |
with open(JSON_FILE, 'r') as f: | |
foursquare_data = json.load(f) | |
f.close() | |
### Format and print stuff | |
for timestamp, dict in foursquare_data.iteritems(): | |
tz_timestamp = int(timestamp) + int(dict["timeZoneOffset"]) | |
# E.g. "2017 May 27 Sat" | |
day_str = datetime.datetime.fromtimestamp(tz_timestamp).strftime(DAY_FORMAT) | |
# E.g. "12:58 PM" | |
time = datetime.datetime.fromtimestamp(tz_timestamp).strftime(TIME_FORMAT) | |
# Construct the object we're inserting. Some check ins no longer have venue names | |
obj = {} | |
if 'venue' in dict and 'name' in dict['venue']: | |
obj["name"] = dict['venue']['name'] | |
else: | |
obj["name"] = 'N/A' | |
obj["time"] = time | |
obj["timestamp"] = tz_timestamp | |
try: | |
formatted_dates[day_str].append(obj) | |
except KeyError: | |
formatted_dates[day_str] = [] | |
formatted_dates[day_str].append(obj) | |
# Print dates | |
base = datetime.datetime.today() | |
date_list = [base - datetime.timedelta(days=x) for x in range(0, numdays)] | |
# Show in reverse order | |
for timestamp in date_list[::-1]: | |
day_str = timestamp.strftime(DAY_FORMAT) | |
print day_str + ": " | |
if day_str in formatted_dates: | |
for obj in sorted(formatted_dates[day_str], key=lambda k: k['timestamp']): | |
print obj["time"] + " " + obj["name"].encode('utf-8').strip() | |
print "" | |
if args.fetch: | |
fetch() | |
if args.show: | |
print "We'll be printing " + str(args.show) + " days\n" | |
while True: | |
print "Press space to stdout" | |
print "Press 'f' to write to " + TEXT_FILE | |
choice = raw_input() | |
if choice == 'f' : | |
# Redirect std out to the text file | |
## Deprecated: Show then write! | |
# show(args.show) | |
print "Opening..." | |
sys.stdout = open(TEXT_FILE, 'w') | |
show(args.show) | |
os.system("open "+TEXT_FILE) | |
break | |
else: | |
show(args.show) | |
break | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment