How To Make A Simple Twitter Bot

Background

Have you ever noticed a bot account while browsing Twitter? How do those really work?

Is there a robot sitting behind a keyboard somewhere, typing in the tweets and sending them out?


Well, not really of course. Twitter bots are composed of code that interacts with Twitter through their public Application Programming Interface(s), or "API" for short. This guide will explore setting up a Twitter bot by interacting with the Twitter REST API from Node.js. Basic familiarity with Twitter is assumed. If you are not familiar with Node.js, you may wish to learn a little about it by Googling it before beginning to make a Twitter bot. (But don't worry - by no means do you have to be a Node expert to make a simple Twitter bot!)

What IS an API?

To crudely summarize something that is very abstract, Application Programming Interfaces allow programs to interact with other programs.

API has a broad definition in computer science, but in the more narrow context of web development, you may generally think of APIs as the ways through which people interact with different servers out there on the Internet. Often, the servers you access through APIs are not your own. But by providing API to the public, companies and individuals allow other programmers standardized and secure ways to link together different pieces of data and code online through simple HTTP requests. This allows people to create really neat and useful websites!

Example: Riot Games and LolKing.net

To illustrate, consider this example: Riot Games is a video game company with a public API, and LolKing is an unaffiliated business that uses their API. LolKing.net provides in depth statistics about online League of Legends matches, Riot Games' major title, in an easy-to-use and visually appealing website lolking.net by making HTTP requests through Riot's API.

Riot Games didn't create this site, LOLKING.net. Rather, they provided the public access to various data surrounding their game, such as character win rates and popularity, and then gave clients access to that data through their API. So, someone else took it open themselves to develop a website that uses Riot Games' API to display leaderboard statistics, character popularity and win rates, etc. - all displayed in visually appealing charts and graphs and easy to search with the website's UI!

The provision and use of APIs through individuals and organizations creates a sort of online ecosystem - and it's responsible for some of the more interesting recent developments in the utility of websites people use everyday!

Now that we have an understanding of APIs in general, we will move forward to our main example and demonstrate how to use Twitter's API to do things like getting tweets from online or randomly posting tweets that you have stored in your code. From there, we'll only be a stone's throw away from creating something as sophisticated as, for example, @DOTHINGSBOT.

So - let's begin!

Set-up: Getting Twitter API Credentials

In order to interact with Twitter, we need security credentials. Why? Well, imagine if someone with bad intentions were to set up a program that makes millions and millions of requests to Twitter in an attempt to flood the server. To prevent something like that from happening, Twitter uses OAuth. You don't need to know how OAuth works really. To set-up your own bot, you just need to know 2 things:

1.) Make a New Twitter Account -> Create an Application

First, make a new Twitter account by following the sign up process from Twitter.com. Once you have a new account, go to apps.twitter.com and click the button to "Create New App" - you will need a Twitter app registered before you can access Twitter's API!

After clicking Create New App, fill in the Name, Description, and Website fields as appropriate. (Don't worry about the "Callback URL" for now; you can leave it blank.)

Once you have created your app, from your dashboard you can retrieve your access credentials. Click the "Keys and Access Tokens" (highlighted in the screenshot below) tab to see them

Be sure to keep these keys a secret - they are meant to stay private, and you shouldn't share them for security reasons!

2.) Create a new JavaScript file -> Copy and Paste your Keys and Access Tokens

Use the editor of your choice to create a new JavaScript file. Then create a new variable "config" with properties for your security credentials as follows:


/*Credentials retrieved from your twitter apps dashboard go here:*/
var config = {
"consumerKey": "YOUR_CONSUMERKEY_GOES_IN_HERE",
"consumerSecret": "YOUR_CONSUMERSECRET_GOES_IN_HERE",
"accessToken": "YOUR_ACCESSTOKEN_GOES_IN_HERE",
"accessTokenSecret": "YOUR_ACCESSTOKENSECRET_GOES_IN_HERE",
"callBackUrl": "XXX"
}

Replace the appropriate fields in your code by pasting in your credentials from your Keys and Access Tokens tab from apps.twitter.com.

We have our keys in place. Now it's time to put them in the ignition, so to speak, by using Node.js and a convenient node module called TwitterJSClient to authenticate and interact with the Twitter REST API.

We're very close to being able to tweet using JavaScript like a pro hacker, as opposed to logging in and tweeting manually like schmuck!

Using TwitterJSClient to post a tweet.

To install TwitterJSClient you can use the command:

npm install twitter-node-client

Now, we need to add a bit of boilerplate code to the JavaScript file.

The following code basically sets up our Twitter node module by passing it our security credentials. It also defines a couple of call back functions. If you are unfamiliar with call back functions, suffice to say that "error" will log errors if our HTTP request doesn't work, and "success" will log the response Twitter gives us if our request is, well, successful.

/*
* for twitter-node-client help:
see https://github.com/BoyCook/TwitterJSClient/blob/master/README.md
*/


