Search code examples
pythonfacebookpyfacebook

PyFacebook Infinite Session


I am trying to set a cron task to read updates for a Facebook application. I have prompted the user to grant Offline Access permissions and i have store the session_key in the db.

I am crearing a new Facebook object and besides api and secret key I also use the session_key (previously stored in db) and the fb uid. When i am trying to create the auth token or do a API call i get a Error 104: Incorrect signature

Any ideas, experience, hints ?


Solution

  • I just wrote a blog entry about my search for something similar - need to write a Python cron script. Here's what I came up with:

    #!/usr/bin/python
    import os, sys, optparse, time, json
    import facebook
    
    ##
    
    USER_SESSION_FILE = os.path.expanduser('fb-user.session')
    APP_KEY_FILE = os.path.expanduser('fb-app.keys')
    
    ##
    
    def main():
        app_keys = open(APP_KEY_FILE).readlines()
        fb_api = facebook.Facebook(api_key=app_keys[0].strip(), secret_key=app_keys[1].strip())
        opts, args = parse_options()
        if args == ['init']:
            init(fb_api)
            return
        session = json.load(open(USER_SESSION_FILE))
        fb_api.uid = session['uid']
        fb_api.secret = session['secret']
        fb_api.session_key = session['session_key']
    
        fb_api.stream.publish(message="test from PyFacebook")
    
    
    def init(fb_api):
        fb_api.auth.createToken()
    
        sys.stdout.write('Opening web page to add application (press ENTER when done)...')
        sys.stdout.flush()
        fb_api.login()
        raw_input()
    
        sys.stdout.write('Asking for offline access now...')
        sys.stdout.flush()
        fb_api.request_extended_permission('offline_access')
        raw_input()
    
        sys.stdout.write('And, finally, asking for permission to publish')
        sys.stdout.flush()
        fb_api.request_extended_permission('publish_stream')
        raw_input()
    
        fb_api.auth.getSession()
    
        if fb_api.session_key_expires != 0:
            print """We were granted a temporary key; please wait a minute and run `%s init` again.""" % (sys.argv[0],)
        else:
            if not os.path.exists(USER_SESSION_FILE):
                # Only set restrictive permissions when creating the file
                # ourselves.
                open(USER_SESSION_FILE, 'w').close()
                os.chmod(USER_SESSION_FILE, 0600)
            json.dump({
                       'uid': fb_api.uid,
                       'secret': fb_api.secret,
                       'session_key': fb_api.session_key,
                       },
                       open(USER_SESSION_FILE, 'w'),
                       sort_keys=True,
                       indent=4)
    
    
    def parse_options():
        p = optparse.OptionParser()
        return p.parse_args()
    
    
    if __name__ == '__main__':
        sys.exit(main())