Get all friends of a given user on twitter with tweepy - python

Using tweepy I am able to return all of my friends using a cursor. Is it possible to specify another user and get all of their friends?
user = api.get_user('myTwitter')
print "Retreiving friends for", user.screen_name
for friend in tweepy.Cursor(api.friends).items():
print "\n", friend.screen_name
Which prints a list of all my friends, however if I change the first line
to another twitter user it still returns my friends. How can I get friends for any given user using tweepy?
#first line is changed to
user = api.get_user('otherUsername') #still returns my friends
Additionally user.screen_name when printed WILL return otherUsername
The question Get All Follower IDs in Twitter by Tweepy does essentially what I am looking for however it returns only a count of ID's. If I remove the len() function I will I can iterate through a list of user IDs, but is it possible to get screen names #twitter,#stackoverflow, #etc.....?

You can use the ids variable from the answer you referenced in the other answer to get the the id of the followers of a given person, and extend it to get the screen names of all of the followers using Tweepy's api.lookup_users method:
import time
import tweepy
auth = tweepy.OAuthHandler(..., ...)
auth.set_access_token(..., ...)
api = tweepy.API(auth)
ids = []
for page in tweepy.Cursor(api.followers_ids, screen_name="McDonalds").pages():
ids.extend(page)
time.sleep(60)
screen_names = [user.screen_name for user in api.lookup_users(user_ids=ids)]

You can use this:
# import the module
import tweepy
# assign the values accordingly
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
# authorization of consumer key and consumer secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# set access to user's access key and access secret
auth.set_access_token(access_token, access_token_secret)
# calling the api
api = tweepy.API(auth)
# the screen_name of the targeted user
screen_name = "TwitterIndia"
# printing the latest 20 friends of the user
for friend in api.friends(screen_name):
print(friend.screen_name)
for more details see https://www.geeksforgeeks.org/python-api-friends-in-tweepy/

Related

Using Python and Tweepy - How to reply with set text each time a specific user tweets?