/*CALLBACK FUNCTIONS*/
var error = function(err, response, body){
console.log('ERROR [%s]', err);
};


var success = function(data){
console.log('Data [%s]', data);
};


var Twitter = require('twitter-node-client').Twitter;


/*Credentials retrieved from your twitter apps dashboard go here:*/
var config = {
"consumerKey": "YOURKEYHERE",
"consumerSecret": "YOURKEYHERE",
"accessToken": "YOURKEYHERE",
"accessTokenSecret": "YOURKEYHERE",
"callBackUrl": "XXX"
}


/*Set-up*/
var twitter = new Twitter(config);

Everything is all set up now! From here, we can begin using the TwitterJSClient documentation to see how to make calls like twitter.postTweet() in our code to post a tweet through Twitter's API!

Tweeting 'Hello World!' through Twitter's API

To start showing how a bot can be made with the environment we've set up, we'll start by simply posting a tweet that says 'Hello World!'

We've already taken care of the hard part by importing someone else's convenient node module, so now we can begin doing things like tweeting with relative ease! To tweet 'Hello World!' through your app's account, simply add the following function call to the end of your script:

twitter.postTweet({status: "Hello World!"}, error, success);

Now run your JavaScript file with Node and - *BINGO*, if all goes according to plan, you should see the tweet on your account's timeline!

We did it!!! We tweeted with JavaScript, thru Twitter's REST API - like a PRO!!!

Tweeting a random tweet from a collection

We can extend the functionality of our bot from here by adding more code.

Let's say we don't want the bot simply to tweet the one phrase we pass it in twitter.postTweet(). Instead, we can have the bot pick a random tweet from a collection by using a random number generator. First, we need a collection of strings.

Here are the strings I used for my bot, for example:

The following code creates a collection of these strings called my_tweets in our JavaScript file:

/*array of tweet strings*/
var my_tweets = ["Shout out to Oregon State University", "This was tweeted with JavaScript",
"Wow", "Nice", "cool", "Let's tweet with Node.js", "Math.random() helps a lot!", "Google it!"];

You can replace what's in the quotation marks with any tweet you'd like. Include however many tweets you'd like to in your own collection.

Math.random()

To select a tweet at random, we first generate a random number by using JavaScript's Math Object and the function random(). Math.random() returns a random decimal number between 0 (inclusive) and 1 (exclusive).

To make use of this to choose a tweet at random, we multiply Math.random() by the length of our my_tweet's collection. Then we use another Math function, floor(), to round to an integer value. Here is the code:

twitter.postTweet({status: my_tweets[Math.floor(Math.random() * my_tweets.length)]}, error, success);

Now running your script with Node will make the bot tweet one of the tweets in your my_tweets collection at random!

Post a Random Tweet Every 15 Minutes

Suppose you don't want to have to run your script everytime you want your bot to tweet a random tweet. Instead, we can use JavaScript timing events with setInterval to tweet every 15 minutes.

NOTE: Twitter limits the rate you can send requests or post tweets. See Twitter API Rate Limits here, and remember not to spam or be abusive when making your own bots!

setInterval()

We can set our bot to tweet at random from my_tweets every 15 minutes (i.e., 900000 milliseconds) with the following code:

var randomTweetGen = function() {
twitter.postTweet({status: my_tweets[Math.floor(Math.random() * my_tweets.length)]}, error, success);
}

/*Use JavaScript's timer function setInterval() to automatically schedule tweets*/
setInterval(randomTweetGen,900000);

Now if you run your script (and leave it running), your bot will post a random tweet every 15 minutes. Thus, we've now developed a more or less "fully functional" bot that will tweet all on its own!

Keep a Bot Going...Forever

To make our Twitter bot run in the background so that it can continue tweeting for us while we carry on with our busy life, we can use another helpful node module called Forever.

To install Forever, you can use the command:

npm install forever

You can use Forever to run scripts continuously. To use Forever to keep your Twitter bot tweetin', you can use the command:

forever start twitterBot.js

(Be sure to replace "twitterBot.js" with the name of your own JavaScript file.)

Exploring the API

A Twitter bot can do more than just post random tweets we give it, of course. In fact, our node module TwitterJSCLient has a convenient library of functions we can use to do all sorts of things with the Twitter REST API. For another example, let's demonstrate how we can make our bot search for a tweet by hashtag, and then send a tweet that says hi to whoever used "#bot"!

The code from here on out gets a bit more sophisticated and lengthy. Check out my JavaScript file that implements searching for "#bot" and saying hi to whoever used the hashtag at the github page here

For hints into the method behind my madness, look at the lines I have commented out in bot101.js which log different things to the console. I figured out how to do my bot by playing with parsing different pieces of the responses Twitter gives us and logging them to the console!

@bot_example100

The End

You can explore more on your own by using different node modules, or writing your own code that uses Twitter's API from scratch!

If you want inspiration for a Twitter bot, check out some of my favorites I've run across online: