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!




118 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
    Replies
    1. Amazing Article, thank you!. I just wish to give you a big thumbs up for the excellent post. Kindly keep updating your blog. Java Developer is a dream career for IT students.To start wonderful Career to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India .

      or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

      Delete
  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. This comment has been removed by the author.

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

    ReplyDelete
  22. Great post and informative blog.it was awesome to read, thanks for sharing this great content to my vision.
    embedded rtos training in chennai | embedded testing training in chennai .

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. thanks for conveying this information in a simpler manner..
    https://www.besanttechnologies.com/training-courses/python-training-institute-in-chennai

    ReplyDelete
  25. Very Good and Useful Information about python-and-aws Thanks For Sharing Nice Article anyone want to learn advance devops tools training or devops Online training
    DevOps Online Training

    ReplyDelete
  26. Thank you for sharing such great information with us. I really appreciate everything that you’ve done here and am glad to know that you really care about the world that we live in
    Click here:
    angularjs training in velarchery
    Click here:
    angularjs training in sholinganallur

    ReplyDelete
  27. I am so proud of you and your efforts and work make me realize that anything can be done with patience and sincerity. Well I am here to say that your work has inspired me without a doubt.
    Click here:
    Microsoft azure training in bangalore
    Click here:
    Microsoft azure training in pune

    ReplyDelete
  28. Excellent blog, I wish to share your post with my folks circle. It’s really helped me a lot, so keep sharing post like this
    Blueprism training in marathahalli


    AWS Training in chennai

    AWS Training in bangalore



    ReplyDelete
  29. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    Devops training in velachery
    Devops training in annanagar

    ReplyDelete
  30. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.

    rpa training in electronic-city | rpa training in btm | rpa training in marathahalli | rpa training in pune

    ReplyDelete
  31. That was a great message in my carrier, and It's wonderful commands like mind relaxes with understand words of knowledge by information's.

    java training in annanagar | java training in chennai

    java training in chennai | java training in electronic city

    ReplyDelete
  32. very nice blog.it contains a lot of information for amazon web services(aws).Thanks a lot.aws online training

    ReplyDelete
  33. Well done! Pleasant post! This truly helps me to discover the solutions for my inquiry. Trusting, that you will keep posting articles having heaps of valuable data. You're the best! 
    angularjs Training in marathahalli

    angularjs interview questions and answers

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in chennai

    ReplyDelete
  34. Thanks for the information, Get the best AWS Training in Chennai from hope tutors.

    ReplyDelete
  35. Thanks for the information. Nice blog. I understood the concept very well. This blog is very informative. And it’s very interesting topic.

    Python Training in Chennai

    ReplyDelete
  36. This comment has been removed by the author.

    ReplyDelete
  37. Really awesome work. keep on blogging, thanks for sharing!
    DevOps Online Training

    ReplyDelete
  38. But he’s trying none the less. I’ve been using Movable-type on several websites for about a year and am anxious about switching to another platform.
    fire and safety course in chennai

    ReplyDelete

  39. Good job in presenting the correct content with the clear explanation. The content looks real with valid information. Good Work

    DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

    Good to learn about DevOps at this time.


    devops training in chennai | devops training in chennai with placement | devops training in chennai omr | devops training in velachery | devops training in chennai tambaram | devops institutes in chennai | devops certification in chennai | trending technologies list 2018

    ReplyDelete
  40. For this web site, you will see our account, remember to go through this info.
    mason soiza

    ReplyDelete
  41. This comment has been removed by the author.

    ReplyDelete
  42. Hey, would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would enjoy your content. Please let me know. Thank you.
    AWS Training in Chennai
    Data Science Training in Chennai
    Python Training in Chennai

    ReplyDelete
  43. Much obliged to you for exceptionally usefull data.. Buy Twitter Retweets

    ReplyDelete
  44. 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 Chennai | Best Data Science Training in Chennai
    Python Training in Chennai | Best Python Training Institutes in Chennai
    RPA Training in Chennai | Best RPA Training in Chennai
    Digital Marketing Training in Chennai | Best Digital Marketing Training in Chennai

    ReplyDelete
  45. Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts
    angularjs online training

    apache spark online training

    informatica mdm online training

    devops online training

    aws online training

    ReplyDelete
  46. This comment has been removed by the author.

    ReplyDelete

  47. The information which you have provided is very good. It is very useful who is looking for Python Training

    ReplyDelete
  48. What a useful article, This is a wonderful sharing, Given so much info in it, keep sharing more..

    ExcelR Data Science in Bangalore

    ReplyDelete
  49. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!
    date analytics certification training courses

    ReplyDelete
  50. Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
    python training in bangalore

    ReplyDelete
  51. I am overwhelmed by your post with such a nice topic. Usually I visit your blogs and get updated through the information you include but today’s blog would be the most appreciable. Well done!




    DATA SCIENCE COURSE MALAYSIA

    ReplyDelete
  52. Interesting post. I Have Been wondering about this issue, so thanks for posting. Pretty cool post.It 's really very nice and Useful post.Thanks
    Data Science Course in Pune

    ReplyDelete
  53. Really I Appreciate The Effort You Made To Share The Knowledge. This Is Really A Great Stuff For Sharing. Keep It Up . Thanks ForQuality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing. data science course in singapore

    ReplyDelete
  54. I see the greatest contents on your blog and I extremely love reading them.
    machine learning course in bangalore

    ReplyDelete
  55. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!data science course in dubai

    ReplyDelete
  56. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites! Now please do visit our website which will be very helpful.
    machine learning course bangalore

    ReplyDelete
  57. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
    top 7 best washing machine
    www.technewworld.in

    ReplyDelete
  58. I am definitely enjoying your website. You definitely have some great insight and great stories.
    Windows VPS Hosting India

    ReplyDelete

  59. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!
    www.technewworld.in
    How to Start A blog 2019
    Eid AL ADHA

    ReplyDelete
  60. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
    data science course malaysia

    ReplyDelete
  61. I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!
    data analytics course malaysia

    ReplyDelete
  62. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.
    Data Science Courses

    ReplyDelete
  63. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us
    You will get an introduction to the Python programming language and understand the importance of it. How to download and work with Python along with all the basics of Anaconda will be taught. You will also get a clear idea of downloading the various Python libraries and how to use them.
    Topics
    About ExcelR Solutions and Innodatatics
    Do's and Don’ts as a participant
    Introduction to Python
    Installation of Anaconda Python
    Difference between Python2 and Python3
    Python Environment
    Operators
    Identifiers
    Exception Handling (Error Handling)
    Excelr Solutions

    ReplyDelete
  64. Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is fantastic, let alone the content!

    3d animation Company
    Best Chatbot Development Company
    Mobile app development in Coimbatore

    ReplyDelete
  65. Such a great and informative article.
    You just made my day thanks for sharing this article.

    data science course singapore is the best data science course

    ReplyDelete
  66. The article is very interesting and very understood to be read, may be useful for the people. I wanted to thank you for this great read!! I definitely enjoyed every little bit of it. I have to bookmarked to check out new stuff on your post. Thanks for sharing the information keep updating, looking forward for more posts..
    Kindly visit us @
    Madurai Travels | Travels in Madurai
    Best Travels in Madurai
    Cabs in Madurai | Madurai Cabs
    Tours and Travels in Madurai

    ReplyDelete