Obtaining Friends Count And Favorites Count From User Object - python

I am having trouble obtaining friends_count and favorites_count using the search_all_tweets Tweepy V2 API call.
GeeksForGeeks lists friends_count and favorites_count as attributes ( https://www.geeksforgeeks.org/python-user-object-in-tweepy/). Unfortunately, I get an Attribute Error raise AttributeError from None with the last 2 lines of code.
user.public_metrics only consists of followers_count,following_count,tweet_count, and listed_count.
user.entities consist of extraneous url data.
Code is shown below:
client = tweepy.Client(bearer_token=config.BEARER_TOKEN, consumer_key=
config.CONSUMER_KEY,consumer_secret= config.CONSUMER_SECRET,access_token=
config.ACCESS_TOKEN,access_token_secret= config.ACCESS_TOKEN_SECRET)
for response in tweepy.Paginator(client.search_all_tweets, query=s,
tweet_fields=['context_annotations','created_at', 'public_metrics','author_id', 'lang', 'geo', 'entities'],
user_fields=['username','entities','public_metrics','location','verified','description'],
max_results=100, expansions='author_id'):
for user in response.includes["users"]:
print(user.public_metrics)
print(user.entities)
print(user.friends_count)
print(user.favorites_count)

The fields listed by GeeksForGeeks are the User's fields in the Twitter V1 API.
There is unfortunately no way to get the number of likes of an User with the Twitter V2 API. You can try to get all his likes and count the total number of returned tweets, but that will work only if the User has only a few likes (and that will consume your monthly Tweet cap).
And friends was the previous name of followings, so the equivalent of friends_count in the Twitter V2 API is following_count. If you were looking for the mutuals, you have to get the full list of followers and the full list of followings of the user and count the number of common elements.
Finally, I would advise you to use the Twitter API documentation (here for User objects).

Related

How to get the number of tweets from a hastag in python?

I am trying to get the number of tweets containing a hashtag (let's say "#kitten") in python.
I am using tweepy.
However, all the codes I have found are in this form :
query = "kitten"
for i, status in enumerate(tweepy.Cursor(api.search, q=query).items(50)):
print(i, status)
I have this error : 'API' object has no attribute 'search'
Tweepy seemed to not cointain this object anymore. Is there any way to answer my problem ?
Sorry for my bad english.
After browsing the web and twitter documentation I found the answer.
If you want the historic of all tweet counts from 2006 you need Academic authorization. This is not my case so I can only get 7 days tracking which is enough in my case. Here is the code :
import tweepy
query = "kitten -is:retweet"
client = tweepy.Client(bearer_token)
counts = client.get_recent_tweets_count(query=query, granularity='day')
for i in counts.data:
print(i["tweet_count"])
The "-is:retweet" is here to not count the retweets. You need to remove it if you want to count them.
Since we're not pulling any tweets (only the volume of them) we are not increasing our MONTHLY TWEET CAP USAGE.
Be carefull when using symbols in your query such as "$" it might give you an error. For a list of valid operators see : list of valid operators for query
As said here Twitter counts introduction, you only need "read only" authorization to perform a recent count request. (see Recent Tweet counts)

Tweepy get Tweets related to a specific country

Context
I am working on a topic modeling for twitter project.
The idea is to retrieve all tweets related to a specific country and analyze them in order to discover what people from a specific country are talking about on Twitter.
What I have tried
1.First Solution
I know that we can use twitter streaming API or cursor to retrieve tweets from a specific country and I have tried the following code to get all tweets given geocodes coordinates of a country.
I have written the following code :
def get_tweets(query_fname, auth, max_time, location=None):
stop = datetime.now() + max_time
twitter_stream = Stream(auth, CustomListener(query_fname))
while datetime.now() < stop:
if location:
twitter_stream.filter(locations=[11.94,-13.64,30.54,5.19], is_async=True)
else:
twitter_stream.filter(track=query, is_async=True)
The problem of this approach
Not everyone has allowed Twitter to access his location details and with this approach, I can only get a few tweets something like 300 tweets for my location.
There are some persons who are not in the country but who tweet about the country and people within the country replies to them. Their tweets are not captured by this approach.
2.Second Solution
Another approach was to collect tweets with hashtags related to a country with a cursor
I have tried this code :
def query_tweet(client, query=[], max_tweets=2000, country=None):
"""
query tweets using the query list pass in parameter
"""
query = ' OR '.join(query)
name = 'by_hashtags_'
now = datetime.now()
today = now.strftime("%d-%m-%Y-%H-%M")
with open('data/query_drc_{}_{}.jsonl'.format(name, today), 'w') as f:
for status in Cursor(
client.search,
q=query,
include_rts=True).items(max_tweets):
f.write(json.dumps(status._json) + "\n")
Problem
This approach gives more results than the first one but as you may notice, not everyone uses those hashtags to tweets about the country.
3.Third approach
I have tried to retrieve the tweet using place id specific to a country but it gives the same problem as the first approach.
My questions
How can I retrieve all tweets about a specific country? I mean everything people are tweeting about for a specific country with or without country-specific hashtags?
Hint: For people who are not located in the country, It may be a good idea to get their tweets if they were replied or retweeted by people within the country.
Regards.

How to find ids of all existing Facebook ad campaigns

I want to extract ids of all ad campaigns using facebook api in python.
me = AdUser(fbid='me')
my_account = me.get_ad_account()
Now for AdAccount 'my_account', I want to get the list of ids of all campaigns. Tried to use
my_account.get_ad_campaigns()
But it gives me the following error:
'AdAccount' object has no attribute 'get_ad_campaigns'
Use the following
my_account.get_campaigns()
Thanks Kanika, this helped me a lot.
In addition, in order to get just the id's themselves you could use the following:
campaigns = account.get_campaigns()
camp_list = []
for campaign in campaigns:
camp_list.append(campaign[Campaign.Field.id])
print(camp_list)
Facebook Developers seemingly haven't updated their documentation fully. You can get more info by checking out the repo here:
https://github.com/facebook/facebook-python-ads-sdk/tree/master/facebookads
Note that according to Facebook, objects.py is now deprecated: "Please use objects in adobjects folder instead." However, it looks like some code snippets they provide still refer to objects.py.

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"]

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