Create Twitter Bot with Python Tweepy Library in 5minutes

Create Twitter Bot with Python Tweepy Library in 5minutes

Social media is one of the biggest tools for growing digital presence and engagement. If you google any list for top ten most visited websites in a specific location, 80% of that list will include social media pages like Facebook, Instagram and Twitter. In this tutorial we are going to cover everything you need to know to create twitter bot with python.

Disclaimer: All methods and code presented in this tutorial are within twitter’s official API and allowed methods, however the limits of how much you can do can be restricted and lead to your account being blocked by twitter if you exceed these limits. Use this code with special care and restraint, especially avoiding spamming and abusing the platform. This code is provided as is and you use it at your own risk.

Steps to Create Twitter Bot Python Tweepy

  • Set up Python development environment
  • Obtain twitter API credentials and developer account
  • Hello world tweepy code – send first tweet
  • Hello world tweepy code – send first image
  • Check for account limits [*very important*]
  • List trends
  • Read twitter timeline
  • Interact with other users
Create Twitter Bot Python Tweepy
Create Twitter Bot Python Tweepy

Set up Python development environment

We will be working from a Virtual Private Server (VPS) – linux server. You can get one easily from digital ocean for $5 about R80. Use this referral link to get a discount: Get Digital Ocean Droplet. When you buy a droplet, you get the option to chose the Operating System of your virtual machine – you need to choose Ubuntu 20.04, which will come pre-installed with Python3.

You will need a cloud server to host your code at the end so that it runs automatically as specified times.

Check out our tutorial for setting up Digital Ocean Droplet

Install Python and Virtual Environment

Start by updating packages:

sudo apt update
sudo apt -y upgrade

If you are on Ubuntu 20.o4 – Python will come pre-installed on the system. You should pick ubuntu 20.04 when buying the droplet from Digital Ocean. Running this code will output the version of python installed.

python3 -V

Now you need to install pip – the package manage for Python.

sudo apt install -y python3-pip

Install development tools

sudo apt install -y build-essential libssl-dev libffi-dev python3-dev

Install Virtual Environment

sudo apt install -y python3-venv

You are now good to go, we can now set up a folder and create an environment to work from.

mkdir twitter && cd twitter
python3 -m venv twitterenv

If this gives you issues you can do:

pip3 install virtualenv

virtualenv twitterenv

Once the Virtual Env is installed – you can run the following code to activate. You need to activate the env from the folder where you created it, every time you want to run python code.

source twitterenv/bin/activate

You will now see (twitterenv) at the beginning of the command line prompt. You can now use pip install to install tweepy and any other python library you need:

pip install tweepy

When you were outside the env, you used pip3 install, to talk to python 3, but inside the venv you can just say pip install – the env was created with Python3 and will be using pip3 by default.

Create two files to work with, one config.py file and another tweet.py file. We will write all our code in the tweet.py and the keys and secrets in the config file. The file structure should now look like:

twitter
|
|_______ twitterenv
|_______ config.py
|_______ tweet.py

Your development environment is completed and ready to go.

Obtain twitter API credentials and developer account to create twitter bot Python

You need a twitter developer account and app to work with, go to the URL: https://dev.twitter.com/apps/new/

You can type it directly in to the url, then click on create new app:

Create Twitter App Credentials
Create Twitter App Credentials

This will then take you through the process to create an app, you will have to give a full explanation to twitter about: (1) Why you need the API credentials and (2) What you will be using the app for.

Declare Twitter App Use Intentions
Declare Twitter App Use Intentions

Enter the details and complete the process. You will receive an email with a verification button you need to click the button to verify your email. You will then be able to create a new app, what you need to get from twitter is:

  • API Secret
  • API Key
  • Access Token
  • Access Token Secret

Hello World Twitter Bot – Send a tweet

Inside the config.py file:

#Twitter API Credentials
api_key = "twitter-api-key"
api_secret = "twitter-api-secret"

access_token = "app-access-token"
access_token_secret = "app-access-token-secret"

You can send a tweet with just a few lines of code using python tweepy

import tweepy
import config

auth = tweepy.OAuthHandler(config.api_key, config.api_secret)
auth.set_access_token(config.access_token, config.access_token_secret)

api = tweepy.API(auth, 
                 wait_on_rate_limit=True, 
                 wait_on_rate_limit_notify=True)

status = "our very first status from python and tweepy :)"
api.update_status(status)

Note:

You tweet needs to be less than 160 characters or there will be an error thrown, so we are going to add code to ensure our tweets are within the required characters.

You can add hashtags and start using the power of python to create unique, useful tweets for your account. Let us look at a revised code:

import tweepy
import config
import random 

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

