It’s all in here…

Photo by Chris J. Davis on Unsplash

Twitter is one of the most widely used social networks. For many organizations and people, having a great Twitter presence is a key factor in keeping their audience engaged.

Part of having a great Twitter presence involves keeping your account active with new tweets and retweets, following interesting accounts, and quickly replying to your followers’ messages. You can do all this work manually, but that can take a lot of time. Instead, you can rely on a Twitter bot, a program that automates all or part of your Twitter activity. This is going to be an easy and fast tutorial to create a simple Twitter bot using the Python language and the Tweepy library.

Twitter API

The Twitter API gives developers access to most of Twitter’s functionality. You can use the API to read and write information related to Twitter entities such as tweets, users, and trends.

Technically, the API exposes dozens of HTTP endpoints related to:

  • Tweets
  • Retweets
  • Likes
  • Direct messages
  • Favorites
  • Trends
  • Media

Tweepy, as we’ll see later, provides a way to invoke those HTTP endpoints without dealing with low-level details.

The Twitter API uses OAuth, a widely used open authorization protocol, to authenticate all the requests. Before making any call to the Twitter API, you need to create and configure your authentication credentials. Later in this article, you’ll find detailed instructions for this.

You can leverage the Twitter API to build different kinds of automation, such as bots, analytics, and other tools. Keep in mind that Twitter imposes certain restrictions and policies about what you can and cannot build using its API. This is done to guarantee users a good experience. The development of tools to spam, mislead users, and so on is forbidden.

The Twitter API also imposes rate limits about how frequently you’re allowed to invoke API methods. If you exceed these limits, you’ll have to wait between 5 and 15 minutes to be able to use the API again. You must consider this while designing and implementing bots to avoid unnecessary waits.

You can find more information about the Twitter API’s policies and limits in its official documentation:

What Is Tweepy?

Tweepy is an open source Python package that gives you a very convenient way to access the Twitter API with Python. Tweepy includes a set of classes and methods that represent Twitter’s models and API endpoints, and it transparently handles various implementation details, such as:

  • Data encoding and decoding
  • HTTP requests
  • Results pagination
  • OAuth authentication
  • Rate limits
  • Streams

If you weren’t using Tweepy, then you would have to deal with low-level details having to do with HTTP requests, data serialization, authentication, and rate limits. This could be time-consuming and prone to error. Instead, thanks to Tweepy, you can focus on the functionality you want to build.

Almost all the functionality provided by Twitter API can be used through Tweepy. The only current limitation, as of version 3.7.0, is that Direct Messages don’t work properly due to some recent changes in the Twitter API.

Step 1:Import the Libraries

The Twitter API gives developers access to most of Twitter’s functionality. You can use the API to read and write information related to Twitter entities such as tweets, users, and trends.

Setup a developer's account on Twitter to get the tokens and keys.

Creating Twitter API Authentication Credentials

As we have previously seen, the Twitter API requires that all requests use OAuth to authenticate. So you need to create the required authentication credentials to be able to use the API. These credentials are four text strings:

  1. Consumer key
  2. Consumer secret
  3. Access token
  4. Access secret

If you already have a Twitter user account, then follow these steps to create the key, token, and secrets. Otherwise, you have to sign up as a Twitter user before proceeding.

Apply for a Twitter Developer Account

Go to the Twitter developer site to apply for a developer account. Here, you have to select the Twitter user responsible for this account. It should probably be you or your organization. Here’s what this page looks like:

In this case, I chose to use my own account.

Twitter then requests some information about how you plan to use the developer account, as shown below:

You have to specify the developer account name and whether you are planning to use it for personal purposes or for your organization.

Step 2: Create an Application

Twitter grants authentication credentials to apps, not accounts. An app can be any tool or bot that uses the Twitter API. So you need to register your app to be able to make API calls.

To register your app, go to your Twitter apps page and select the Create an app option.

