Python - Facebook API - Need a working example - python

Ok, so i've googled around, i've found threads here on stackoverflow and i've checked the official Facebook wiki and.. and what not..
I now hope that one of you guys sits on a Facebook API sample code for Python.
This is what i've got so far and all i get is "Invalid Signature" via PyFacebook which appears to be a dead project:
from facebook import Facebook
api_key = '123456789______'
secret = '<proper secret key>'
OTK = 'XXXXX' # <-- You get this from: https://www.facebook.com/code_gen.php?v=1.0&api_key=123456789______
long_term_key = None
fb = Facebook(api_key, secret)
def generate_session_from_onetime_code(fb, code):
fb.auth_token = code
return fb.auth.getSession()
if not long_term_key:
long_term_key = generate_session_from_onetime_code(fb, OTK)['session_key']
print 'Replace None with this in the .py file for long_term_key:'
print long_term_key
fb.session_key = long_term_key
fb.uid = 000000001 # <-- Your user-id
fb.signature = api_key # <-- This doesn't work at all, MD5 of what?
#fb.validate_signature(fb) # <-- doesn't work either, prob need to pass MD5 handle?
print fb.friends.get() # <-- Generates "Invalid Signature"
"all" i want, is to retrieve my friends list for now,
if there's a better API point me in the right direction but Facebook has officially declared their own Python SDK dead and pyfacebook is almost working for me but not quite..
So, please help.

The unofficial fork of the python sdk is still working fine for me.
To retrieve your friends, generate an access token here:
https://developers.facebook.com/tools/access_token/
Limitations:
A user access token with user_friends permission is required to view
the current person's friends.
This will only return any friends who have used (via Facebook Login) the app making the request.
If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.
Code
import facebook
token = 'your token'
graph = facebook.GraphAPI(token)
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
friend_list = [friend['name'] for friend in friends['data']]
print friend_list

Related

How do I get the firebase current user id (uid) in python?

I need to get the current user id.
In Javascript I use this to obtain the id
uid = firebase.auth().currentUser.uid // uid= ABO0Xc2E6KSDodEhenICkXF371x1
how do I get the uid in python
?
This is the code to retrieve the user id without login or signup.
auth.current_user['localId']
user = auth.sign_in_with_email_and_password(email,password)
print(user['localId'])
this will display the current firebase UID on output screen
You didn't mention a library, but all your other questions are using Pyrebase, so skimming over the documentation (which you should definitely be reading)...
# Get a reference to the auth service
auth = firebase.auth()
# Log the user in
user = auth.sign_in_with_email_and_password(email, password)
# Get the user's idToken
token = user['idToken']
Resurfacing an old question, but looking in to the documentation of Pyrebase here, I noticed that when you refresh the token, the userId is (compared to the other auth functions) retreived. So my solution is:
user = auth.sign_in_with_email_and_password("email", "pass")
user = auth.refresh(user['refreshToken'])
print(user['userId'])
EDIT:
I now see there is a 'localId' variable in the user object even before refreshing - as #Abdul indicated.

where can I get all names of connections in the graph API

