A Twitter Bot in 20 Minutes With Node.js

By Posted in - Development & Technology on October 3rd, 2013 20 Comments Bot
Update (10/15/2013):

I’ve updated the post to reflect a some recent, minor changes to the twit library.

(Quick) Intro

My aim here is to simply provide a jumping off point for anyone interested in learning about Twitter bots, Node.js, or both. We’ll get a functioning bot up in as short a time as possible using a copy-paste approach, from which point you can modify, improve, or break it all you want.

Speed-run Version

Here’s a list of what we’re going to do. You may not even need to read anything beyond this if you’re in a hurry and already know whay you’re doing.

  1. Install Node.js – http://nodejs.org/
  2. Create a Twitter account – http://www.twitter.com/
  3. Register an application with the Twitter API – https://dev.twitter.com/
  4. Create an access token
  5. Install the twit module – https://github.com/ttezel/twit
  6. Configure the example with your consumer key, consumer secret, access token, and access token secret
  7. Make millions selling fake Viagra (Just kidding, please don’t try to do this.)

Node.js

For installing node, you can either go to http://nodejs.org/ and download it, use a package manager if you’re on Linux, or install from source here https://github.com/joyent/node/wiki/Installation. I’m a fan of installing from source, but it’s up to you.

Once you’ve installed it, create a file called hello.js. Open it and enter:

console.log("Hi there, world");

Now, at the command prompt type:

node hello 

If you see “Hi there, world” in your terminal, then it worked.

Create a Twitter Account

We are making a bot

First off, yes, we are making a bot. This does not mean we will be spamming people. However, even with the best of intentions it can be easy to accidentally have a bot perform in ways that might draw forth the wrath of Twitter. We will do our best to avoid this, but as you play around with making bots you run the risk of having an account banned or otherwise mucked with.

For this reason I highly recommend creating a new Twitter account. That way if your account gets banned, no big deal. I would hate to see you lose your social media maven account with 100,000+ followers because of some faulty bot logic.

Once you have a Twitter account set up, make sure you’re following a few dozen people. The people you choose to follow become a foundation for future bot actions.

Twitter API Access

Head over to https://dev.twitter.com/. Once you’ve signed in with the Twitter account you’ll be using with your bot, go to My Applications. Twitter now requires authentication for all API calls, so we have to create an application which will provide us with some tokens that will allow us to utilize the API.

Once you’ve created your application, go to the details tab and take a look at the OAuth settings. Copy the consumer key and consumer secret, as we’ll be needing those soon. Now go to the Settings tab. Under the header Application Type, select “Read, Write, and Access direct message”. This will give our bot free reign to access almost all of the API calls. Click the update button and go back to details.

Scroll to the bottom and create an access token. You may have to refresh the page a few times before it shows up. Now you’ll see an “Access token” and an “Access token secret”. Copy these as well.

At this point we have two entities that we’re working with. We have our actual Twitter user account and we have a registered application. We can make API calls either as a user or as an application.

This definitely matters for people who make Twitter applications that customers or clients access and then grant permission to perform actions on their behalf. Right now, for us, it doesn’t matter. The only thing you might want to know right now is that you use the consumer key and consumer secret to make API calls on behalf of the application, and you use your access token and access token secret to make API calls on behalf of your user account.

Installing the twit Module

Node.js has a number of things going for it, but in particular it has one big advantage over many other technologies: an incredible community. You can find all kinds of open source libraries and examples online.

