Tuesday, September 6, 2016

Make a Twitter Bot in Python and AWS Lambda

I followed this excellent tutorial from Joel Grus on how to make a Twitter Bot. If you have followed some of my post before, Project Mining Social Web 2nd Edition or Python with JSon, you know I have had a little bit of experience using the Twitter API.

Here is a screenshot of the Twitter Bot:

What is different this time, is that I wish to use AWS Lambda as the backend. I want to know what is required and what the workflow was. I wont repeat the steps Joel listed out in his tutorial, just some of the things I found out:

1. Seems that AWS Lambda wants the main file to be lambda_function.py and the main function to be lambda_handler(event, context).

2. The scheduling trigger is now "CloudWatch Events - Schedule" instead of just schedule.

3. I learned this from a friend that to always immediately put the credential file in .gitignore to avoid accidentally checking it in on GitHub.

echou$ cat .gitignore

I am now the proud owner of a Twitter Bot that searches for Cisco layoff news and retweet them. On this date of Aug. 19, 2016 that was the big news of the week.



Here is what my code ended up as:

from __future__ import print_function
from twython import Twython
from twython.exceptions import TwythonError
import re
import json, pprint
with open('credentials.json') as f:
  credentials = json.loads(f.read())
client = Twython(credentials["consumer_key"],
query = "cisco layoffs -filters:retweets"
rgx = r"cisco"
def lambda_handler(event, context):
    results = client.search(q=query)
    for tweet in results["statuses"]:
        text = tweet["text"]
        # re.search matches anywhere in the string; re.I means case-insensitive
        if re.search(rgx, text, re.I):
            # client.retweet will raise an error if we try to retweet a tweet
            # that we've already retweeted. to avoid having to keep track, we
            # just use a try/except block
            except TwythonError as e:

results = client.search(q=query)

Happy Coding!


  1. That is very interesting; you are a very skilled blogger. I have shared your website in my social networks! A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article.
    Aws Online Training

  2. Updating ourselves to the latest technology is the good idea to live in this modern IT world. Reading articles like your blog this will make an encouraging power within me. Thanks for sharing such an informative content. AWS Training in Bangalore | Big Data Hadoop Training in Bangalore