Count likes on a Facebook post using Python+Facebook Graph API - python

I want to count how many times a friend has liked a user's post using Python.
I have successfully fetched the names of friends who have liked the posts. But there are some posts which don't have any like at all. The code gives an error there. I'm using facebook-sdk 1.0.0. Any help would be much appreciated.
Code snippet is:
import facebook
graph=facebook.GraphAPI(access_token="")
posts=graph.get_connections(id="me",connection_name="posts")
for w in range (0,5):
p1=posts['data'][w]['likes']['data']
for i in range (0,len(p1)):
r=p1[i]['name']
print(r)
Also, Is there any way to find out the list of friends hitting maximum likes on all posts?

I am a little unsure on exactly what you are missing here or what your question is, but it looks like all you need to do is define the name you want to look for and count how many times it occurs in your code.
Something like this:
import facebook
likes = 0 # How many times they likes on your posts
friend = "Bob" # Your friends name
graph=facebook.GraphAPI(access_token="")
posts=graph.get_connections(id="me",connection_name="posts")
for w in range (0,5):
p1=posts['data'][w]['likes']['data']
for i in range (0,len(p1)):
if friend == p1[i]['name']
likes += 1
print likes
Also, you could clean up your code considerably if you ditched the ranges for your for loops and instead iterated over the data structures themselves. Something like this would work:
import facebook
likes = 0 # How many times they likes on your posts
friend = "Bob" # Your friends name
graph=facebook.GraphAPI(access_token="")
posts=graph.get_connections(id="me",connection_name="posts")
for user_post in posts['data']:
for name in user_post['likes']['data']:
if friend == name['name']
likes += 1

Related

Twitter timeline in Python, but only getting 20ish results?

I'm a nub when it comes to python. I literally just started today and have little understanding of programming. I have managed to make the following code work:
from twitter import *
config = {}
execfile("config.py", config)
twitter = Twitter(
auth = OAuth(config["access_key"], config["access_secret"],
config["consumer_key"], config["consumer_secret"]))
user = "skiftetse"
results = twitter.statuses.user_timeline(screen_name = user)
for status in results:
print "(%s) %s" % (status["created_at"], status["text"].encode("ascii",
"ignore"))
The problem is that it's only printing 20 results. The twitter page i'd like to get data from has 22k posts, so something is wrong with the last line of code.
screenshot
I would really appreciate help with this! I'm doing this for a research sentiment analysis, so I need several 100's to analyze. Beyond that it'd be great if retweets and information about how many people re tweeted their posts were included. I need to get better at all this, but right now I just need to meet that deadline at the end of the month.
You need to understand how the Twitter API works. Specifically, the user_timeline documentation.
By default, a request will only return 20 Tweets. If you want more, you will need to set the count parameter to, say, 50.
e.g.
results = twitter.statuses.user_timeline(screen_name = user, count = 50)
Note, count:
Specifies the number of tweets to try and retrieve, up to a maximum of 200 per distinct request.
In addition, the API will only let you retrieve the most recent 3,200 Tweets.

Facebook SDK for Python - getting all page likes of a Facebook profile