We will start off by taking advantage of this fact. The first thing we need is a Twitter API library so we can actually make API calls in our project. Let’s go ahead and use this one (https://github.com/ttezel/twit). Let’s create a directory called twitterbot. Go the that directory in your terminal.

Node.js comes with a nifty package manager called npm.  npm stands for Nifty Package Manager (or maybe it’s Node Packaged Modules, I forget). It makes installing packages, or modules as they are more properly called, quite straightforward.

Let’s start by installing the twit module:

npm install twit

If you’re on linux of OS X and get an error, after it fails try:

sudo !!

This is what you’ll end up with:

.
└── node_modules
    └── twit
        ├── examples
        │   ├── bot.js
        │   └── rtd2.js
        ├── lib
        │   ├── auth.js
        │   ├── oarequest.js
        │   ├── parser.js
        │   └── twitter.js
        ├── node_modules
        │   └── oauth
        │       ├── examples
        │       │   ├── express-gdata
        │       │   │   ├── server.js
        │       │   │   └── views
        │       │   │       ├── google_calendars.ejs
        │       │   │       ├── google_contacts.ejs
        │       │   │       └── layout.ejs
        │       │   └── term.ie.oauth-HMAC-SHA1.js
        │       ├── index.js
        │       ├── lib
        │       │   ├── oauth2.js
        │       │   ├── oauth.js
        │       │   ├── sha1.js
        │       │   └── _utils.js
        │       ├── LICENSE
        │       ├── Makefile
        │       ├── package.json
        │       ├── Readme.md
        │       └── tests
        │           ├── oauth2.js
        │           ├── oauth.js
        │           └── sha1.js
        ├── package.json
        ├── README.md
        └── tests
            ├── long-running-rest.js
            ├── multiple-conn.js
            ├── rest.js
            ├── streaming.js
            ├── twit.js
            └── user-stream.js

Running the Bot

We are now mere minutes away from having a functioning Twitter bot. Navigate to the node_modules -> twit -> examples folder. bot.js is a module that provides a few function calls that perform some multi-step Twitter actions, but we don’t need to look at that right now. In fact, all we need to do to get our bot running is to go up one directory (node_modules -> twit) and create a configuration file.

Create a file called config1.js. The twit README.md file shows the proper format for the config file:

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

If you’ve followed along and set everything up in Twitter, you should already have these values. Now, the big moment. Type in the following:

node examples/rtd2.js

You now officially have a running Twitter bot. If you get impatient and don’t want to wait for the first action, you can go into rtd2.js and, at the end of the setInterval, change the interval from 40000 (40 seconds) to something smaller, like 10000 (10 seconds).

What’s it Doing?

Right now, not a whole lot. Every 40 seconds it does one of 3 things: 1) tweet a random popular tweet from github, 2) follow a random friend of one of your followers, or 3) unfollow someone who hasn’t followed you back.

As a brief aside, I did exactly what we’ve just done a few months back. I set up a bot, let it start running, and then promply forgot about it. I checked up on it about a week later and was stunned to see it had over 400 followers. How many of those followers themselves were bots is another matter.

What Next?

This just scratches the surface of both node and creating Twitter bots. I plan on writing more posts on this topic, but there are a few different directions I could take things. What would you like to see next? A deeper look at the node code behind it? Analysis of the Twitter API and bot behavior? Something else? Leave a comment and let me know. Or, if you have any feedback, I’d love to hear it. Thanks!

Update:

A second tutorial on expanding your bot’s functionality is now up.

Stay Up to Date

If you have enjoyed the tutorials so far and want to be notified as soon as another one comes out, please sign up to be notified. I promise you that I won’t spam you.



