How to build a twitter bot using Python
In this tutorial, we will learn how to create a twitter bot in python using the python library called Tweepy. For this, first you need to apply for developers account for twitter which I will talk about later in this tutorial. This bot mainly performs the following two functions:
- Automatically follows everyone who is following you
- replies to whoever tags you with a certain keyword
Setting up Twitter Developer Account
For this, first you need to login with your twitter account and then follow this link Twitter Developer account setup
and as soon you open this link, on top right corner you can see an apply button, click on that and follow everything that says there. As soon as you are done creating your account, next step is going to be creating your “Apps” which you can select as an option within twitter developers website. After that, click on create new app, fill in the information and then click on create and your app should be created.
Important :- After creating your app, hover over to “keys and token” section and generate “Consumer API keys” and “Access token and access token secret”. Copy all four of these and keep them handy as we are going to use later in the process i.e during coding.
Developing the Twitter Bot using Python
Very first step towards building the Bot is to install the Tweepy library in our system which can be done by writing
pip install tweepy
Now first we need to import tweepy in our code and that we can do by writing:
Now we will need consumer_key, consumer_secret, access_token and access token secret these are the keys that we generated while setting up our twitter developer account and we will put them up in code like:
consumer_key = 'enter your API key here' consumer_secret = 'enter your API secret key here' access_token = 'enter access_token here' access_token_secret = 'enter access_token_secret here'
Next step is creating OAuthHandler instance and into this we pass our consumer key and consumer secret. For example:
Authentication = tweepy.OAuthHandler(consumer_key, consumer_secret) Authentication.set_access_token(access_token, access_token_secret) api = tweepy.API(Authentication)
after doing this, now everything is set and this is more like a foundation for every twitter bot that you will make after this point. Now in order to make a bot that will follow everyone who follows you, we are gonna need a for loop that will iterate through a list of people that are following you and will follow them on it’s way and on your command line you will be able to see the name of the people who were followed by you using the bot, and the code for the same is:
for all_followers in tweepy.Cursor(api.followers).items(): all_followers.follow() print(all_followers.screen_name)
Code above pretty much explains itself, the way for loop works is it goes through all the people that you are following you and Cursor is tweepy object and you can also pass a value to .items(value) this will limit the amount of iteration over people and last line of the code is just to print the name of followers on console the code will work even if you don’t use the print statement as it is used only to print names on console and Complete code will look like:
import tweepy consumer_key = 'enter your API key here' consumer_secret = 'enter your API secret key here' access_token = 'enter access_token here' access_token_secret = 'enter access_token_secret here' Authentication = tweepy.OAuthHandler(consumer_key, consumer_secret) Authentication.set_access_token(access_token, access_token_Secret) api = tweepy.API(Authentication) for all_followers in tweepy.Cursor(api.followers).items(): all_followers.follow() print(all_followers.screen_name)
Now in order to make our bot reply to tweets with a certain hashtag we need to repeat the above processes until the for loop because this time we are going to do it differently. First as described above, import tweepy, set keys and do the api authentication after that we need to do this:
tweet = api.search("#name_your_hashtag", count = 1)
Above block of code just searches for the hashtag as the name (api.search) indicates, and you can set up the value of count yourself as it only indicates the amount of tweets that we are going to fetch, you can also provide @username in place of hashtag and then bot will reply as soon as that user is tagged. Next thing we have to do is write this block of code:
for tweet in tweets: try: screen_name = tweet.user.screen_name comment = ("@%s write anything here" %(screen_name)) tweet = api.update_status(comment,tweet.id) except tweepy.TweepError as Error: print(Error.reason)
What this block of code does is it iterates through the tweets which is hashtag or username in this case and then a try statement is used to check the code in try statement. Comment is what our bot will reply to the user @%s is necessary as it is required to convert argument to string during string formatting and writing %(screen_name) will help us to avoid printing @%s along with the string message. After this the api.update_status will update the status of the tweet and comment and tweet.id arguments are passed and as the name suggests, the comment argument will be used to tweet the message and tweet.id will help us to fetch the id of the tweet to avoid retweet. Finally in except statement we print the reason for error (if any).
Note :- Your command line will show error if you try to run the program over and over again over a single tweet, every tweet has a different id and to avoid spam by the bot we use the except statement, this will simply print the reason on your console.