hashtags = ["#hashtag1", "#hashtag2", "#hashtag3", "#hashtag4", "#hashtag5", 
            "#hashtag6", "#hashtag7", "#hashtag8", "#hashtag9", "#hashtag10",
           ]

messages = [
"Sending tweets from tweepy",
"Follow us to get latest job info",
"Any day is inspiration day - Zatosh Nakamoto",
"Never give up, your life starts now",
"Always believe in yourself",
"Life is not short, it is way too log",
"We live in amazing times",
"Remember to sanitise, everyday"
]

def updateStatus():
    msg = random.choice(messages)
    tags = random.sample(hashtags, 2)
    for tag in tags:
        msg += ' '+tag

    if len(msg) < 160:
        api.update_status(msg)
    

updateStatus()

We are doing a lot of things here, but they will all be useful in allowing us to automate this script. We have multiple string options called messages. These will be the possible tweets that you will send out. We then use the python random library – to choose a random message to send out. Each time you run this code, a different random message will be sent out.

If you keep your list long enough, you will be able to send out a different string every time.

We have a list of hashtags – where we are selecting 2 random hashtags.

We them check the length of the tweet before sending out, and we are done

Send an image with your tweet

Sending a tweet with an image is just as simple, you need to know the absolute path to where the image is saved on your device.

image = 'path-where-image-is-saved/image.jpg'

def updateImage(image):
    msg = random.choice(messages)

    if len(msg) < 160:
        api.update_with_media(filename=image, status=msg)
    
updateImage(image)

Everything else remains the same except for adding the file-path for the image and the new function. Note you can also include text with you image, hashtags etc.

Check for Account Limits

This is a very important step, you need to know the limits of what you are allowed to do. Generally tweeting every couple of hours should not get you in to trouble, but once you start using the API to its limits, by following people, checking trends etc – you will need to be aware of the limits.

For that you need to run the code:

import config
import tweepy


auth = tweepy.OAuthHandler(config.api_key, config.api_secret)
auth.set_access_token(config.access_token, config.access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

limits = api.rate_limit_status()
print(limits)

Your limits are returned as a JSON object, you can print out on your command line or save as a JSON, its up to you.

Subsequent functions, I will not always show you how to get the API in the code, assume that always remains the same.

List Trends

This is useful if you want to know what the trending hashtags and topics are in your area. Twitter makes this available on you dashboard, you can also access it using the API.

Let us say we are based in Johannesburg and would like to know what the trending topics are. All we need is the Longitude, Latitude to get started. You can get this easily by googling a landmark like – Sandton City Mall. Go to Maps:

Sandton City Latitude Longitude
Sandton City Latitude Longitude

You can then input these numbers in your code to list your local trends.

lat = -26.1088467
lon = 28.0505311
trends = api.trends_closest(lat,lon)

woeid = trends[0]['woeid']
top_trends = api.trends_place(woeid)

for item in top_trends[0]['trends']:
    print('\n')
    print(item)

We are doing this in two steps:

  1. We use the longitude and latitude to get the woeid
  2. We use the woeid to get trend data

For Sandton, this is what we got:

Twitter Local Trends Tweepy
Twitter Local Trends Tweepy

You will see the name of the trend, url and even the search volume. So you can organise this to find hashtags to use for your tweets.

Read Twitter Timeline

If you just want to find out what is happening:

public_tweets = api.home_timeline()
print(public_tweets)

Or you want to print out tweets from someone else timeline, like Cryril Ramaphosa for example.

maphosa_tweets = api.user_timeline('CyrilRamaphosa')
print(maphosa_tweets)

You need to know the handle for Ramaphosa of course.

Interact with others

You are also able to use the api to follow, block, etc other people from your python code.

Get your user details:

user = api.me()
print(user)

Get someone else’s public information:

maphosa = api.friends("CyrilRamaphosa")
print(maphosa)

Get Ramaphosa’s Followers:

maphosa_followers = api.followers("CyrilRamaphosa")
print(maphosa_followers)

Follow Ramaphosa

api.create_friendship("CyrilRamaphosa")

Unfollow Ramaphosa:

api.destroy_friendship("CyrilRamaphosa")

Search for users:

search-results = search_users(q=["bitcoin"])
print(search_results)

Ready Create Twitter Bot with Python?

You now have all the power in your hands to go out there and be creative with your twitter account. Engage other users and grow your following. The power is in your hands.

Going forward, you will need:

  1. To run your functions in a loop or schedule
  2. Deploy to a virtual server [guess what you are already on a Virtual Server], just run and go

Video Tutorial

Read more tutorials – https://blog.tati.digital/category/tutorials/

Leave a Reply

Your email address will not be published.

Subscribe to our mailing list

And get this 💃💃 Free😀 eBook !

Holler Box