(20) awesome folk have had something to say...

  • Weng Fu - Reply

    October 5, 2013 at 1:01 pm

    Can you please provide source code for this soft in the VB6 language. Thank you.

  • Peter Armstrong - Reply

    October 5, 2013 at 1:59 pm

    Awesome tutorial! I set it up in about 20 minutes and I plan on spending saturday customizing it :) Looking forward to reading more from you in the future :)

  • sunpietro - Reply

    October 5, 2013 at 4:43 pm

    What about limits Twitter have for making request?
    As far as I know, it’s 15 requests per 15 minutes.

  • Max - Reply

    October 5, 2013 at 5:32 pm

    haha!

  • Christian Paulsen - Reply

    October 5, 2013 at 5:40 pm

    Peter Armstrong:

    Thanks! I’m curious to see what kind of bot you end up making.

    Sunpietro:

    Yes, 15 requests per 15 minutes is right, though there is a bit of variation. Here’s a list of API call limits: https://dev.twitter.com/docs/rate-limiting/1.1/limits.

    It can definitely make debugging a bit of a pain at times. I hope to go into that in a bit more detail in a later post.

  • Greg - Reply

    October 7, 2013 at 3:56 pm

    Great post. Would love to see deeper dive into where you can go with a twitter bot or alternatives/comparison to the twitter API. Maybe a “when” to use “what” communication API.

  • Roger Moore - Reply

    October 8, 2013 at 3:58 pm

    lol ?

  • Umair Aslam - Reply

    October 9, 2013 at 12:30 pm

    i have followed the post but when i run node examples/rtd2.js i get the following error

    module.js:340
    throw err;
    ^
    Error: Cannot find module ‘../config1′
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object. (D:\TestArea\twitter-bot-20-minutes-node-js\twitterbot\node_modules\twit\examples\rtd2.js:6:15)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

    any thougts ??

  • Steve - Reply

    October 10, 2013 at 5:29 pm

    This tool just invalidated the entire voting process for most network TV talent shows. Long live automation!

  • Christian Paulsen - Reply

    October 10, 2013 at 5:50 pm

    Greg:

    Thanks for the feedback. I hope to have another post up tomorrow that digs deeper into what you can do with a bot and the Twitter API.

    Umair Aslam:

    It can’t find your configuration file. Make sure you have it in the right spot and that the name matches whatever you have set in rt2d2.js.

  • Paul - Reply

    October 11, 2013 at 1:03 am

    A deeper look at the node code behind it would be nice (learning) and how would you go about getting it to retweet multiple, customizble twitter accounts?

    Thanks

  • Mohit Thakral - Reply

    October 11, 2013 at 4:27 am

    There are few things, missing first is example in “twit” has changed thats what the home page says. it needs config1 and config2.js. But, for this example I found it only needs config1.js. Second, the example is now returning 404 :(. Don’t know why. I am loooking into it.

    I tested my access and consumer key and token using twitter for mac client’s developer console and there it seems to work.

  • Adrian - Reply

    October 11, 2013 at 8:42 pm

    Running into a problem and not sure what’s wrong. Followed the workflow to set it all up. Paths, keys and access tokens all appear to be correct, but getting this when running: http://www.dazulu.com/nodebot.PNG

  • […] thing. I’m not sure where I should start but let me just start with twitter; it is possible to set up a twitter bot in 20 minutes  and it is almost common knowledge that fake twitter accounts is a huge money spinner . This […]

  • some - Reply

    November 20, 2013 at 6:03 pm

    Can you point me to a more detailed description of creating the twitter API? I don’t have a website to input and I’m stuck at this step:

    Twitter now requires authentication for all API calls, so we have to create an application which will provide us with some tokens that will allow us to utilize the API.

    Once you’ve created your application, go to the details tab and take a look at the OAuth settings. Copy the consumer key and consumer secret, as we’ll be needing those soon. Now go to the Settings tab. Under the header Application Type, select “Read, Write, and Access direct message”. This will give our bot free reign to access almost all of the API calls. Click the update button and go back to details.

    • Christian Paulsen - Reply

      November 23, 2013 at 7:58 pm

      I don’t know of a good API tutorial off the top of my head, but for what you’re trying to do you don’t need to have your own website. Yes, it forces you to enter a URL, but you can put any valid URL in there you want and it will still work.

  • James - Reply

    December 5, 2013 at 10:52 am

    Genius mate, really appreciated this. Wanted to get quick off the blocks and now to dive deeper and figure out the tricky stuff. big thank you.

  • Hernán Cussi - Reply

    December 17, 2013 at 6:55 pm

    Hi there,

    Great tutorial, I found it very interesting. One thing though, I’m getting this response from github when the bot it’s trying to tweet:

    allErrors: [ { message: 'Sorry, that page does not exist', code: 34 } ]

    Seems that something has changed in the github site that now the query that is being built it’s not longer valid…

    I’ll look into this but if you’ve already figured that out would be great :)

    Thanks, Hernán

  • Aaron - Reply

    December 25, 2013 at 1:15 am

    Is there a tutorial for windows?

  • Asim - Reply

    December 29, 2013 at 2:41 pm

    Once you’ve installed it, create a file called hello.js. Open it and enter:
    console.log(“Hi there, world”);

    Now, at the command prompt type:
    1

    node hello

    If you see “Hi there, world” in your terminal, then it worked.

    doesn’t work .

Please leave a Comment