Python facebook.GraphAPI() Examples

The following are 19 code examples of facebook.GraphAPI(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module facebook , or try the search function .
Example #1
Source File: facebook_module.py    From stephanie-va with MIT License 6 votes vote down vote up
def do_init(self):
        app_id = self.get_configuration('facebook_app_id')
        app_secret = self.get_configuration('facebook_app_secret')
        app_access_token = self.get_configuration('facebook_access_token')
        if app_id and app_secret and app_access_token:
            params = {
                'client_id': app_id,
                'client_secret': app_secret,
                'grant_type': 'fb_exchange_token',
                'fb_exchange_token': app_access_token
            }
            r = self.requests.get("https://graph.facebook.com/oauth/access_token", params=params)
            if r.ok:
                oauth_access_token = r.json()['access_token']
                self.oauth_access_token = self.write_configuration('facebook_oauth_token', oauth_access_token)
                self.graph = facebook.GraphAPI(oauth_access_token)
                return True
        return False 
Example #2
Source File: shareonfacebook.py    From pets with MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        api = facebook.GraphAPI(
            access_token=self.config.fb_share_token, version=settings.FACEBOOK_SHARE_GRAPH_API_VERSION
        )
        url = self.config.fb_share_link

        for pet in Pet.objects.get_unpublished_pets():
            api.put_object(
                parent_object="me",
                connection_name="feed",
                message=self.get_message(pet),
                link=url.format(pet.get_absolute_url()),
            )

            pet.published = True
            pet.save() 
Example #3
Source File: facebook.py    From rssit with MIT License 6 votes vote down vote up
def generate_access_app(server, config, path):
    if not config["app_id"] or not config["app_secret"]:
        server.send_response(500, "Error")
        server.end_headers()

        server.wfile.write(bytes("app_id or app_secret not set", "UTF-8"))
        return True

    access_token = facebook.GraphAPI().get_app_access_token(
        config["app_id"],
        config["app_secret"]
    )

    server.send_response(200, "OK")
    server.end_headers()

    server.wfile.write(bytes(access_token, "UTF-8"))
    return True 
Example #4
Source File: 0117_get_gender_from_facebook.py    From canvas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def forwards(self, orm):
        batch_size = 100
        fb = facebook.GraphAPI(settings.FACEBOOK_APP_ACCESS_TOKEN)
        fb_uids = [str(fb_uid) for fb_uid in orm.FacebookUser.objects.values_list('fb_uid', flat=True)]
        for batch_start in range(0, len(fb_uids), batch_size):
            print batch_start, 'to', min(batch_start+batch_size, len(fb_uids))
            fb_results = fb_call(lambda: fb.get_objects(fb_uids[batch_start:batch_start+batch_size]))
            genders = defaultdict(lambda: [])
            for fb_uid, fb_user_info in fb_results.items():
                if not hasattr(fb_user_info, 'get'):
                    print "Facebook fucked up", repr(fb_uid), '=>', repr(fb_user_info)
                else:
                    genders[Gender.from_string(fb_user_info.get('gender', ''))].append(fb_uid)
            
            for gender, gendered_uids in genders.items():
                orm.FacebookUser.objects.filter(fb_uid__in=gendered_uids).update(gender=gender) 
Example #5
Source File: oauth20_account.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_user(self):
        """
        Override this method by sublcassing the class.

        """
        if not current.session.token:
            return None
        return dict(first_name='Pinco',
                    last_name='Pallino',
                    username='pincopallino')
        raise NotImplementedError("Must override get_user()")

        # Following code is never executed.  It can be used as example
        # for overriding in subclasses.
        if not self.accessToken():
            return None

        if not self.graph:
            self.graph = GraphAPI((self.accessToken()))

        user = None
        try:
            user = self.graph.get_object("me")
        except GraphAPIError:
            current.session.token = None
            self.graph = None

        if user:
            return dict(first_name=user['first_name'],
                        last_name=user['last_name'],
                        username=user['id']) 
Example #6
Source File: models.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def complete_quest(user, quest_comment, access_token, request=None):
    if user.id != quest_comment.author_id:
        raise ServiceError("You can't share to your timeline a drawing you didn't create.")

    try:
        user.facebookuser
    except FacebookUser.DoesNotExist:
        raise ServiceError("Can't share to your timeline if you haven't added your Facebook account yet.")

    # Although we've renamed it to "draw", Facebook still internally refers to it as "complete".
    action = 'complete'

    quest_url = quest_comment.get_share_page_url_with_tracking(user, 'facebook', absolute=True)

    @bgwork.defer
    def rewards():
        economy.credit_personal_share(user)

    send_action = '{}:{}'.format(settings.FACEBOOK_NAMESPACE, action)

    @bgwork.defer
    def do_graph_action():
        try:
            graph = GraphAPI(access_token)
            graph.put_object('me', send_action, quest=quest_url)
            if request:
                Metrics.share_to_timeline.record(request, quest=quest_url)
        except GraphAPIError as e:
            if request:
                Metrics.share_to_timeline_error.record(request, quest=quest_url)
            client.create_from_exception() 
Example #7
Source File: models.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def migrate_facebook_avatar(self, request, facebook_access_token):
        fb = GraphAPI(facebook_access_token)
        avatar = fb.get_object('me/picture', type='large', redirect='false')['data']

        if avatar.get('is_silhouette'):
            return

        self.userinfo.avatar = User.upload_avatar_from_url(request, avatar.get('url'))
        self.userinfo.save() 
Example #8
Source File: models.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def notify_friends_of_signup(self, access_token):
        fb = GraphAPI(access_token)
        friends = fb.get_object('me/friends')['data']
        fb_friends = FacebookUser.objects.filter(fb_uid__in=[friend['id'] for friend in friends])
        Actions.facebook_friend_joined(self.user, fb_friends) 
Example #9
Source File: models.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_fb_user_from_access_token(cls, access_token):
        fb = GraphAPI(access_token)
        try:
            fb_user = fb.get_object('me')
            return fb, fb_user
        except GraphAPIError:
            raise ServiceError("There appears to be an issue communicating with Facebook. "
                               "Please try logging in again.") 
Example #10
Source File: util.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_fb_api(request):
    fb_user = facebook.get_user_from_cookie(request.COOKIES,
                                            Config['facebook']['app_id'],
                                            Config['facebook']['secret'])
    access_token = fb_user and fb_user.get('access_token')
    if not access_token:
        raise NotLoggedIntoFacebookError()

    return fb_user, facebook.GraphAPI(access_token) 
Example #11
Source File: notifiers.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def _post_facebook(self, **data):
        if self.config['group_id']:
            api = facebook.GraphAPI(access_token=self.config['access_token'], version='2.12')

            try:
                api.put_object(parent_object=self.config['group_id'], connection_name='feed', **data)
                logger.info("Tautulli Notifiers :: {name} notification sent.".format(name=self.NAME))
                return True
            except Exception as e:
                logger.error("Tautulli Notifiers :: Error sending {name} post: {e}".format(name=self.NAME, e=e))
                return False

        else:
            logger.error("Tautulli Notifiers :: Error sending {name} post: No {name} Group ID provided.".format(name=self.NAME))
            return False 
Example #12
Source File: notifiers.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def _get_credentials(self, code=''):
        logger.info("Tautulli Notifiers :: Requesting access token from {name}.".format(name=self.NAME))

        app_id = plexpy.CONFIG.FACEBOOK_APP_ID
        app_secret = plexpy.CONFIG.FACEBOOK_APP_SECRET
        redirect_uri = plexpy.CONFIG.FACEBOOK_REDIRECT_URI

        try:
            # Request user access token
            api = facebook.GraphAPI(version='2.12')
            response = api.get_access_token_from_code(code=code,
                                                      redirect_uri=redirect_uri,
                                                      app_id=app_id,
                                                      app_secret=app_secret)
            access_token = response['access_token']

            # Request extended user access token
            api = facebook.GraphAPI(access_token=access_token, version='2.12')
            response = api.extend_access_token(app_id=app_id,
                                               app_secret=app_secret)

            plexpy.CONFIG.FACEBOOK_TOKEN = response['access_token']
        except Exception as e:
            logger.error("Tautulli Notifiers :: Error requesting {name} access token: {e}".format(name=self.NAME, e=e))
            plexpy.CONFIG.FACEBOOK_TOKEN = ''

        # Clear out temporary config values
        plexpy.CONFIG.FACEBOOK_APP_ID = ''
        plexpy.CONFIG.FACEBOOK_APP_SECRET = ''
        plexpy.CONFIG.FACEBOOK_REDIRECT_URI = ''

        return plexpy.CONFIG.FACEBOOK_TOKEN 
Example #13
Source File: fb-video-dl.py    From fb-video-dl with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_vidinfo(videoID):
    try:
        try:
            graph = facebook.GraphAPI()
            vidObject = graph.get_object(videoID)
            video_url = vidObject['source']
        except facebook.GraphAPIError:
            sys.exit('error : unable to reach facebook')


        url_h = urllib2.urlopen(video_url)
        meta  = url_h.info()
        size  = meta['Content-Length']
        content_type = meta['content-type']
        format = re.search('video/(\w+)', content_type).group(1)
        if vidObject.has_key('name'):
            filename = ''.join(e for e in vidObject['name'] if e.isalnum())
        else:
            filename = None
    except urllib2.URLError:
        sys.exit('error : unable to retrieve video info')


    info = {'url':video_url, 'name':filename, 'size':size, 'format':format}
    return info


#downloads the video 
Example #14
Source File: facebook.py    From rssit with MIT License 5 votes vote down vote up
def get_api(access_token):
    global graphs
    if access_token not in graphs:
        graphs[access_token] = facebook.GraphAPI(access_token)

    return graphs[access_token] 
Example #15
Source File: facebook_module.py    From stephanie-va with MIT License 5 votes vote down vote up
def set_graph(self, oauth_access_token=None):
        if oauth_access_token:
            self.oauth_access_token = oauth_access_token
        self.graph = facebook.GraphAPI(self.oauth_access_token) 
Example #16
Source File: auth.py    From selene-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_facebook_account_email(token: str) -> str:
    facebook_api = GraphAPI(token)
    facebook_account = facebook_api.get_object(id='me?fields=email')

    return facebook_account['email'] 
Example #17
Source File: facebook_api.py    From GraphiPy with MIT License 5 votes vote down vote up
def __init__(self, api):
        token = api["access_token"]
        id = api["id"]
        self.graph = facebook.GraphAPI(token) 
Example #18
Source File: auth.py    From app with MIT License 4 votes vote down vote up
def auth_facebook():
    """
    Authenticate user with Facebook
    Input:
        facebook_token: facebook access token
        device: to create an ApiKey associated with this device
    Output:
        200 and user info containing:
        {
            name: "John Wick",
            mfa_enabled: true,
            mfa_key: "a long string",
            api_key: "a long string"
        }

    """
    data = request.get_json()
    if not data:
        return jsonify(error="request body cannot be empty"), 400

    facebook_token = data.get("facebook_token")
    device = data.get("device")

    graph = facebook.GraphAPI(access_token=facebook_token)
    user_info = graph.get_object("me", fields="email,name")
    email = user_info.get("email").strip().lower()

    user = User.get_by(email=email)

    if not user:
        if DISABLE_REGISTRATION:
            return jsonify(error="registration is closed"), 400
        if not email_domain_can_be_used_as_mailbox(
            email
        ) or personal_email_already_used(email):
            return jsonify(error=f"cannot use {email} as personal inbox"), 400

        LOG.d("create facebook user with %s", user_info)
        user = User.create(email=email.lower(), name=user_info["name"], activated=True)
        db.session.commit()
        email_utils.send_welcome_email(user)

    if not SocialAuth.get_by(user_id=user.id, social="facebook"):
        SocialAuth.create(user_id=user.id, social="facebook")
        db.session.commit()

    return jsonify(**auth_payload(user, device)), 200 
Example #19
Source File: import_fbid_csv.py    From canvas with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def handle(self, *args, **options):
        users = [line.strip() for line in file('/var/canvas/data/canvas_installed_users.csv')]
        fb = facebook.GraphAPI(settings.FACEBOOK_APP_ACCESS_TOKEN)
        
        def fb_call(fun, retries=0):
            try:
                return fun()
            except (facebook.GraphAPIError, IOError):
                if retries < 5:
                    time.sleep(retries + 0.01)
                    return fb_call(fun, retries + 1)
                else:
                    raise
        
        missing = 0
        existing = 0
        added = 0
        try:
            for n in range(0, len(users), 100):
                fb_results = fb_call(lambda: fb.get_objects(users[n:n+100]))
                for fbid, info in fb_results.items():
                    if "email" not in info:
                        print "no email", fbid
                        missing += 1
                    else:
                        try:                        
                            FacebookUser(
                                 fb_uid=info['id'], 
                                 email=info['email'],
                                 first_name=info['first_name'],
                                 last_name=info['last_name'],
                                 user=None
                             ).save()
                        except IntegrityError:
                            existing += 1
                        else:
                            added += 1
        
                        
                        
                print "Processed", n, "of", len(users)
        finally:
            print "Total", len(users)
            print "Missing email", missing
            print "Added", added
            print "Existing", existing