Make Your Own Twitter Bot using Python

Subscribe to my newsletter and never miss my upcoming articles

Twitter is an American microblogging and social networking service on which users post and interact with messages known as "tweets". In this article will see how to make your own Twitter bot using python.

This will be a Python built Twitter retweet bot using Tweepy. It can be used for automation and marketing purposes.

Here's my live Twitter bot (mlb0t) by the end of the article you will also have the same.

This Twitter bot can do many tasks by its own such as:

  • Retweets the tweets with particular #hastags.
  • Favourites/Likes the tweets with particular #hashtags.
  • Follows the users who tweet with particular #hashtags.
  • Can also DM the users if granted with permission.

Requirements

  • Install Tweepy using pip- An easy-to-use Python library for accessing the Twitter API.

    pip install tweepy

  • Make a Twitter Developer Account.
    1. Sign up for a separate account for your Twitter Bot and then apply for Twitter Developer Account.
    2. Enter the necessary details and wait for your mail confirmation. Once confirmed, click on Create an App option.
    3. Enter the necessary details to generate the secret key and access tokens.
    4. Copy the keys and keep them safe.
    5. Make sure you fully understand Twitter's Rules on Automation. Play nice. Don't spam!
  • And you also need to have a Heroku Account.

Development

  • Create a new directory to contain all of your retweet bot files.

    mkdir retweet-bot

  • Follow all the steps as shown in this Youtube Video

  • Create a new Twitter Application. This is where you'll generate your keys, tokens, and secrets.

  • Fill in your keys, tokens, and secrets in the credentials.py file.
  • Check comments in bot.py to tweak the retweet bot to your liking.
  • The example demonstrates a single hashtag value, but you can tweak the code to search for multiple hashtags. Example:

    q= #MachineLearning OR #ai

  • Run your bot.py file from your Command Prompt/Terminal with this command.

    python bot.py

  • If it runs without any errors on the terminal, now it can be deployed on Heroku.
  • Once the deployment is done you're good to go you! Sit back and relax have successfully created a Twitter bot.
  • Note: Make sure that your bot.py and credentials.py files are, obviously, in the same directory.

For deployment on Heroku

You need to make three different files

  • runtime.txt (Includes Python Version python-3.8.1)
  • requirements.txt (pip freeze > requirements.txt)
  • Procfile (worker: python bot.py)

You can find the whole code here: https://github.com/imanishbarnwal/twitter-bot

Additional Information

  • If you are stuck anywhere you can contact me via Twitter or LinkedIn I will be glad to help you.

No Comments Yet