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!




43 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
    Replies
    1. Hi Eric,

      Nice to be visiting your blog again, it has been months for me. Well this article that i’ve been waited for so long.

      I am a beginner in programming,started learning python a few days ago.When I was doing exercise,found a problem that I couldn't solve by myself.Could anyone help me about it?Thank you very much.
      My python version is 3.6.3
      the codes:
      Python Code: (Double-click to select all)
      1
      2
      3
      4 name = ["aa", "bb", "cc", "dd"]
      for zzz in (name):
      name.remove(zzz)
      print(name)
      I wanted to delete or remove all values in the list,but the results always contain the values on the even places (like "bb" and "dd").
      However,when I execute codes below:
      Python Code: (Double-click to select all)
      1
      2
      3 name = ["aa","bb","cc","dd"]
      for zzz in (name):
      print("hello, " + zzz)


      I can get the results I want, printing every string with all the names in the list.
      Is it because this function cannot use with remove function?


      PEP 8 provides coding conventions for the Python code. It describes rules to adhere while coding in Python. This helps in better readability of code and thereby better understanding and easy maintainability. It covers from code indentation, amount of space to use for indentation, spaces v/s tabs for indentation, commenting, blank lines, maximum line length, way of importing files, etc.

      It was cool to see your article pop up in my google search for the process yesterday. Great Guide.
      Keep up the good work!

      Ciao,
      Hima

      Delete
  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. I feel really happy to have seen your webpage and look forward to so
    many more entertaining times reading here. Thanks once more for all
    the details.


    AWS Training in Bangalore


    AWS Training in Bangalore

    ReplyDelete
  7. At that point I scanned for website architecture, site improvement, and pay per click Buy twitter followers

    ReplyDelete
  8. It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.

    Data Science Training in Bangalore


    DataScience Training in Chennai


    ReplyDelete
  9. Informative post about hadoop, i am looking forward for realtime hadoop online training institute.

    ReplyDelete
  10. Great article. May be create a short video/GIF about the working of the application. It will be very useful to see the working of the app.

    Ashwathi,
    Facilitator,
    Kamal Technologies - Best React JS, Angular JS, Node JS training institute in Chennai

    ReplyDelete
  11. This blog is very helpful for beginners and experts also, thanks for sharing it. Keep share content on MSBI Online Training Bangalore

    ReplyDelete
  12. many people come and go but i don't think that anyone can replace him https://twitter.com/darrenwinters01 follow this man for the best ideas about business..!!

    ReplyDelete
  13. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.
    AWS Training in Bangalore|

    ReplyDelete
  14. I simply wanted to thank you so much again. I am not sure the things that I might have gone through without the type of hints revealed by you regarding that situation.
    amazon-web-services-training-institute-in-chennai

    Best Hadoop Training Institute In chennai

    ReplyDelete
  15. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.

    Selenium Training in chennai


    ReplyDelete
  16. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
    UI Path Training in Bangalore

    ReplyDelete
  17. My rather long internet look up has at the end of the day been compensated with pleasant insight to talk about with my family and friends.
    Python Training in Bangalore

    ReplyDelete
  18. Hello There,


    A really interesting, clear and easily readable Network Automation Nerds article of interesting and different perspectives' will clap. So much is so well covered here.

    I need some help on how to build this project and what c++ program to us, I have TC in stalled and when I build it comes up with and error or some think like that, all I want is to learn how to build projects and I really want to see how this project works.
    I read multiple articles and watched many videos about how to use this tool - and was still confused! Your instructions were easy to understand and made the process simple.


    Thanks and Regards,
    Meera

    ReplyDelete
  19. This is a much needed information thank you for sharing and it's very helpful to know about this information. Thanks for sharing it MSBI Online Training

    ReplyDelete
  20. I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
    Aws Training in Hyderabad
    Python Training in Hyderabad
    Data Science Training with Python in Hyderabad

    ReplyDelete
  21. This is an excellent blog thanks for sharing valuable information with us please check it once at MSBI Online Training Hyderabad

    ReplyDelete