DEV Community

Cover image for How to create a Twitter Bot using Python and Tweepy (Quick and Easy)
Fernando Groders
Fernando Groders

Posted on

How to create a Twitter Bot using Python and Tweepy (Quick and Easy)

Hey guys, today you are going to learn how to develop a Twitter bot using Python and a library called Tweepy.
Founded in March 2006, Twitter is available in 40 languages and has about 335 million active users per month. Offering users a space for conversation and to share written content, photos and videos, Twitter is one of the most famous social networks.

Table Of Contents

Getting your API keys on Twitter for Developers

First of all, to connect your bot with your Twitter account, you need to use the Twitter API. To get your API keys you need a Twitter account. If you don't have one you can create here Create an Account
Now you will get the access to Twitter for Developers. After accessing it, click on Developer Portal. Click on Developer Portal
Complete your app’s registration by answering the form. Create your app
After that, go to Projects & Apps -> Your App -> Edit app permissions Edit app permissions
Here you can find your app permissions and the API keys. After generating the credentials, save them to later use in your code. Get the API keys

Install Tweepy

Before start coding, you need to install the library that we are going to use. The easiest way to install it is using PIP. (If you don't have PIP installed, Click here. In your CMD:

# Install Tweepy
$ pip install tweepy
Enter fullscreen mode Exit fullscreen mode

Authenticate your App

Now it's time to start the fun part, coding. First of all create a file called "twitter.py". Open it in your IDE and add this code:

# Import Tweepy
import tweepy

# Change with your API keys
API_KEY = ['API_KEY'] 
API_KEY_SECRET = ['API_KEY_SECRET'] 
ACCESS_TOKEN = ['ACCESS_TOKEN']
ACCESS_SECRET = ['ACCESS_SECRET']

# Connect with the API
auth = tweepy.OAuthHandler(API_KEY, API_KEY_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

# Add your code 
Enter fullscreen mode Exit fullscreen mode

Ok, now you have the basic to create a functional bot, but I will give you an example of a bot that answer “@user Hello World” when somebody mention him.

Example Bot

After doing the previous steps, you will need a function to save the last ID answered by the bot. Create a file called "lastId.txt" and put "1" inside without the quotation marks. Then add this code in your twitter.py file:

fileName = 'lastId.txt'
# Function to save the last id answered on ./lastId.txt
def saveLastId(lastId, fileName): 
    f_write = open(fileName, 'w')
    f_write.write(str(lastId))
    f_write.close()
    return
Enter fullscreen mode Exit fullscreen mode

If you have a function to save the ID, you need one to read what your bot saved or it will answer always the same tweet

# Function to read the last id that is saved on ./lastId.txt
def readLastId(fileName): 
    f_read = open(fileName, 'r') 
    ultimo_id_lido = int(f_read.read().strip())
    f_read.close()
    return ultimo_id_lido
Enter fullscreen mode Exit fullscreen mode

After that, we will create a function to answer the tweets

# Function to answer a mention
def tweet():
    print('BOT WORKING...')
    lastId = readLastId(fileName) # Get the last ID
    mentions = api.mentions_timeline(lastId, tweet_mode='extended') # Get all mentions since the last ID
    for mention in reversed(mentions): # Reads the mentions in reverse order
        if '@youruser'.upper() in mention.full_text.upper(): # Verifies if your bot was mentioned 
            lastId = mention.id
            print(str(mention.id) + ' - ' + mention.full_text) # Prints the mention
            saveLastId(lastId, fileName) #Save the last id 
            print('Answering tweet')
            message = 'Hello @{}!'.format(mention.user.screen_name) # Message to be sent
            api.update_status(status=message, in_reply_to_status_id=mention) # Reply to the mention
Enter fullscreen mode Exit fullscreen mode

And to finish the code, we will add a loop to make the bot work every 30 seconds. As we are using "time", then we need to add the import on the top of the file.

import time
Enter fullscreen mode Exit fullscreen mode

In the last line of the file:

#Loop that runs the bot every 30 seconds
while True: 
    tweet()  
    time.sleep(30)
Enter fullscreen mode Exit fullscreen mode

So the final file would be something like:

# Import Tweepy
import tweepy
import time

# Change with your API keys
API_KEY =['API_KEY'] 
API_KEY_SECRET = ['API_KEY_SECRET'] 
ACCESS_TOKEN = ['ACCESS_TOKEN']
ACCESS_SECRET = ['ACCESS_SECRET']

# Connect with the API
auth = tweepy.OAuthHandler(API_KEY, API_KEY_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

fileName = 'lastId.txt'
# Function to save the last id answered on ./lastId.txt
def saveLastId(lastId, fileName): 
    f_write = open(fileName, 'w')
    f_write.write(str(lastId))
    f_write.close()
    return

# Function to read the last id that is saved on ./lastId.txt
def readLastId(fileName): 
    f_read = open(fileName, 'r') 
    ultimo_id_lido = int(f_read.read().strip())
    f_read.close()
    return ultimo_id_lido

# Function to answer a mention
def tweet():
    print('BOT WORKING...')
    lastId = readLastId(fileName) # Get the last ID
    mentions = api.mentions_timeline(lastId, tweet_mode='extended') # Get all mentions since the last ID
    for mention in reversed(mentions): # Reads the mentions in reverse order
        if '@youruser'.upper() in mention.full_text.upper(): # Verifies if your bot was mentioned 
            lastId = mention.id
            print(str(mention.id) + ' - ' + mention.full_text) # Prints the mention
            saveLastId(lastId, fileName) #Save the last id 
            print('Answering tweet')
            message = 'Hello @{}!'.format(mention.user.screen_name) # Message to be sent
            api.update_status(status=message, in_reply_to_status_id=mention) # Reply to the mention

#Loop that runs the bot every 30 seconds
while True: 
    tweet()  
    time.sleep(30)
Enter fullscreen mode Exit fullscreen mode

Now you just need to run the file “Twitter.py” and your bot will start working. If you want you can create a .exe and make it work in second plan. But this will become another tutorial.

Inspiring Examples

Of course this is a very simple example of a bot, but you can create very advanced bots using Tweepy. If you want to read all the possibilities, you can read Tweepy's documentation here. Now it's time to be creative and create bots. If you are not a creative person here are some examples of Twitter bots to inspire you:

Now you are ready to create AWESOME Twitter bots. The next step is upload your bot and run it on Cloud, but this is a topic that will become another article.
If you have any doubts, you can contact me here:

Thanks for reading, if you like it and learned something, like the post, comment and share with others developers! :D

Top comments (0)