How to make a Twitter Bot with Python
Do you use Twitter? Have you come across a twitter bot that like, retweet, follow, or even reply to your tweets?
Do you want to know how to build one?
Log in to your Twitter account on which you want to make a bot.
Apply for a Developer Account
To apply for the developer account, follow these steps:
Google twitter developer account and it will redirect you this website. Once you click apply on the top right corner, you can proceed further.
I’m using my new account pymoonBot to make a bot, which will like, and retweet the hashtag #python3.
Select, apply for a developer account.
Post selection, you will get a number of options, it will ask you to choose why you want to apply for the developer account.
Here we are making a bot, so you can select Making a bot.
Now, on the next page, you need to fill some details.
Twitter will ask you to fill out some questions related to how you would use this account and the twitter data.
Enter all the necessary details about what you’d do with this bot.
After filling all the necessary details, you’ll get an agreement page. Accept all the terms and conditions.
And then click on Submit application.
Next, You will be asked to confirm mail. Post confirmation, a new window will open like this.
Enter the name and click Get keys.
Good, Now we have the keys. Save them somewhere safe, we’ll need them soon.
Time to Code!
You can find my code at https://github.com/ayushi7rawat/Twitter-Bot
Now, let's understand it.
In order to communicate with the Twitter API, we need some module, here we are using Tweepy.
To install Tweepy you can refer this https://github.com/tweepy/tweepy/issues/1063. You can also refer to the Tweepy (http://docs.tweepy.org/en/latest/index.html) documentation.
once you install the module,
#Set up connection
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
This is used to authenticate your Twitter account.
Here we will require the keys.
auth variable is created to authenticate the account, Twitter uses OAuth to do this.
Next, we can set the tokens.
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
This class provides a wrapper for the API as provided by Twitter.
This program will look for the keyword #python3 in a tweet and will limit the number of tweets to be processed in a day. To like a tweet, you can use tweepy.favorite() , and for retweet tweepy.retweet().
You can play around and experiment with your bot but remember Twitter has some guidelines that you must follow otherwise, your account will get restricted.
Finally, it’s time for the deployment. You can use any platform of your choice for this, I have used Render.
Here’s my bot.
You can find my code at https://github.com/ayushi7rawat/Twitter-Bot.
Now you can build your own bot.