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
*.pyc
credentials.json

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.

https://twitter.com/Network4_Nerds

echou$

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"],
                 credentials["consumer_secret"],
                 credentials["access_token_key"],
                 credentials["access_token_secret"])
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):
            print(tweet["text"])
            # 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
            try:
                client.retweet(id=tweet["id"])
            except TwythonError as e:
                print(e)

results = client.search(q=query)
pprint.pprint(results)


Happy Coding!




2 comments:

  1. hello admin.I got enough knowledge about Make a Twitter Bot in Python and AWS Lambda.Thank you for explaining in step by step.I am really impressed your blog.if you want know more details about..CCNA Training in Bangalore
    AWS Training in Bangalore

    ReplyDelete