An image

Serverless Twitter Bot

This is my first Twitter Bot. The goal is to tweet jokes every 2 hours. This is a challenge from #NoServerNovember challenge from the Serverless Framework team. The longest part was to create the Twitter account and got the API Keys from Twitter.

Stack:




Steps


  • Install de Serverles Framework
  $  npm i serverless -g
  • Configure AWS provider credentials. Guide
 $  serverless config credentials --provider aws --key <YOUR_AWS_KEY> --secret <YOUR_AWS_SECRET>
  • Create the project using NodeJS template. Guide
$ serverless create --template aws-nodejs --path serverless-twitter-bot 

and then:

$ cd serverless-twitter-bot
  • Create a package.json for NPM
$ npm init 
  • Add Axios dependency, I used Axios as request API for NodeJS. Axios is a great package and it is very easy to use, a very good alternative could be node-fetch.
$ npm i axios 
  • Add Twitter API client for NodeJs. There are differents Twitter clients for NodeJs. This one seems very popular and very easy to use.
$ npm i twitter 
  • Create a Twitter account and get API Keys and Secrets. An e-mail account and a mobile number is needed to create the account, then go to Developer Twitter and fill the form to create an application and get the Keys, this is the longest part of the whole process.

  • Serverless configuration - serverless.yml:

    • The provider information (Runtime, Region, Stage, etc)
    • The Twitter keys are configured as Environment variables.
    • The Function handler and the Event, in this case, a scheduled event.
provider:
  name: aws
  runtime: nodejs8.10 
  stage: dev
  region: eu-central-1
  environment:
    CONSUMER_KEY: #CONSUMER_KEY_HERE"
    CONSUMER_SECRET: #CONSUMER_SECRET_HERE#
    ACCESS_TOKEN_KEY: #ACCESS_TOKEN_KEY_HERE#
    ACCESS_TOKEN_SECRET: #ACCESS_TOKEN_SECRET_HERE#

functions:
  bot:
    handler: handler.bot
    events:
      - schedule: rate(2 hours)

Coding

  • Connecting to Twitter, initialize the Twitter object with Keys:
const Twitter = require('twitter');

const tw = new Twitter({
    consumer_key: process.env.CONSUMER_KEY,
    consumer_secret: process.env.CONSUMER_SECRET,
    access_token_key: process.env.ACCESS_TOKEN_KEY,
    access_token_secret: process.env.ACCESS_TOKEN_SECRET
});
  • Handler:
    • The Dad Joke API needs the User-Agent header, the Twitter Bot account name is used in this case.
    • Async / Await is used for easily handling the flow.
module.exports.bot = async () => {
  try {
    const jokeResponse = await axios({
      url: 'https://icanhazdadjoke.com/',
      headers: {
        'Accept': 'application/json',
        'User-Agent': '@TheMonkeyJoker1'
      }
    }); 
    await tw.post('statuses/update', {
      status: jokeResponse.data.joke
    });
  } catch (err) {
    console.log('Error:' + err.message);
  }
}

Deploy

$ serverless deploy

If everything was fine with the AWS deployment, we'll have our Lambda function tweeting every 2hrs.

twitter-bot

Sources

GitHub