Tweepy check if user A is following user B? - python

I have this code (not all of the code) and it basically gets the 20 most recent followers. The problem is that it will make a follow request to people who I am already following. This wouldn't be a problem but twitter limits how many requests you can make.
followers = api.followers()
following = api.friends()
tofollow = [x for x in followers if x not in following]
for u in tofollow:
try:
u.follow()
number_followed+=1
print number_followed,". ", u.screen_name
except tweepy.TweepError as err:
print "Error: when following ", u.screen_name
i think it has something to do with when i make tofollow
any thoughts?

I think that if you want to make twitter queries for the whole set and not for 20 most recent, you should use a cursor.
For example:
tweepy.Cursor(api.followers).items()
Also if you don't want to violate the twitter rate limiting you could use the following line when initializing the api object:
api = tweepy.API(auth, wait_on_rate_limit=True)
Hope it helps. Here is an example:
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)
friends = api.friends_ids(api.me().id)
print("You follow", len(friends), "users")
for follower in tweepy.Cursor(api.followers).items():
if follower.id != api.me().id:
if follower.id in friends:
print("You already follow", follower.screen_name)
else:
follower.follow()
print("Started following", follower.screen_name)

Related

Using Tweepy and Python, how do I unfollow all the accounts that don't follow me back starting with the oldest ones first?

