In continuation with a series of tutorial on Twitter Automation, we will be discussing about how to retweet a particular tweet using Python. In the previous article here, we saw how to post tweet using Python. We saw how to use Tweepy package in Python to post tweets.
In this article, we will see, how to search Tweets based on certain keywords and retweet them.
Example : Let us say, you want to search Tweets based on the keyword “Hillary Clinton” and retweet them. We will see how to do it using Tweepy in Python.
Step 1 : First step is to obtain the Consumer Keys and Access Token key. If you dont know how to obtain this, please refer here.
Step 2 : Import Tweepy and
In this example, I assume that Tweepy is already installed. If not, you can install Tweepy using the command:
1
|
pip install tweepy
|
Step 3 : First we need to login using the Consumer keys and Access token keys. You can login and obtain the API using the following code.
1
2
3
4
5
6
7
8
9
10
11
12
|
import tweepy
def login_to_twitter(consumer_key, consumer_secret, access_token, access_token_secret):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
ret = {}
ret['api'] = api
ret['auth'] = auth
return api
|
Step 4 : Now, we need to search for all those tweets having the keyword “Hillary Clinton”. You can do using Tweepy as follows :
1
2
3
4
5
|
query = "Hillary Clinton"
tweet_cursor = tweepy.Cursor(api.search, query, result_type="recent", include_entities=True, lang="en").items()
for tweet in tweet_cursor:
tweet_id = tweet.id_str #Id of the Tweet
|
Based on the search key, you will get multiple tweets matching the keywords. Each of the tweet is identified by the Tweet ID.
Step 5 : Once we know the id of each Tweet which has the keyword “Hillary Clinton”. You can retweet using the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# ######## Retweet A Tweet ###################################
def retweet(api, tweet_id):
success = False
try:
a= api.retweet(tweet_id)
# Sleep for 2 seconds, Thanks Twitter
print("Sleeping for 5 seconds")
time.sleep(5)
success = True
except tweepy.TweepError as e:
a=e.response.text
b=json.loads(a)
error_code = b['errors'][0]['code']
if(error_code == 327):
success = True
return success
|
I hope, you find this article very useful. If you have any doubts or have any comments concerning this tutorial, Please leave a comment or contact me. I would be glad to help.