Reputation: 21
I'm trying to create a Twitter bot using tweepy that will search, like and retweet any status update containing the words "Retweet to enter", and I was successful. However, I would also like the script to follow the person that created the composition (I'm creating this script to try and win contests, and you often need to follow the account that is hosting the contest as well).
My script is pasted below. Currently, the script will indeed follow someone, but it is not the person who created the tweet.
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
user2 = api.me()
print(user2.name)
def main():
search = ("Retweet to enter")
numberoftweets = 5
for tweet in tweepy.Cursor(api.search, search).items(numberoftweets):
try:
tweet.favorite()
tweet.retweet()
api.create_friendship(tweet.user.id)
print("Tweet Retweeted and followed")
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
main()
Upvotes: 1
Views: 3209
Reputation: 575
The comments from Alan on the question are indeed correct, api.search
returns retweets as well as original tweets. At the moment, for retweets, your code will follow the retweeting account. Here are a couple of ways you can handle this:
Filter out retweets
While you could get all tweets and then filter the results, you'd be wasting valuable API calls. It would be better to filter at the API request. You can do this through Twitter's standard operators. Adding the following to your search string will remove all retweets
-filter:retweets
So your search would be
search = "Retweet to enter -filter:retweets"
Get the original tweet author
Maybe you don't want to filter out retweets. The responses Twitter returns will still allow you to obtain the original author from a retweet. You have to check that whether the tweet is a retweet, and if it is it shall have the retweeted_status
property. This contains info about the original tweet, including its author.
if tweet.retweeted:
api.create_friendship(tweet.retweeted_status.author)
Adding the above to your code should allow you to follow the original author.
Personally, I'd prefer the filtering option, but it's up to you. Hope one of these helps.
Upvotes: 1