Using an access token from the Facebook Graph API Explorer (https://developers.facebook.com/tools/explorer), with access scope which includes user likes, I am using the following code to try to get all the likes of a user profile:
myfbgraph = facebook.GraphAPI(token)
mylikes = myfbgraph.get_connections(id="me", connection_name="likes")['data']
for like in mylikes:
print like['name'], like['category']
...
However this is always giving me only 25 likes, whereas I know that the profile I'm using has 42 likes. Is there some innate limit operating here, or what's the problem in getting ALL the page likes of a user profile?
Per the Graph documention:
When you make an API request to a node or edge, you will usually not
receive all of the results of that request in a single response. This
is because some responses could contain thousands and thousands of
objects, and so most responses are paginated by default.
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.2#paging
Well, this appears to work (a method, which accepts a user's facebook graph):
def get_myfacebook_likes(myfacebook_graph):
myfacebook_likes = []
myfacebook_likes_info = myfacebook_graph.get_connections("me", "likes")
while myfacebook_likes_info['data']:
for like in myfacebook_likes_info['data']:
myfacebook_likes.append(like)
if 'next' in myfacebook_likes_info['paging'].keys():
myfacebook_likes_info = requests.get(myfacebook_likes_info['paging']['next']).json()
else:
break
return myfacebook_likes
The above answers will work, but pretty slowly for anything with many likes. If you just want the count for number of likes, you can get it much more efficiently with total_likes:
myfacebook_likes_info = graph.get_connections(post['id'], 'likes?summary=1')
print myfacebook_likes_info["summary"]["total_count"]

Random page of followers of a Twitter user

Consider a Twitter user who has 1 million followers. I want to collect a random page of followers of this user. Is there any way to do this? I don't want to get the list of all followers because it would exhaust my tokens.
I'm looking for something like this:
follower_ids = api.followers_ids(user_id, page=page_index)
where page_index is a random page.
Thanks.
From the documentation, you can get the amount of followers from a user, e.g. twitterdev:
https://api.twitter.com/1.1/users/show.json?screen_name=twitterdev
This returns, amongst other things, followers_count:
{
...
"followers_count": 143916,
...
}
From there you can work out how which pages the random followers are on.
Just to be clear, I've never used twitter, or the API, and have just searched for you.
you can select for example 20 ids from all ids like this:
SCREEN_NAME= "the_user_name"
followersIds = api.followers_ids(SCREEN_NAME)
print followersIds[:20]

Discogs API => How to retrieve genre?

I've crawled a tracklist of 36.000 songs, which have been played on the Danish national radio station P3. I want to do some statistics on how frequently each of the genres have been played within this period, so I figured the discogs API might help labeling each track with genre. However, the documentation for the API doesent seem to include an example for querying the genre of a particular song.
I have a CSV-file with with 3 columns: Artist, Title & Test(Test where i want the API to label each song with the genre).
Here's a sample of the script i've built so far:
import json
import pandas as pd
import requests
import discogs_client
d = discogs_client.Client('ExampleApplication/0.1')
d.set_consumer_key('key-here', 'secret-here')
input = pd.read_csv('Desktop/TEST.csv', encoding='utf-8',error_bad_lines=False)
df = input[['Artist', 'Title', 'Test']]
df.columns = ['Artist', 'Title','Test']
for i in range(0, len(list(df.Artist))):
x = df.Artist[i]
g = d.artist(x)
df.Test[i] = str(g)
df.to_csv('Desktop/TEST2.csv', encoding='utf-8', index=False)
This script has been working with a dummy file with 3 records in it so far, for mapping the artist of a given ID#. But as soon as the file gets larger(ex. 2000), it returns a HTTPerror when it cannot find the artist.
I have some questions regarding this approach:
1) Would you recommend using the search query function in the API for retrieving a variable as 'Genre'. Or do you think it is possible to retrieve Genre with a 'd.' function from the API?
2) Will I need to aquire an API-key? I have succesfully mapped the 3 records without an API-key so far. Looks like the key is free though.
Here's the guide I have been following:
https://github.com/discogs/discogs_client
And here's the documentation for the API:
https://www.discogs.com/developers/#page:home,header:home-quickstart
Maybe you need to re-read the discogs_client examples, i am not an expert myself, but a newbie trying to use this API.
AFAIK, g = d.artist(x) fails because x must be a integer not a string.
So you must first do a search, then get the artist id, then d.artist(artist_id)
Sorry for no providing an example, i am python newbie right now ;)
Also have you checked acoustid for
It's a probably a rate limit.
Read the status code of your response, you should find an 429 Too Many Requests
Unfortunately, if that's the case, the only solution is to add a sleep in your code to make one request per second.
Checkout the api doc:
http://www.discogs.com/developers/#page:home,header:home-rate-limiting
I found this guide:
https://github.com/neutralino1/discogs_client.
Access the api with your key and try something like:
d = discogs_client.Client('something.py', user_token=auth_token)
release = d.release(774004)
genre = release.genres
If you found a better solution please share.

Full list of twitter "friends" using python and tweepy

By friends I mean all of the twitter users who I am following.
Is it possible using tweepy with python 2.7.6 to display a full list of all friends?
I have found it possible to display a list which contains some of my friends with the following code. After handling authorization of course.
api = tweepy.API(auth)
user = api.get_user('MyTwitterHandle')
print "My Twitter Handle:" , user.screen_name
ct = 0
for friend in user.friends():
print friend.screen_name
ct = ct + 1
print "\n\nFinal Count:", ct
This code successfully prints what appears to be my 20 most recent friends on Twitter, the ct variable is equal to 20. This method excludes the rest of the users I am following on Twitter.
Is it possible to display all of the users I am following on twitter? Or at least a way to adjust a parameter to allow me to include more friends?
According to the source code, friends() is referred to the GET friends / list twitter endpoint, which allows a count parameter to be passed in:
The number of users to return per page, up to a maximum of 200. Defaults to 20.
This would allow you to get 200 friends via friends().
Or, better approach would be to use a Cursor which is a paginated way to get all of the friends:
for friend in tweepy.Cursor(api.friends).items():
# Process the friend here
process_friend(friend)
See also:
incomplete friends list
Tweepy Cursor vs Iterative for low API calls

Categories

Resources