I don't know how to use Tweepy; can you tell me? - python

I install Tweepy and Python-Twitter and try code, and I tried to run.
If I try this code:
import tweepy
import time
#insert your Twitter keys here
consumer_key ='xxx'
consumer_secret='xxx'
access_token='xxx'
access_token_secret='xxx'
twitter_handle='handle'
auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
list= open('twitter_followers.txt','w')
if(api.verify_credentials):
print ('We successfully logged in')
user = tweepy.Cursor(api.followers, screen_name=twitter_handle).items()
while True:
try:
u = next(user)
list.write(u.screen_name +' \n')
except:
time.sleep(15*60)
print ('We got a timeout ... Sleeping for 15 minutes')
u = next(user)
list.write(u.screen_name +' \n')
list.close()
I get this error when I do:
File "C:\Users\xxx.py", line 19, in <module>
user = tweepy.Cursor(api.followers, screen_name=twitter_handle).items()
AttributeError: 'API' object has no attribute 'followers'
Are there any errors that have not been progressed yet?

Tweepy v4.0.0 renamed API.followers to API.get_followers.
Also, you're not calling API.verify_credentials and instead only checking if the method exists, so that if statement expression will always evaluate to True and print.

Related

Tweepy error when trying to gather Tweets

I'm trying to get Tweets using the Tweepy module in Python. However, whenever I try to collect Tweets using the tweepy.Cursor function, it returns the error:
TweepyException Traceback (most recent call last)
<ipython-input-5-a26c992842dc> in <module>
----> 1 tweets_list = tweepy.Cursor(api.search_tweets(q="oranges", tweet_mode='extended', lang='en')).items()
~\anaconda3\lib\site-packages\tweepy\cursor.py in __init__(self, method, *args, **kwargs)
38 raise TweepyException('Invalid pagination mode.')
39 else:
---> 40 raise TweepyException('This method does not perform pagination')
41
42 def pages(self, limit=inf):
TweepyException: This method does not perform pagination
I do not know why this is. I can still post Tweets using the api.update_status() function. Please help. Here is my code. As you can see, the setup is correct; it is only this function that is returning the error.
from config import *
import tweepy
import datetime
consumer_key= 'CONSUMER KEY HERE'
consumer_secret= 'CONSUMER KEY SECRET HERE'
access_token= 'ACCESS TOKEN HERE'
access_token_secret= 'ACCESS TOKEN SECRET HERE'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
try:
api.verify_credentials()
print("Authentication Successful")
except:
print("Authentication Error")
tweets_list = tweepy.Cursor(api.search_tweets(q="oranges", tweet_mode='extended', lang='en')).items()
If there is an error in the function or the code itself, can you please write a correct version? I'm trying to gather Tweet data for a project.
You're passing the result of the call to / invocation of API.search_tweets, rather than the method itself, to Cursor.
See Tweepy's Pagination documentation for an example of how to use Cursor.

Why does my twitter bot post more than expected?

I am using the code time.sleep(3600) and it is tweeting more than every 3600 seconds. Why is this happening?
Currently it is tweeting at 9 minutes past, then 32 minutes past.
Edit:
Here is the code. The only other reason this could be happening is that this may be running in multiple instances accidentally. I will check that.
# tweepy will allow us to communicate with Twitter, time will allow us to set how often we tweet
import tweepy, time
#enter the corresponding information from your Twitter application management:
CONSUMER_KEY = 'mykey' #keep the quotes, replace this with your consumer key
CONSUMER_SECRET = 'mykey' #keep the quotes, replace this with your consumer secret key
ACCESS_TOKEN = 'my-my' #keep the quotes, replace this with your access token
ACCESS_SECRET = 'mykey' #keep the quotes, replace this with your access token secret
# configure our access information for reaching Twitter
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
# access Twitter!
api = tweepy.API(auth)
# open our content file and read each line
filename=open('content.txt')
f=filename.readlines()
filename.close()
# for each line in our contents file, lets tweet that line out except when we hit a error
for line in f:
try:
api.update_status(line)
print("Tweeting!")
except tweepy.TweepError as err:
print(err)
time.sleep(3600) #Tweet every hour
print("All done tweeting!")
This may be caused by your module not being protected from running when imported.
That means every time your module is imported, (could happen on
from package import *
), your code is interpreted and a new loop is created.
You could ensure your code is run only when you want it to run with this :
Make a function from your code, let's name it main().
You can then check if your module is called as a script.
def main():
# tweepy will allow us to communicate with Twitter, time will allow us to set how often we tweet
import tweepy, time
#enter the corresponding information from your Twitter application management:
CONSUMER_KEY = 'mykey' #keep the quotes, replace this with your consumer key
CONSUMER_SECRET = 'mykey' #keep the quotes, replace this with your consumer secret key
ACCESS_TOKEN = 'my-my' #keep the quotes, replace this with your access token
ACCESS_SECRET = 'mykey' #keep the quotes, replace this with your access token secret
# configure our access information for reaching Twitter
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
# access Twitter!
api = tweepy.API(auth)
# open our content file and read each line
filename=open('content.txt')
f=filename.readlines()
filename.close()
# for each line in our contents file, lets tweet that line out except when we hit a error
for line in f:
try:
api.update_status(line)
print("Tweeting!")
except tweepy.TweepError as err:
print(err)
time.sleep(3600) #Tweet every hour
print("All done tweeting!")
if __name__ == "__main__":
main()
If you have to use your code from another script, you can use
from your_module import main
main()
Or from a command line :
python -m your_module

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.

Tweepy check if user A is following user B?

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)

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