How to create a Twitter Bot using Python and Tweepy (Quick and Easy)
Tags: python, beginners, twitter, tutorial
Published: 2021-08-24 16:18:10

Hey guys, today you are going to learn how to develop a [Twitter] (https://twitter.com/) bot using Python and a library called [Tweepy] (https://www.tweepy.org).
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](#chapter-1)
* [Install Tweepy](#chapter-2)
* [Authenticate your App](#chapter-3)
* [Example Bot](#chapter-4)
* [Inspiring Examples](#chapter-5)
 
## Getting your API keys on Twitter for Developers <a name="chapter-1"></a>
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](https://twitter.com/i/flow/signup) ![Create an Account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zrqtyv2nc50dgazab7tr.png)
Now you will get the access to [Twitter for Developers] (https://developer.twitter.com/en). After accessing it, click on Developer Portal. ![Click on Developer Portal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4i2s8klnq9l70pbj91rd.png)
Complete your app’s registration by answering the form.  ![Create your app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wpz4qlm8dc3wv4uv34i2.png)
After that, go to Projects & Apps -> Your App -> Edit app permissions ![Edit app permissions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dnbq31vt6v6bo0sen3ic.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2jimbw02t965g39754e7.png)
 
## Install Tweepy <a name="chapter-2"></a>
Before start coding, you need to install the library that we are going to use. The easiest way to install it is using [PIP](https://pypi.org/project/pip/). (If you don't have PIP installed, [Click here](https://pip.pypa.io/en/stable/installation/). In your CMD:
```shell
# Install Tweepy
$ pip install tweepy
```
 
## Authenticate your App <a name="chapter-3"></a>
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:
```python 
# 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 
```
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 <a name="chapter-4"></a>
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:
```python
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
```

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
```python
# 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
```
After that, we will create a function to answer the tweets
```python 
# 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
```

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.
```python 
import time
```
In the last line of the file:
```python 
#Loop that runs the bot every 30 seconds
while True: 
    tweet()  
    time.sleep(30)
```
So the final file would be something like:
```python
# 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)
```
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 <a name="chapter-5"></a>
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](https://docs.tweepy.org/en/stable/index.html). 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:
* [Dizumfilme](https://twitter.com/DizUmFilme)
* [Philosopher BOT](https://twitter.com/bot_philosopher)
* [Video Downloader Bot](https://twitter.com/DownloaderBot)
* [CleverBot](https://twitter.com/cleverbot)
* [Art Commission Bot](https://twitter.com/cmsn_ART)

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:
* [Website](https://fegroders.github.io)
* [LinkedIn](https://www.linkedin.com/in/fernandogroders) 
* [Instagram](https://instagram.com/fegroders) 

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