Building a Twitter Bot with Python and AWS Lambda
Tags: tutorial, twitter, python, aws
Published: 2020-07-14 16:05:09

I think bots are neat. I really like the artwork on Pokémon trading cards. So I built a Twitter bot that tweets out two Pokémon cards every six hours in Pokémon in-game battle style.

You can check out the Twitter bot at [@tinyversusbot](https://twitter.com/tinyversusbot) and if you want to see the Pokémon team you'd start your adventure with, visit [tinyversusbot](https://tinyversusbot.herokuapp.com/).

Here's an overview of how I created this bot using Python and AWS Lambda.

---

##Summary
1. Link a Twitter developer account to your Python project using the `tweepy` library

2. Add your project to AWS Lambda to tweet in intervals

---

##Breakdown
###Part 1: Twitter Developer Account and `tweepy` Python Library
**1. Create a Twitter Account**
If you haven't already, you're going to need to create the Twitter account that your bot will be tweeting from/as. You can register [here](https://twitter.com/i/flow/signup).

**2. Create a Twitter Developer Account**
You can create your Twitter developer account [here](https://developer.twitter.com/en/apply-for-access). Connect this account to the Twitter account you made in Step 1.

**3. Connect to your Twitter Account via Tweepy**
I used the `tweepy` library for this bot - you'll need to have it installed.
```
pip install tweepy
```

Import tweepy and set up the authorization.
```
import tweepy

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
```

Here are some tweet code examples:
```
# Standard tweet
# var tweet || inline string
api.update_status(status=tweet)

## Tweet with media (multiple images)
api.update_status(status=tweet, media_ids=mediaIds)
```
Note: You can't tweet images directly from their web URLS. You'll have to store the image locally before you can use it.

Check out their [documentation](http://docs.tweepy.org/en/latest/) for other `tweepy` abilities.

---

###Part 2: Setting Up Your Bot on AWS Lambda
**1. Create an AWS Account**
[Sign up](https://aws.amazon.com/) for an AWS account if you don't have one.

**2. Create Your Lambda Function**
Go to [Lambda Service](https://aws.amazon.com/lambda/), click on "Functions", then on "Create function." Name your function, select the appropriate Runtime, then click "Create function."

In your Lambda Function, you can either place your code in `lambda_function.py` or create your own file within the AWS code editor. Don't delete the `lambda_handler` function that is needed to return a status code for Lambda to run.

Above the `return` in the `lambda_handler` function, make a call to your tweet function.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/g46kpr1b1yuyfnpcijcj.png)

**2.5. Add Environment Variables**
I originally had this code committed to GitHub and deployed to Heroku, so I set up environment variables - this was so that I can connect to the Twitter API without committing my secrets. 

When I moved the tweet code to AWS Lambda, I still created the environment variables to keep any credentials out of the code.

Add your authorization key and secrets as environment variables and update your code. 

Here's an example where I declare my consumer key as an environment variable:
```
CONSUMER_KEY = environ['CONSUMER_KEY']
```

**3. Add Layer**
I imported some Python packages that aren't installed natively on Lambda. Layers store dependencies and can be used by other functions, so if you happen to be creating a whole lot of Twitter bots that use the same libraries, you won't need to repackage them for every new function.

Your Python libraries need to be imported as a zipped folder within a `python` subdirectory. My zipped folder structure looks like this:
```
layer > python > my python libraries
```

On the Lambda dashboard, create a new layer and upload the .zip file. Go back to your Lambda function and add the new layer. To test and confirm that everything's working as expected, click the "Test" button above your Designer panel.

If there's a new tweet on your Twitter account, congratulations! It worked!

**4. Add CloudWatch Trigger**
Now we need to add a trigger that automatically runs at certain intervals so that your bot tweets on its own. My bot doesn't have any specific requirements, only that it needs to post every six hours, so I set it on a schedule with a fixed rate of 6 hours.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ouunta8uwwv71bolyr85.png)

Go to your CloudWatch service and create a new rule (under the Events tab). Set a new target to your Lambda function and press "Configure details".

After doing all that, my Designer panel looks like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nmn6g2fru2p6pgx6ewxy.png)

**5. You're Done!**
Your Twitter bot should be active and running on its own.

Pay attention to the default timeout setting. My code times out with the default time, so I had to raise the timeout setting. If your program takes more than the default 30 seconds, you will need to increase the timeout setting.

On the free tier of AWS Lambda, you get 1 million requests free each month. If you plan on going over the free tier limit, keep an eye on how much compute time you're consuming. CloudWatch metrics can be found on the "Monitoring" tab on your Lambda function.

> Happy bot developing! Feel free to share your Twitter bots below.