import facebook
token = 'your token'
graph = facebook.GraphAPI(token)
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
the second parameter in the method get_connections() is the name if a connection, I found the documentation of graph api (http://facebook-sdk.readthedocs.org/en/latest/api.html) but I could not get the information how I get a list with all names of all connections which exist in a graph.
Thank you!
Always use the official API reference, all the existing connections are in there: https://developers.facebook.com/docs/graph-api/reference
For example: https://developers.facebook.com/docs/graph-api/reference/user/
(Scroll down to "Edges")

PRAW: Authorizing with OAuth prevents me from getting submissions/comments

If I use OAuth, I am unable to get new submissions or comments from a subreddit.
My Oauth code looks like this:
import praw
import webbrowser
r = praw.Reddit(user_agent)
r.set_oauth_app_info(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
authURL = r.get_authorize_url("FUZZYPICKLES", "identity submit", True)
webbrowser.open(authURL)
authCode = input("Enter the code: ")
accInfo = r.get_access_information(authCode)
After that I can try to get submissions
submission = r.get_subreddit("test").get_new()
or comments
comments = r.get_comments("test")
but if I use either value, the program crashes with the error:
raise OAuthInsufficientScope('insufficient_scope', response.url)
praw.errors.OAuthInsufficientScope: insufficient_scope on url https://oauth.reddit.com/r/test/comments/.json
If I don't use OAuth, either by using login() or by just not authorizing, I have no such issues. I am using Python 3.4. What am I doing wrong?
I found the solution myself. To read posts, you need "read" in your list of requested scopes. So, "identity submit" should be "identity read submit".

Navigating nodes/connections/objects in Facebook API + Python

I am connecting to Facebook fine with pythonforfacebook, I have an access token set up that grants me this information, but I don't know the correct syntax for getting a dictionary with my friends names and hometown. Can someone help me out as to how this should be corrected?
import facebook
graph = facebook.GraphAPI("access token")
friends = graph.get_connections("me", "friends")
print friends[hometown]
Ensure that you have friends_hometown permission also you need to explicitly request it as a field
friends = graph.get_connections("me", "friends", fields="hometown")
Then you cannot access hometowns like that you need to understand the data structure. friends holds data (which holds all your friends) and a paging parameter.
for fr in friends['data']:
if 'hometown' in fr:
print fr['id'] + ' ' + fr['hometown']['name']

Twython - How to associate multiple twitter accounts with one user

I want to allow registered users to add multiple twitter accounts. I followed twython-django example, and got a working version of one user - one twitter account. If the user tries to use twitter login again, follows same view again, I get this error: Invalid / expired Token.
I tried adding force_login=true to oauth/authorize and oauth/authenticate, removing 'request_token' from request.session dict, but i still get Invalid Token error during get_authentication_tokens().
How to properly associate multiple twitter accounts with the same user, using twython? What am I missing here?
Here is an a twython-django example: https://github.com/ryanmcgrath/twython-django/blob/master/twython_django_oauth/views.py
My view:
def twitter_login(request):
redirect_back_to_url = request.build_absolute_uri()
if 'request_token' not in request.session:
# request authorization tokens
t = Twython(twitter_token=settings.TWITTER_CONSUMER_KEY,
twitter_secret=settings.TWITTER_CONSUMER_SECRET,
callback_url=redirect_back_to_url)
# Request an authorization url to send the user to...
request_oauth_key = t.get_authentication_tokens()
# signing current session as one with twitter authentication
request.session['request_token'] = request_oauth_key
# redirecting the user to twitter authorization url for authentication
return HttpResponseRedirect(request_oauth_key['auth_url'])
else:
# user authenticated, receiving auth token
t2 = Twython(twitter_token=settings.TWITTER_CONSUMER_KEY,
twitter_secret=settings.TWITTER_CONSUMER_SECRET,
oauth_token=request.session['request_token'][
'oauth_token'],
oauth_token_secret=request.session['request_token'][
'oauth_token_secret'])
oauth_key = t2.get_authorized_tokens()
# save authorized tokens
# twitter oauth tokens dont expire
token = Token.objects.get_or_create(account_name=oauth_key['screen_name'],
token=oauth_key['oauth_token'],
secret=oauth_key['oauth_token_secret'])
user = request.user.get_profile()
user.twitter.add(token[0].id)
user.save()
logger.info('Successfully acquired twitter oauth token.')
return HttpResponseRedirect(reverse('profile'))
Update: possible solution
I changed my view to this:
def twitter_login(request):
redirect_back_to_url = request.build_absolute_uri()
if 'request_token' not in request.session:
# request authorization tokens
t = Twython(twitter_token=settings.TWITTER_CONSUMER_KEY,
twitter_secret=settings.TWITTER_CONSUMER_SECRET,
callback_url=redirect_back_to_url)
# Request an authorization url to send the user to...
request_oauth_key = t.get_authentication_tokens()
# signing current session as one with twitter authentication
request.session['request_token'] = request_oauth_key
# redirecting the user to twitter authorization url for authentication
return HttpResponseRedirect(request_oauth_key['auth_url'])
else:
# user authenticated, receiving auth token
t2 = Twython(twitter_token=settings.TWITTER_CONSUMER_KEY,
twitter_secret=settings.TWITTER_CONSUMER_SECRET,
oauth_token=request.session['request_token'][
'oauth_token'],
oauth_token_secret=request.session['request_token'][
'oauth_token_secret'])
oauth_key = t2.get_authorized_tokens()
if 'screen_name' not in oauth_key:
del request.session['request_token']
request.session.modified = True
return HttpResponseRedirect(reverse('twitter_login'))
# save authorized tokens
# twitter oauth tokens dont expire
token = Token.objects.get_or_create(account_name=oauth_key['screen_name'],
token=oauth_key['oauth_token'],
secret=oauth_key['oauth_token_secret'])
user = request.user.get_profile()
user.twitter.add(token[0].id)
user.save()
logger.info('Successfully acquired twitter oauth token.')
return HttpResponseRedirect(reverse('profile'))
And not sure yet if this had anything to do with it. I added after line 272 in twython.py request_args['force_login'] = True. But, as i said, i'm not sure if that had any impact, cos according to https://dev.twitter.com/docs/api/1/post/oauth/request_token force login is not one of the optional args.
Some voodoo this was. lol.
Tell me if its a total rubbish.
Mmm, I believe OP got it working/right, but just as a quick breakdown, twython-django isn't built to support multiple account associations (it's also not on Django 1.5, so be careful with that until it's updated~).
You'd need to do what OP did and set up a separate table for Tokens that match over to a User, and then handle which account they're currently using by pulling the appropriate tokens. OPs use of force_login also seems to have worked because, while it's not necessarily documented, I believe it still works (according to this thread, unless I'm misreading it - if I am, I would love to be corrected).
I don't expect this answer to be accepted as I'm not really solving anything, but if anyone else encounters this I'm hoping to leave something more clear-cut than the above notes. Hope that's alright!

Categories