A little help please. This is what I am working with now (I got it from here on stackoverflow) and it works very well, but it seems to only work with the most recent accounts in the list of accounts that don't follow me back. I want to start unfollowing accounts from the oldest to the newest because I keep reaching the limit of the API. I thought to make a list of followers and reverse it then plug that in somewhere but not quite sure how to do that or what the syntax would be. Thanks in advance.
import tweepy
from cred import *
from config import QUERY, UNFOLLOW, FOLLOW, LIKE, RETWEET
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
def main():
try:
if UNFOLLOW:
my_screen_name = api.get_user(screen_name='YOUR_SCREEN_NAME')
for follower in my_screen_name.friends():
Status = api.get_friendship(source_id = my_screen_name.id , source_screen_name = my_screen_name.screen_name, target_id = follower.id, target_screen_name = follower.screen_name)
if Status [0].followed_by:
print('{} he is following You'.format(follower.screen_name))
else:
print('{} he is not following You'.format(follower.screen_name))
api.destroy_friendship(screen_name = follower.screen_name)
except tweepy.errors.TweepyException as e:
print(e)
while True:
main()
here is the config.py file
#config.py
UNFOLLOW = True
I recently assembled some pieces of code together to reach this, so I'll just copy paste what I already have here instead of updating your code, but I can point out the main points (and give some tips).
The full code:
import tweepy
from cred import *
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
def unfollower():
followers = api.get_follower_ids(screen_name=api.verify_credentials().screen_name)
friends = api.get_friend_ids(screen_name=api.verify_credentials().screen_name)
print("You follow:", len(friends))
for friend in friends[::-1]:
if friend not in followers:
api.destroy_friendship(user_id = friend)
else:
pass
friends = api.friends_ids(screen_name=api.me().screen_name)
print("Now you're following:", len(friends))
unfollower()
Now what happened here and what is different from your code
This two variables:
followers = api.followers_ids(screen_name=api.verify_credentials().screen_name)
friends = api.friends_ids(screen_name=api.verify_credentials().screen_name)
create a list with the ids from both the followers (follow you) and the friends (you are following), now all we need to do is compare both.
There is a discussion about the Twitter Rate limit and how using cursors have a smaller rate than not using, but I'm not qualified to explain the whys, so let's just assume that if we do not want small rate limits, the best way is not to use requests that have a intrinsic small rate limit like the api.get_friendship and them getting the screen_name, instead I'm using the get_friend_ids method.
the next part involves what you called "make a list of followers and reverse", well the list is already there in the variable "followers", so all we need to do now is reverse read it with the following command:
for friend in friends[::-1]:
this says: "read each element of the list, starting from index -1" roughtly "read the list backwards".
Well, I think the major points are these, I created a function but you really don't even need to, is just easier to update this to a class if you need to, and this way you don't need to use the while True: main(), just call the function unfollow() and it will automatically end the script when the unfollows are over.
Now some minor points that might improve your code:
Instead of using
screen_name='YOUR_SCREEN_NAME'
That you need a config file or to hardcode the screen_name, you can use
screen_name=api.verify_credentials().screen_name
This way it will automatically knows that you want the authenticating user information (note that I didn't used this part on my code, for the get_friend_ids method does not need the screen_name)
Now this part
from cred import *
from config import QUERY, UNFOLLOW, FOLLOW, LIKE, RETWEET
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
First I've eliminated the need for the config file
and you can eliminate all the extra info that comes imported from the cred file, so you don't need to import all in from cred import * updating cred.py with:
import tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
and now you can only impor the api function with from cred import api, this way the code can become cleaner:
import tweepy
from cred import api
def unfollower():
followers = api.get_follower_ids(screen_name=api.verify_credentials().screen_name)
friends = api.get_friend_ids(screen_name=api.verify_credentials().screen_name)
print("You follow:", len(friends))
for friend in friends[::-1]:
if friend not in followers:
api.destroy_friendship(user_id = friend)
else:
pass
friends = api.get_friend_ids(screen_name=api.verify_credentials().screen_name)
print("Now you're following:", len(friends))
unfollower()
Lastly, if anyone is having problems with the api.get_friend_ids or get_follower_ids remember that the tweepy update for versions 4.x.x changed the name of some methods, the ones I remember are:
followers_ids is now get_follower_ids
friends_ids is now get_friend_ids
me() is now verify_credentials()
Well, I guest that's it, you can check the rest on the docs.
Happy pythoning!

How can I get a large list of followers from a Twitter user and then follow them?

How can I get a list of followers from a Twitter account with a lot of followers? My code is meant to get followers from a user and then follow them but max I can get and follow is 200 with my code and then after 200 it gets new users but way slower. Is there a way to get thousands more?
import tweepy
from time import sleep
consumer_key = ''
consumer_secret = ''
access_key = ''
access_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
users = tweepy.Cursor(api.followers, screen_name='twitter', count=200).items()
count = 0
while True:
try:
user = next(users)
api.create_friendship(user.screen_name)
sleep(1)
print(user.screen_name)
except tweepy.TweepError as e:
if e.api_code == 161:
while(count < 901):
print(count, end='\r')
sleep(1)
count +=1
if e.api_code == 160:
pass
except StopIteration:
pass
Twitter documentation says there is a limit of 200 to the count parameter of the api. I would guess that is causing you your trouble.
The number of users to return per page, up to a maximum of 200. Defaults to 20.
Check your Twitter rate limits.
Servers normally have a limit on the number of calls you can make to them before they begin to restrict access. The reason for this is that if they let every server ping them 1000+ times a minute, the cost of their servers will be higher and it will make it harder to spot a DNS attack (aggressive servers have a high limit of calls they can make while still looking like non-aggressive servers).

count parameter is ignored when querying user_timeline in tweepy

I'm trying to use the tweepy library in one of my python projects. When I try the following code that creates a tweepy cursor to fetch a user's timeline status messages, the count parameter is always ignored.
def search(self, username, keyword, consumer_key, consumer_secret, access_token, access_token_secret):
#start twitter auth
try:
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
user = api.get_user(username)
except Exception as e:
print(str(e))
self.error = str(e)
return
self.followercount = user.followers_count
self.screenname = user.screen_name
results = []
for status in tweepy.Cursor(api.user_timeline, id=username, count=2).items():
try:
tweet = status._json
In this instance, the count is set to 2 in the Cursor object, yet it receives all of them. What am I doing wrong?
tweepy.Cursor() does not appear to recognize a count argument. In fact, count is not mentioned anywhere in tweepy/cursor.py, the module where tweepy.Cursor is defined. Instead, it looks like you might want to use:
for status in tweepy.Cursor(api.user_timeline, id=username).items(2):
passing the limit to items() instead of as the count keyword argument. See this section in the tweepy Cursor tutorial.

Return a users tweets with tweepy

I am using tweepy and python 2.7.6 to return the tweets of a specified user
My code looks like:
import tweepy
ckey = 'myckey'
csecret = 'mycsecret'
atoken = 'myatoken'
asecret = 'myasecret'
auth = tweepy.OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
api = tweepy.API(auth)
stuff = api.user_timeline(screen_name = 'danieltosh', count = 100, include_rts = True)
print stuff
However this yields a set of messages which look like<tweepy.models.Status object at 0x7ff2ca3c1050>
Is it possible to print out useful information from these objects? where can I find all of their attributes?
Unfortunately, Status model is not really well documented in the tweepy docs.
user_timeline() method returns a list of Status object instances. You can explore the available properties and methods using dir(), or look at the actual implementation.
For example, from the source code you can see that there are author, user and other attributes:
for status in stuff:
print status.author, status.user
Or, you can print out the _json attribute value which contains the actual response of an API call:
for status in stuff:
print status._json
import tweepy
import tkinter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
# set parser=tweepy.parsers.JSONParser() if you want a nice printed json response.
userID = "userid"
user = api.get_user(userID)
tweets = api.user_timeline(screen_name=userID,
# 200 is the maximum allowed count
count=200,
include_rts = False,
# Necessary to keep full_text
# otherwise only the first 140 words are extracted
tweet_mode = 'extended'
)
for info in tweets[:3]:
print("ID: {}".format(info.id))
print(info.created_at)
print(info.full_text)
print("\n")
Credit to https://fairyonice.github.io/extract-someones-tweet-using-tweepy.html
In Tweeter API v2 getting tweets of a specified user is fairly easy, provided that you won’t exceed the limit of 3200 tweets. See documentation for more info.
import tweepy
# create client object
tweepy.Client(
bearer_token=TWITTER_BEARER_TOKEN,
consumer_key=TWITTER_API_KEY,
consumer_secret=TWITTER_API_KEY_SECRET,
access_token=TWITTER_ACCESS_TOKEN,
access_token_secret=TWITTER_TOKEN_SECRET,
)
# retrieve first n=`max_results` tweets
tweets = client.get_users_tweets(id=user_id, **kwargs)
# retrieve using pagination until no tweets left
while True:
if not tweets.data:
break
tweets_list.extend(tweets.data)
if not tweets.meta.get('next_token'):
break
tweets = client.get_users_tweets(
id=user_id,
pagination_token=tweets.meta['next_token'],
**kwargs,
)
The tweets_list is going to be a list of tweepy.tweet.Tweet objects.

Python save state in a for loop for a twitter bot

I'm writing a twitter bot using tweepy that will search for mentions to it and then implement actions based on the text in the tweet. Eventually I want to run it every few minutes via cron. I'm a python beginner, so forgive my ignorance.
My problem is preventing duplicates. I have a loop that goes through and tests whether a tweet is new by checking whether its id is greater than the previous tweet. However, I can't work out a way of initializing this variable, and then saving changes to it at the end of the loop.
Here is my current (broken) code:
import sys
import tweepy
## OAuth keys go here.
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
def ask_bot():
old_id = 0
for tweet in api.mentions():
if tweet.id > old_id:
print "#%s: %s" % (tweet.author.screen_name, tweet.text)
old_id = tweet.id + 1
else:
pass
The desired behaviour at the end is for the loop to only print tweets that haven't been printed before.
I don't know much about Tweepy, but this may help:
import sys
import tweepy
## OAuth keys go here.
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
seen_ids = []
def ask_bot():
global seen_ids
for tweet in api.mentions():
if tweet.id not in seen_ids:## Heading ##:
print "#%s: %s" % (tweet.author.screen_name, tweet.text)
seen_ids.append(tweet)
else:
pass
So, it will search through Twitter for all tweets aimed at it, then it will check if it has seen that ID before. The reason I used global is so changes would affect the main variable seen_ids, not a copy made inside of the function.
Good Luck!
I would just make a list of IDs that have been printed. Then you would simply check if the ID you're trying to print is already in the printed list. If it is, do nothing. If it isn't, print it and add it to the list.
In other words:
import sys
import tweepy
## OAuth keys go here.
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
printed_ids = []
def ask_bot():
old_id = 0
for tweet in api.mentions():
if tweet.id not in printed_ids:
print "#%s: %s" % (tweet.author.screen_name, tweet.text)
printed_ids.append(tweet.id)
else:
pass

Categories

Resources