I am able to reply to a specific tweet by getting tweet IDs, but cannot get my configuration to do what I want it to do, which is to reply to every tweet from a specific user. I have that user's username and ID. Currently it appears to only be pulling one tweet, which I suspect has something to do with line 23's tweet.id. I guess what I'm looking for is a way to ensure that my bot replies every single time this user tweets. Here is my current code (sensitive info redacted)
from ast import For
import tweepy
api_key = "###############################################"
api_secret = "###############################################"
bearer_token = r"###############################################"
access_token = "###############################################"
access_token_secret = "###############################################"
client = tweepy.Client(bearer_token, api_key, api_secret, access_token, access_token_secret)
auth = tweepy.OAuth1UserHandler(api_key, api_secret, access_token, access_token_secret)
api = tweepy.API(auth)
toReply = "TwitterUsernameHere"
api = tweepy.API(auth)
tweets = api.user_timeline(screen_name = toReply, count=1)
for tweet in tweets:
api.update_status("#" + toReply + " Why? ", in_reply_to_status_id = tweet.id)
Assuming that you are following the Twitter automation rules (i.e. that you're only replying to Tweets that the user has opted-in for your app to reply to - otherwise your user account or app will be restricted)...
... your code currently checks the user's Timeline, and then replies to the most recent single Tweet (count=1 on the user_timeline call). You would need this to check for new Tweets in order to reply to different ones. You could store tweet.id somewhere and only reply to it when it changes.
Note that there are a few other things to tidy up:
from ast import For is not required
client = tweepy.Client targets the Twitter API v2 but the rest of the code uses Twitter API v1.1 (via tweepy.API)
bearer_token is unused in this code and will only work for a read operation in v1.1 of the API so you could remove it.

how to collect twitter data from multiple IDs

I have a list of 14 user IDs and I have to collect them from each of the users.I run this Code to get the IDs from different Account. How could I get data from all the accounts?
# assign the values accordingly
consumer_key = 'XXXX'
consumer_key_secret = 'XXXXX'
access_token = 'XXXXX'
access_token_secret = 'XXXXXX'
# authorization of consumer key and consumer secret
auth = tweepy.OAuthHandler(consumer_key, consumer_key_secret)
# set access to user's access key and access secret
auth.set_access_token(access_token, access_token_secret)
# calling the api
api = tweepy.API(auth)
# the screen name of the user
screen_name = ["m","b","c"]
ID = []
# fetching the user
for i in range(len(screen_name)):
user = api.get_user(screen_name[i])
#fetching the ID
ID.append(user.id_str)
del(user)
ID
i got this
['15454564','25645464','35456464']
HOW CAN I GET THE DATA FROM MULTIPLE IDS
To get data from multiple Tweet IDs, just create separate variables or arrays to store the data you want. And to pull data from Tweet IDs, just check the Tweepy documentation at https://docs.tweepy.org/en/v3.5.0/. Good luck, and let me know if you have any other questions.

get all retweets user-id for each tweet-id

I have a list of tweets Id more than 100 and I want to get all retweets Id for each tweet Id the code that I used is for one tweet Id how can I give the list of tweets Id and check if there is retweets for this tweet print the user ids
# import the module
import tweepy
# assign the values accordingly
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
# authorization of consumer key and consumer secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# set access to user's access key and access secret
auth.set_access_token(access_token, access_token_secret)
# calling the api
api = tweepy.API(auth)
# the ID of the tweet
ID = 1265889240300257280
# getting the retweeters
retweets_list = api.retweets(ID)
# printing the screen names of the retweeters
for retweet in retweets_list:
print(retweet.user.screen_name)
can anyone help me ?
For getting Retweets from a list of Tweets, you'll need to iterate over your list of Tweet IDs and call the api.retweets function for each one in turn.
If your Tweets themselves have more than 100 Retweets, you'll hit a limitation in the API.
Per the Tweepy documentation:
API.retweets(id[, count])
Returns up to 100 of the first retweets of the given tweet.
The Twitter API itself only supports retrieving up to 100 Retweets, see the API documentation (this is the same API that Tweepy is calling):
GET statuses/retweets/:id
Returns a collection of the 100 most recent retweets of the Tweet specified by the id parameter.
This works for me:
for retweet in retweets_list:
print (retweets_list.retweet_count)

Followers in twitter (tweepy)

I'm trying to download my followers of twitter and the followers of my followers. T
The code seems to work but it doesn´t download all my followers. It downloads a portion and in this portion I think it works well. But why not all?
why is it?
-- coding: utf-8 --
"""
#author: Mik
"""
import csv
import time
import tweepy
# Copy the api key, the api secret, the access token and the access token secret from the relevant page on your Twitter app
api_key = ''
api_secret = ''
access_token = '-'
access_token_secret = ''
# You don't need to make any changes below here # This bit authorises you to ask for information from Twitter
auth = tweepy.OAuthHandler(api_key, api_secret)
auth.set_access_token(access_token, access_token_secret)
# The api object gives you access to all of the http calls that Twitter accepts
api = tweepy.API(auth)
#User we want to use as initial node
user=''
#This creates a csv file and defines that each new entry will be in a new line
csvfile=open(user+'network2.csv', 'w')
spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
#This is the function that takes a node (user) and looks for all its followers #and print them into a CSV file... and look for the followers of each follower...
def fib(n,user,spamwriter):
if n>0:
#There is a limit to the traffic you can have with the API, so you need to wait
#a few seconds per call or after a few calls it will restrict your traffic
#for 15 minutes. This parameter can be tweeked
time.sleep(40)
#This is for private users that we wont be able to see their followers
try:
users=tweepy.Cursor(api.followers, screen_name = user, wait_on_rate_limit = True).items()
for follower in users:
spamwriter.writerow([user+';'+follower.screen_name])
fib(n-1,follower.screen_name,spamwriter)
#n defines the level of autorecurrence
except tweepy.TweepError:
print("Failed to run the command on that user, Skipping...")
n=2
fib(n,user,spamwriter)
If I understood correctly then you want to get ids of all followers of each of your followers.
Use logic like following, it will get you details of your 3000 followers per 15 minutes
import tweepy
#twitter credentials here---------------------------------------------------
auth = tweepy.OAuthHandler(your keys)
auth.set_access_token(your keys)
api = tweepy.API(auth)
iter1 = tweepy.Cursor(api.followers, screen_name = 'your_screen_name',count = 200).pages()
for request in range(15):
your_200_followers = next(iter1)
for each_follower in your_200_followers:
variable = each_follower.followers_ids
#store the <list> variable somewhere

How to extract screen_name from a tweet and use that to get all the past favorites of that user?

I want to search the tweets, extract the screen_name from the statuses and use that to get the past favorite tweets of that screen_name. Now I donot know how to extract the screen_names from statuses and then how to use to get past favorites. This is my code(the problem is with the last line):
import tweepy
consumer_key = ''
consumer_secret = ''
access_token = ''
access_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
search_results = tweepy.Cursor(api.search,q="Ganesh World").items()
for i in search_results:
print i.text.encode('utf-8')
print api.favorites([i.screen_name])
It is throwing AttributeError:Status object has no attribute 'screen_name'
No need to waste another API call,
You can fetch it from inner data elements, i.e. from author , and within that from its json like this:
for i in search_results:
print i.author._json['screen_name']
Try this:
for i in search_results:
print i.text.encode('utf-8')
user_details = api.get_user(user_id = i.from_user_id)
print api.favorites([user_details.screen_name])
You are trying to get screen_name directly from the tweet. First you should get id and then use it to get screen name.
you have to do:
i.user.screen_name

Categories