Creating a Twitter bot with Node and AWS SAM

Sep 6, 2020

Twitter logo

šŸ¦ I made my first twitter bot.

The new twitter account is an election forecaster. As of this moment it posts once daily about the current odds of the 2020 presidential election between Joe Biden and Donald Trump. This isn't a partisan account, it's just data.

The 2020 election twitter forecast account is here. To see how it works the source code is on github.

I made this mostly for myself as a way of seeing the current election forecast without having to check Five Thirty Eight every day.

I played with a couple of fun tools. If you have knowledge of these tools it should be straightforward to make a bot for yourself.

Requirements

  • Basic scripting knowledge. I used Node, but you can use whatever language AWS Lambda supports.
  • AWS account with basic knowledge of Lambda, EventBridge, and the Serverless Application Model (SAM).
  • A Twitter developer account
  • An idea

Quick overview

I've been playing around with AWS Lambda a lot recently and I wanted to play with their serverless application model (SAM).

Most of the services here are pretty straightforward on their own. I liked playing with these tools because they gave you an easy way to run a cron job without having to spin up separate EC2 instances. This keeps the cost really cheap when all you have to do is run a simple function once a day.

The AWS Serverless Application Model (SAM) is the service that everything runs on. SAM is an abstraction on top of a bunch of other core AWS services. SAM is a fancy version of AWS Cloudformation. With SAM we can specify the resources we want to use in a template file. That template will tell AWS to create our other resources for us.

In this project we are only going to need to spin up a serverless lambda function and a EventBridge (Cloudwatch) rule that will tell AWS to call our function once a day on a schedule.

template.yml

...
Resources:
  ScheduledEventLogger:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs12.x
      Handler: src/twitter-bot.handler
      # Runs every day.
      Events:
        CloudWatchEvent:
          Type: Schedule
          Properties:
            Schedule: cron(30 20 * * ? *)
      MemorySize: 128
      Timeout: 100
...

The Resources section above will spin up a new lambda function and create a cloudwatch schedule that acts like a cron job. In the example above the job will call the twitter-bot.handler function once a day at 20:30 UTC time.


If you would like to see some code you can find the source on my github. The README there also goes into more detail on how to get set up with AWS SAM.

Bottom line: If you need to do some processing on a set schedule AWS SAM is a great, simple, and cheap way of getting this done. If you have any questions send me an email or message me on Twitter.

A handsome man.

I'm Wesley. I live in Boston and work on Wonderment.

Go back to home