Skip to content

Instantly share code, notes, and snippets.

@ogawa
Created October 19, 2010 07:55
Show Gist options
  • Save ogawa/633809 to your computer and use it in GitHub Desktop.
Save ogawa/633809 to your computer and use it in GitHub Desktop.
FacebookCommander - an early prototype of a command-line interface for Facebook
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getopt
import os, yaml
import cgi
import urllib
import webbrowser
import facebook
class BaseHandler():
redirect_uri = 'http://www.facebook.com/connect/login_success.html'
def __init__(self, yaml_file=None):
if not yaml_file:
yaml_file = os.path.join(os.path.dirname(__file__), 'fc.yaml')
self.config = yaml.safe_load(
open(yaml_file).read().decode('utf-8')
)
if not 'app_id' in self.config:
sys.exit('app_id is not defined in fc.yaml.')
if not 'app_secret' in self.config:
sys.exit('app_secret is not defined in fc.yaml.')
class AppVerificationHandler(BaseHandler):
def get(self):
if 'code' in self.config:
print 'code has already been defined in fc.yaml'
return
params = dict(
client_id=self.config['app_id'],
redirect_uri=self.redirect_uri
)
url = 'https://graph.facebook.com/oauth/authorize?' + urllib.urlencode(params)
webbrowser.open(url)
print 'First, open the following URL via your browser:'
print url
print
print 'After allowing the permission of this command, you\'ll be redirected to the follwing URL:'
print 'http://www.facebook.com/connect/login_success.html?code=xxxx'
print
print 'Please add the following line to your fc.py by hand.'
print 'code: xxxx'
sys.exit()
class AccessTokenHandler(BaseHandler):
def get(self):
if 'code' in self.config:
params = dict(
client_id=self.config['app_id'],
redirect_uri=self.redirect_uri,
client_secret=self.config['app_secret'],
code=self.config['code']
)
res = cgi.parse_qs(urllib.urlopen(
'https://graph.facebook.com/oauth/access_token?' +
urllib.urlencode(params)).read())
access_token = res['access_token'][-1]
return access_token
else:
verifier = AppVerificationHandler()
verifier.get() # may quit this program.
class FacebookCommander(facebook.GraphAPI):
def __init__(self, access_token=None, yaml_file=None):
if not access_token:
access_token = AccessTokenHandler(yaml_file=yaml_file).get()
self.access_token = access_token
""" Utility methods """
def get_profile(self, profile_id='me'):
profile = self.get_object(profile_id)
return profile
def put_link(self, url, message='', profile_id='me'):
self.put_wall_post(
message=message,
attachment=dict(link=url, type='link'),
profile_id=profile_id
)
return
""" post by facebook.GraphAPI (http://github.com/facebook/python-sdk) """
def test_put_wall_post():
fc = FacebookCommander()
fc.put_wall_post('なるほど四時じゃねーよ')
""" post by FacebookCommander method """
def test_put_link():
fc = FacebookCommander()
fc.put_link(message='Hello, again!', url='http://www.google.com/')
def usage():
print 'Usage: %s [--help] [--yaml=config_file] [--wall=message]' % sys.argv[0]
print
print ' --help print this message.'
print ' --yaml specify a config file.'
print ' --wall specify a message to post.'
print
def main():
try:
optlist, args = getopt.getopt(sys.argv[1:], 'hc:w:', longopts=['help', 'yaml=', 'wall='])
except getopt.GetoptError:
usage()
sys.exit(2)
yaml_file = None
message = None
for opt, arg in optlist:
if opt in ('-h', '--help'):
usage()
sys.exit()
if opt in ('-y', '--yaml'):
yaml_file = arg
if opt in ('-w', '--wall'):
message = arg
if message:
fc = FacebookCommander(yaml_file=yaml_file)
fc.put_wall_post(message)
else:
print "No message."
if __name__ == "__main__":
main()
app_id: NNNNNNNN
app_secret: XXXXXXXXX
#code: YYYYYYYYY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment