dark mode light mode Search Menu
Search

How to Build Example Bot

Mark Kelly on Flickr

To help people understand how Twitter bots work, Darius Kazemi has created an Example Bot project on Github which anybody can download and tweak. Here are the instructions on how to use this project.

This Twitter bot retweets the latest tweet using the “#mediaarts” hashtag. It attempts to retweet once per hour. This article is a slightly expanded version of the README.MD file for the Example Bot project on Github. Mostly I have added links to the bottom of the article, some of which are in the readme file.

You must be comfortable using your computer’s command line interface to use this bot. If you’ve never used it, there are tutorials for Mac OSX and Windows at the bottom of this article. You’ll also need a text editor, for example, TextWrangler for Mac or Notepad++ for other operating systems. Both editors are free.

Installation

If you don’t already have have them, please install Node.js (links below). This will install two programs: node, which runs JavaScript from the command line, and npm, which helps you install software that Node.js can run.

Make an empty project directory somewhere convenient for you, download the master zip file with the Example Bot files, and unzip the contents to your project directory. Go to your project directory in the command line. There should be three files there: .gitignore, README.md, and bot.js.

With your command line software, navigate to the project directory then type:

npm install twit

This installs some code to the npm_modules subdirectory, which you don’t need to worry about. (It’s Twit, the library that lets us talk to Twitter.)

Connecting to Twitter

At this point you need to register a Twitter account and also get its “app info”.

So create a Twitter account for whatever account you want to tweet this stuff. Twitter doesn’t allow you to register multiple twitter accounts on the same email address. I recommend you create a brand new email address (perhaps using Gmail) for the Twitter account. Once you register the account to that email address, wait for the confirmation email. Then go here and log in as the Twitter account for your bot:

https://dev.twitter.com/apps/new

Once you’re there, fill in the required fields: name, description, website. None of it really matters at all to your actual app, it’s just for Twitter’s information. Do the captcha and submit.

Next you’ll see a screen with a “Details” tab. Click on the “Settings” tab and under “Application Type” choose “Read and Write”, then hit the update button at the bottom.

Then go back to the Details tab, and at the bottom click “create my access token”. Nothing might happen immediately. Wait a minute and reload the page. then there should be “access token” and “access token secret”, which are both long strings of letters and numbers.

Now use a text editor to open up the “config.js” file included in the Example Bot files you downloaded. The config.js file should look like this:

module.exports = {
  consumer_key:         'blah',
  consumer_secret:      'blah',
  access_token:         'blah',
  access_token_secret:  'blah'
}

In between those quotes, instead of ‘blah’, paste the appropriate info from the Twitter Details page. This is essentially the login information for your Twitter app.

Now type the following in the command line software, assuming you are still working in your project directory:

node bot.js

Hopefully at this point you see a message like “Success! Check your bot, it should have retweeted something.” Check the Twitter account for your bot, and it should have retweeted a tweet with the #mediaarts hashtag.

The Example Bot Code Explained

Since this magazine is about helping people explore computer science and software programming, here is a brief explanation of the Example Bot code. Here is the code in the bot.js file which creates then runs the bot:

// Our Twitter library
var Twit = require('twit');

// We need to include our configuration file
var T = new Twit(require('./config.js'));

// This is the URL of a search for the latest tweets on the '#mediaarts' hashtag.
var mediaArtsSearch = {q: "#mediaarts", count: 10, result_type: "recent"};

// This function finds the latest tweet with the #mediaarts hashtag, and retweets it.
function retweetLatest() {
    T.get('search/tweets', mediaArtsSearch, function (error, data) {
        // log out any errors and responses
        console.log(error, data);
        // If our search request to the server had no errors...
        if (!error) {
            // ...then we grab the ID of the tweet we want to retweet...
            var retweetId = data.statuses[0].id_str;
            // ...and then we tell Twitter we want to retweet it!
            T.post('statuses/retweet/' + retweetId, { }, function (error, response) {
                if (response) {
                    console.log('Success! Check your bot, it should have retweeted something.')
                }
                // If there was an error with our Twitter call, we print it out here.
                if (error) {
                    console.log('There was an error with Twitter:', error);
                }
            })
        }
        // However, if our original search request had an error, we want to print it out here.
        else {
            console.log('There was an error with your hashtag search:', error);
        }
    });
}

// Try to retweet something as soon as we run the program...
retweetLatest();
// ...and then every hour after that. Time here is in milliseconds, so
// 1000 ms = 1 second, 1 sec * 60 = 1 min, 1 min * 60 = 1 hour --> 1000 * 60 * 60
setInterval(retweetLatest, 1000 * 60 * 60);

Here are the details:

  • First, notice all the comments which begin with //. Not only are they helpful, terse useful comments are a sign of a professional. Not because the coder is special. Rather the coder knows they (or someone else) may have to come back in a year and no comments, or bad comments, would make the future update difficult, maybe impossible.
  • Line 2 includes the Twit library when this script is run by Node.js. All the Twitter-related interactions, for example, login and tweeting, are handled by Node.js with the Twit library. This saves you coding, or knowing how to code, all the back and forth with Twitter.
  • Line 5 sets a variable called T to store all the configuration values the Twit library will need when it runs. These Twit configuration values are in the config.js file in the Twit folder.
  • Line 9 sets a variable with values needed by Twit. These values are in pairs, as keys and values separated by a single colon (:) and with each key:value pair separated by a comma. This key:value pair format is JSON format. In this case, the q key has a value of #mediaarts, the hashtag used by tweets the Example Bot will retweet. The count key has a value of 10 to limit how many retweets the bot will make. The result_type key limits the tweets to recent tweets, using the recent value.
  • Line 11 starts the retweetLatest() function. This function calls on line 12 the T variable which, if you remember, holds the configuration values for the Twit library, the mediaArtsSearch variable with our Twitter search parameters in key:value pairs, and sets up an error function then instructs the function on line 14 to log any errors to a log file. This is basic setup code for most functions.
  • Line 16 begins the definition of what happens if there is no error (!error). A success or failure message is written to the log file.
  • Line 31 begins the definition of what happens if there is an error, using an else statement. An error message is written to the log file.
  • Line 38 calls the retweetLatest() function when the Example Bot program is run.
  • Line 41 uses the setInterval() JavaScript function to call the retweetLatest function every hour (1000*60*60) as defined in milliseconds. Once you call Example Bot with the node bot.js command from your command line software, this value tells Node.js how often to call the bot.js file.

You also should note the Example Bot application also has an ideal file structure. The bot code is in bot.js and configuration values in config.js. This is a pattern you’ll find with many Node.js applications. And all applications tend to follow a common pattern based on the preferences of coders who use a particular language.

Next Steps

Here are a couple ways you might tweak the Example Bot project, in no particular order:

  • Edit the bot.js file to change the hashtag to something different. It’s line 8 in the current bot.js file, the q: "#mediaarts" bit. Change #mediaarts to something different and be sure to keep the double quotes before and after your hashtag.
  • Edit the bot.js file to change the update frequency. It’s the last line with comments above to explain the formula, the setInterval(retweetLatest, 1000 * 60 * 60); bit. Time is measured in milliseconds. The default update time is 1 hour, or 1000 milliseconds (= 1 second) times 60 seconds (= 1 minute) times 60 minutes (= 1 hour). To change to 30 minutes, for example, the formula would be 1000 milliseconds (= 1 second) times 60 seconds (= 1 minute) times 30 minutes.

Learn More

Command Line Interfaces (CLI)

http://blog.teamtreehouse.com/introduction-to-the-mac-os-x-command-line
http://www.bleepingcomputer.com/tutorials/windows-command-prompt-introduction/
https://kidscodecs.com/linux-command-list-for-command-line-interfaces/
https://kidscodecs.com/where-to-find-command-line-interface-software/

Node.js

http://nodejs.org/
http://nodejs.org/download/
http://www.bearfruit.org/2013/06/19/how-to-install-node-js-successfully/

Darius K’s Example Bot Respository on Github

https://github.com/dariusk/examplebot
https://github.com/dariusk/examplebot/archive/master.zip

Twitter

https://dev.twitter.com/apps/new

Text Editors

http://www.barebones.com/products/textwrangler/
http://notepad-plus-plus.org/

Twit Library for Node.js

https://github.com/ttezel/twit

A Twitter Bot in 20 Minutes With Node.js

Definitely 20 minutes if you know what you’re doing. The article on this page should make this article even more self-explanatory.
http://www.apcoder.com/2013/10/03/twitter-bot-20-minutes-node-js/