DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


How to make a Twitter Bot using Python and Tweepy

  • 6 minutes read
  • 1077 Views
How to make a Twitter Bot using Python and Tweepy

    Table of Contents

How to make a Twitter Bot using Python and Tweepy

If you are new to python and looking for some fun python project , a twitter bot is a must try. So in this tutorial we will make a twitter bot using python and tweepy .

What is a Twitter Bot

A twitter bot is a program which automatically does the following using the twitter api :

  • Sends a twitter update.
  • Retweet some tweets.
  • Favorite/like some tweets.
  • Follow/followback people on twitter and many more.

A twitter bot can be as simple as one sending a tweet at random interval or as complex as one which uses AI and Machine learning for interacting with people.

What Twitter Bot will we be creating?

We will make a Twitter Bot using Python which will work as under:-

  1. If a user mentions you in a tweet and sends a picture (with atleast one person) to you.
  2. Our Twitter Bot will remove the background of the image.
  3. And automatically send back the image without the background to the original user.

What will we need?

  1. A twitter account
  2. Tweepy api module
  3. requests module
  4. An account on remove.bg and it’s api
  5. Pillow (Python Image Library)

Setting up your twitter account/tweepy api

I hope that all of you already have a twitter account. If not, click here to create one. Once you are done creating the account open developer’s page and click on ‘Apps’ —> ‘Create an app’

Create a Twitter Bot using Python and tweepy -1.png

Create a Twitter Bot using Python and Tweepy - 2.png

In the next screen fill the following:-

  1. App name : bg_remove_demo (You can use any)
  2. Application Description: Write the one which we have written above.
  3. Website URL : https://placeholder.com will do.
  4. Tell us how this app will be used : Write down the description again

and hit ‘Create’. Hit ‘Create’ again and then click on Keys and tokens.

Create a Twitter Bot using Python and tweepy -3.png

Create a Twitter Bot using Python and tweepy -4.png

In the next screen you will get the Consumer API Keys i.e. API Key and API Secret Key. Now, create Access token and Access token secret. In permission tab check that ‘Access Permission’ is for “read and write”

Create a Twitter Bot using Python and tweepy -5.png

Let’s get into the coding part:-

$ cd desktop
$ mkdir remove_bg_demo && cd remove_bg_demo

Now create and activate the virtual environment using the following command:-

$ virtualenv . 
$ source bin/activate

Install the necessary modules

$ pip install tweepy
$ pip install python-decouple

Now, we will be saving our credentials in a ‘.env’ file and using python-decouple to access that in our code. So create a new file. Or alternatively, you can use Environmental variable to save your secret keys .

$ nano .env

And in the .env file add your credentials

CONSUMER_KEY=YOURKEYGOESHERE
CONSUMER_SECRET=YOURSECRETGOESHERE
ACCESS_TOKEN=YOURACCESSTOKENGOESHERE
ACCESS_SECRET=ACCESSSECRETGOESHERE

You don’t need to add quotes or space.

Create a python file ‘bot.py’ and start coding

import tweepy
from decouple import config

All the requests will use Oauth for authentication. And after authentication we will construct an API instance

# authentication

auth = tweepy.OAuthHandler(config("CONSUMER_KEY"), config("CONSUMER_SECRET"))
auth.set_access_token(config("ACCESS_TOKEN"), config("ACCESS_SECRET"))

# API instance

api = tweepy.API(auth)

You can check the functionality by sending a test tweet

api.update_status("This is a test tweet using tweepy.")

Setting up remove.bg API

If everything goes well, we can jump to the next step. Head to remove.bg, sign up and sign in. Then click on API and scroll to down. Click on ‘Show’, copy the API key and paste it into .env file.

BG_API_KEY=YOURAPIKEY

Create a Twitter Bot using Python and tweepy -6.png

You must note that, the free account only provides 50 API calls per month. So use them wisely.

Finalizing the Bot

First of all, we will be creating a stream listener, which is a class inheriting tweepy.StreamListener class and we will be overriding it’s inbuilt on_status function and modifying it in such a way that it will fetch the screen name and id of the tweet. Then, Each tweet on a twitter has certain entities which hold URLs, media, hashtag etc. So, we will check whether the tweet sent contains any media i.e. image

class MyStreamListener(tweepy.StreamListener):

    def on_status(self, status):
        username = status.user.screen_name
        status_id = status.id

        if ‘media’ in status.entities:
            for image in status.entities['media']:
                tweet_image(image['media_url'], username, status_id)

Now, we create a stream and start it

my_stream_listener = MyStreamListener()
stream = tweepy.Stream(auth, my_stream_listener)
stream.filter(track=['@saral_gyaan'])

I will quickly go through the code above. So, when we will run our python script, it will start a Stream Listener which will look for tweets which contain ‘@saral_gyaan’ in it (this we have set up in the filter). Then comes on_status method, if there is any tweet mentioning saral_gyaan, it will grab the screen name of the user and the status id. Then it will check whether, that status/tweet has any media, and if it has a media, it will run a function called ‘tweet_image()’. No we will create the ‘tweet_image()’function

import requests
from io import BytesIO
from PIL import Image

def tweet_image(url, username, status_id):
    filename = 'temp.png'
    response = requests.get(url, stream=True)
    if response.status_code == 200:
        i = Image.open(BytesIO(request.content))
        i.save(filename)
        remove_bg(filename)
        api.update_with_media('no-bg.png', status=f'@{username}, Here is the picture without the background', in_reply_to_status_id=status_id)
    else:
        print("unable to download image")

It will check for the response from the stream, and if there is a response, it will open the image, save it as ‘temp.png’ and then run the function remove_bg() on it and finally update the twitter status mentioning the original user and containing the image without the background.

Finally, we will create the remove_bg() function, which will take the image attribute

def remove_bg(filename):
    response = requests.post(
    'https://api.remove.bg/v1.0/removebg',
    files={'image_file': open(filename, 'rb')},
    data={'size': 'auto'},
    headers={'X-Api-Key': config('BG_API_KEY')},)
    if response.status_code == requests.codes.ok:
        with open('no-bg.png', 'wb') as out:
            out.write(response.content)
    else:
        print("Error:", response.status_code, response.text)

This is a code which has been provided at remove.bg, it looks for the response, and if the reponse is “OK”, it removes the background and create “no-bg.png”, the same is tweeted out by tweet_image() function.

Now, run the script on your local machine and try it by tweeting the image.

$ python bot.py

And Voila, your bot is ready and running!

Check this tweet to see how it worked in the past.

Check out the complete code here


Related Posts

Create your Own Customizable Email Spam Filter using Python
By Udit Vashisht

Use Python and Gmail API to create your own Customizable Email Spam Filter

There was a time when you will run to the mailbox outside your home at a fixed time to check your mail and segregate the crap out of it. But today, we all live in a digital ...

Read More
Convert JSON to CSV using Python
By Udit Vashisht

JSON to CSV in Python

In this tutorial, we will convert multiple nested JSON files to CSV firstly using Python’s inbuilt modules called json and csv using the following steps and then using Python Pandas:-

  1. First of all we will read-in the JSON ...

    Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python