My First Twitter Bot

I’ve been working on this twitter bot occasionally for the past several months and decided to write a three-part series about the process: creating the twitter app, setting up the bot to post images, and hosting the app in the cloud. This bot uses the Rijksmuseum API to tweet out random images from the Amsterdam museum’s collection (they made their public domain collection available in order to extend their reach beyond their own website) and is built using node.js (an open source server framework) and the Twit node package (Twitter API Client for node).

CREATE A TWITTER APP

Before writing any code, create a Twitter app and get the API keys. Open a new tab in Sublime Text (or your IDE of choice) to hold the API keys and name it config.js. Replace the x’s with the matching key values to authenticate:

var config = {
    api_key:  'xxxxxx',
    consumer_key:  'xxxxxx',
    consumer_secret:  'xxxxxx',
    access_token:  'xx-xxxx',
    access_token_secret:  'xxxxxx'
}

module.exports = config;

In order for the bot to make calls to the API, first install the Twit node package and include it in the server.js file with require(). Pull in the Twitter API keys stored in the config file (store the Rijksmuseum API key here as well). Make a Twit object that connects to the APIs and call the post() function to post an actual tweet.

// Use the Twit node package
var Twit = require('twit');

// Pull in all Twitter & Rijksmuseum authorization info
var config = require('./config');

// Make a Twit object for connection to the API
var T = new Twit(config);

// Test the post function
T.post('statuses/update', { status: 'i am a bot, i am a bot' }, function(err, data, response) {
  console.log(data)
})

In Terminal, cd into the project folder and type node server.js to send the first tweet. Check your Twitter feed for new activity. The next article will explain how to set the bot up to post images from the collection. The final article in this three-part series on Twitter bots will explain how to host the bot on Heroku and store the image for posting on AWS S3 (Simple Cloud Storage Service).