You need to provide the following information about your app and its purpose:

  • App name: a name to identify your application (such as example bot)
  • Application description: the purpose of your application (such as An example bot for a Real Python article)
  • Your or your application’s website URL: required, but can be your personal site’s URL since bots don’t need a URL to work
  • Use of the app: how users will use your app (such as This app is a bot that will automatically respond to users)

Step 3: Create the Authentication Credentials

To create the authentication credentials, go to your Twitter apps page. Here’s what the Apps page looks like:

Here you’ll find the Details button of your app. Clicking this button takes you to the next page, where you can generate the credentials.

By selecting the Keys and tokens tab, you can generate and copy the key, token, and secrets to use them in your code:

After generating the credentials, save them to later use in your code.

You can test the credentials using the following snippet:

import tweepy
from tkinter import *
consumer_key= ‘’
consumer_secret= ‘’
access_token= ‘’
access_token_secret= ‘’
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
user = api.me()
print(user.name)
print(user.location)

Step 2:Setup the GUI

Here we are using labels to setup Search text and what response would you like to give for it.

root = Tk()
label1 = Label( root, text=”Search”)
E1 = Entry(root, bd =5)
label2 = Label( root, text=”Number of Tweets”)
E2 = Entry(root, bd =5)
label3 = Label( root, text=”Response”)
E3 = Entry(root, bd =5)
label4 = Label( root, text=”Reply?”)
E4 = Entry(root, bd =5)
label5 = Label( root, text=”Retweet?”)
E5 = Entry(root, bd =5)
label6 = Label( root, text=”Favorite?”)
E6 = Entry(root, bd =5)
label7 = Label( root, text=”Follow?”)
E7 = Entry(root, bd =5)
def getE1():
return E1.get()
def getE2():
return E2.get()
def getE3():
return E3.get()
def getE4():
return E4.get()
def getE5():
return E5.get()
def getE6():
return E6.get()
def getE7():
return E7.get()

Step 3: Retweet, Follow, Reply

The function analyzes your response and does the intended action.Its a simple switch statement with each response triggering a corresponding tweepy function.

def mainFunction():
getE1()
search = getE1()

getE2()
numberOfTweets = getE2()
numberOfTweets = int(numberOfTweets)

getE3()
phrase = getE3()

getE4()
reply = getE4()

getE5()
retweet = getE5()

getE6()
favorite = getE6()
getE7()
follow = getE7()
if reply == “yes”:
for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):
try:
#Reply
print(‘\nTweet by: @’ + tweet.user.screen_name)
print(‘ID: @’ + str(tweet.user.id))
tweetId = tweet.user.id
username = tweet.user.screen_name
api.update_status(“@” + username + “ “ + phrase, in_reply_to_status_id = tweetId)
print (“Replied with “ + phrase)

except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
if retweet == “yes”: 
for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):
try:
#Retweet
tweet.retweet()
print(‘Retweeted the tweet’)
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
if favorite == “yes”: 
for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):
try:
#Favorite
tweet.favorite()
print(‘Favorited the tweet’)
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
if follow == “yes”: 
for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):
try:
#Follow
tweet.user.follow()
print(‘Followed the user’)

except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break

submit = Button(root, text =”Submit”, command = mainFunction)
label1.pack()
E1.pack()
label2.pack()
E2.pack()
label3.pack()
E3.pack()
label4.pack()
E4.pack()
label5.pack()
E5.pack()
label6.pack()
E6.pack()
label7.pack()
E7.pack()
submit.pack(side =BOTTOM)
root.mainloop()
Output

That’s It!

Found this article useful? Follow me (Rahula Raj) on Medium and check out my most popular articles below! Please 👏 this article to share !

Check out my other articles.

3 steps for Face Detection using Python


How to Make an Autonomous Twitter Bot in 3 Blissfully Easy Steps using Python? was originally published in Analytics Vidhya on Medium, where people are continuing the conversation by highlighting and responding to this story.