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!




26 comments:

  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

    ReplyDelete
  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

    ReplyDelete
  3. you provide a very good information that is very useful for modern IT world. I gather lot of articles but this very nice one to read,They gave lot of new ideas for me.Thanks for sharing this valuable information.
    Python Online Training

    ReplyDelete
  4. Thanks for sharing this unique and informative post. This blog which provided me the required information. Software Testing Training in Chennai | Java Training in Chennai

    ReplyDelete
  5. It’s too informative blog and I am getting conglomerations of info’s about Python certification. Thanks for sharing,
    Python Training in Marathahalli
    Java Training in Marathahalli

    ReplyDelete
  6. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

    python training in bangalore|

    ReplyDelete
  7. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    Besant technologies Marathahalli

    ReplyDelete
  8. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
    hadoop training in chennai

    ReplyDelete
  9. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition."Oracle Training in Chennai"

    ReplyDelete
  10. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.

    python training in bangalore|

    ReplyDelete