Skip to content

Instantly share code, notes, and snippets.

@pcardune
Created September 2, 2011 04:47
Show Gist options
  • Save pcardune/1187930 to your computer and use it in GitHub Desktop.
Save pcardune/1187930 to your computer and use it in GitHub Desktop.
Authenticate with Facebook on the Command Line
#!/usr/bin/python2.6
import os.path
import json
import urllib2
import BaseHTTPServer
import webbrowser
from urlparse import urlparse, parse_qs
from urllib import urlencode
APP_ID = '<your-app-id-here>'
SERVER_PORT = 8080
REDIRECT_URI = 'http://127.0.0.1:%s/' % SERVER_PORT
ACCESS_TOKEN = None
LOCAL_FILE = '.fb_access_token'
def get_url(path, args=None):
args = args or {}
if ACCESS_TOKEN:
args['access_token'] = ACCESS_TOKEN
if 'access_token' in args or 'client_secret' in args:
endpoint = "https://graph.facebook.com"
else:
endpoint = "http://graph.facebook.com"
return endpoint+path+'?'+urlencode(args)
def get(path, args=None):
return json.loads(urllib2.urlopen(get_url(path, args=args)).read())
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
global ACCESS_TOKEN
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
params = parse_qs(urlparse(self.path).query)
ACCESS_TOKEN = params.get('access_token', [None])[0]
if ACCESS_TOKEN:
open(LOCAL_FILE,'w').write(ACCESS_TOKEN)
self.wfile.write("You have successfully logged in to facebook. "
"You can close this window now.")
else:
self.wfile.write('<html><head>'
'<script>location = "?"+location.hash.slice(1);</script>'
'</head></html>')
def print_status(item, color=u'\033[1;35m'):
print color + u"{name}\033[0m: {message}".format(name=item['from']['name'],
message=item['message'].strip())
def authenticate():
global ACCESS_TOKEN
if not os.path.exists(LOCAL_FILE):
print "Logging you in to facebook..."
webbrowser.open('https://www.facebook.com/dialog/oauth?' +
urlencode({'client_id':APP_ID,
'redirect_uri':REDIRECT_URI,
'response_type':'token',
'scope':'read_stream'}))
httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', SERVER_PORT), RequestHandler)
while ACCESS_TOKEN is None:
httpd.handle_request()
else:
ACCESS_TOKEN = open(LOCAL_FILE).read()
if __name__ == '__main__':
authenticate()
for item in get('/me/feed')['data']:
if item.get('type') == 'status':
print_status(item)
if 'comments' in item:
for comment in item['comments'].get('data', []):
print_status(comment, color=u'\033[1;33m')
print '---'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment