Create your very own Twitter bot that runs on Node.js

I thought to myself a while ago that I wanted to try to create an automated twitter bot and see how many followers I could get. I also wanted to find out what I could actually automate and how to put the pieces together. This bot will randomly tweet things as well as follow and un-follow people. Near the end of this post I’ll tell you the name of my bot so you can see the output and maybe even follow my awesome tweets!

Thank you to The appcoder Article “A Twitter bot in 20 Minutes” for giving me a good starting point to base my bot on.

NODE.JS INSTALLATION STEPS

Make sure you are in the root directory you want to run out of. I run my tests out of my /home/[username]/codetests folder.  This is the foundation that you will need to have to get the rest of this project working.

Go to http://nodejs.org/ and download it and install it.

My Set up is

  •  CentOS 6.4 Hosted VPS
  •  1 processor
  • 4 GB RAM

Make sure you have npm installed on the server for installing the twit and chance modules. I would like to point out that you don’t really need a beefy server to do this with. In fact I am using a server that hosts some other applications I am playing around with to run this on. It barely even shows up when checking on running processes.

 INSTALLING THE TWIT AND CHANCE MODULE

The first thing we need is a Twitter API library so we can actually make API calls in our project.  Let’s create a directory called twit under the node_modules folder. Go the that directory in your terminal. Node.js has a package manager called npm.Let’s start by installing the twit module:

 INSTALL THE TWIT MODULE

Make sure you are in the node_modules folder. When you install Node it creates a folder called node_modules any new modules will be installed under that folder structure.
So for example I have node installed at :

/home/[username]/codetests

so what shows up is a folder called

/home/[username]/codetests/node_modules .

If you cd into node_modules and then install the twit and chance modules you will be just fine. Thats how I did it.
The command to install twit is :

npm install twit

Once the install is all done you’ll end up with something looking like the following:

+– node_modules
+– twit
+– examples
    +– bot.js
    +– rtd2.js
+– A bunch more folders
+– More Folders

The command to install chance is :

npm install chancejs

Once the install is all done you will end up with:

+– node_modules
+– twit
+– examples
    +– bot.js
    +– rtd2.js
+– chance

TIME TO GO AND CREATE A NEW TWITTER ACCOUNT

DO NOT USE YOUR OWN ACCOUNT FOR THIS!!!!!!!  REMEMBER, WE ARE MAKING A BOT

Your account may be banned, it could somehow anger other twitter users and get spammed or who knows what else bad could happen. To protect yourself, go make a new Gmail account, create a new twitter account and use that email for the account information. I feel the less connection it has to you the better. After creating your Twitter account manually start following a few people. The bot is written to look at the people you follower and follow their followers so if you have zero people you follow it will throw an error and just not work right ( except for the chance part of it ).

 GET YOUR TWITTER API KEYS

Head over to https://dev.twitter.com/. Sign in with the Twitter account you created above and click on the area in the lower right called “Get started with the platform“.  On the page that comes up in the lower right again there is a section for the Rest API . in the rest API list click on “Manage & create your applications” to get to the page where you can set up the API keys you will need.

Twitter requires authentication for all API calls and now you will be creating a few keys that tell Twitter that you are authorized to use their API. In the application area you will have a section for OAuth settings. This is where you get your consumer key and consumer secret. Copy both the Consumer Key and Consumer Secret to notepad or your favorite text editor. In the Settings tab you will see a few check boxes for Application Type, you want to select “Read, Write, and Access direct message”. Click the save/update button and go back to your details view.

Scroll to the bottom of the page and you will see a button to create an access token. Once you click this I found that I had to click around on the site including going back to the OAuth tab a few times until it finally showed up. You will now see an “Access token” and an “Access token secret”. Copy these as well underneath the other two keys you put in that text file.

You just created a Twitter Application! Yay! You have the actual Twitter user account and you also have a new registered application. This means that you can make API calls either as a user or as an application!

RUNNING THE BOT

We are almost ready to start running the Twitter bot.  Go to the node_modules/twit folder and create your Twitter Bot config file.

Remember those keys we copied before when you created the Twitter Application?  Well, here is where we actually start using them. Create a file called config1.js. The twit README.md file in the root directory will show you the proper format for the config file, but it should look similar to the below:

module.exports = {
consumer_key: ‘[CONSUMER_KEY]’
, consumer_secret: ‘[CONSUMER_SECRET]’
, access_token: ‘[ACCESS_TOKEN]’
, access_token_secret: ‘[ACCESS_TOKEN_SECRET]’
}

Take the information you put in the text file from the Twitter application creation page or copy it directly from the page into that file replacing the keys and the secrets in the square bracketed areas. Once you have that information put into the config file save it and get ready to run a test bot for the first time!

Implementing CHANCEJS into the bot

The original article I referenced above and in this post created the bot to friend other friends, un-follow people not following you back and tweet from an RSS feed. I thought , what if I could randomly create tweets and  re-tweet based on search criteria while also adding in some following and un-following to the mix.  To that end I created the following script you can try out and change as much as you want. I instantiate the chance library we installed above and then use the built in funtions to create my random tweets from!

For example to tweet a randomly created hashtag I did the following:

var chance = new Chance();
var my_random_hashtag = chance.hashtag();

var params = ‘Lets trend this random Hashtag! ‘ + my_random_hashtag
bot.tweet(params, function(err, reply) {
if(err) return handleError(err);
});

Its really just that simple! you can see the full list of parameters you can randomly create on the chancejs website .

THE CHANCE BOT

Download the file here :chancebot

//
// Twitter bot using Chance node library that tweets about random things
// Also makes new friends and prunes its followings.
//
// Load Chance
var Chance = require(‘../../chance/chance’); // load chance

var Bot = require(‘./bot’)
, config1 = require(‘../config1’);

var bot = new Bot(config1);

console.log(‘Chancebot: Running.’);

//get date string for today’s date (e.g. ‘2011-01-01’)
function datestring () {
var d = new Date(Date.now() – 6*600*60*1000); //est timezone
return d.getUTCFullYear() + ‘-‘
+ (d.getUTCMonth() + 1 ) + ‘-‘
+ d.getDate();
};

console.log(datestring());

setInterval(function() {
bot.twit.get(‘followers/ids’, function(err, reply) {
if(err) return handleError(err)
});

var rand = Math.random();

if(rand <= 0.10) { // Chance color

// Instantiate Chance so it can be used
var chance = new Chance();
var my_random_color = chance.color();

var params = ‘New Random Web color: ‘ + my_random_color
bot.tweet(params, function(err, reply) {
if(err) return handleError(err);
});
}

else if(rand <= .20) { // chance Hashtag

// Instantiate Chance so it can be used
var chance = new Chance();
var my_random_hashtag = chance.hashtag();

var params = ‘Lets trend this random Hashtag! ‘ + my_random_hashtag
bot.tweet(params, function(err, reply) {
if(err) return handleError(err);
});
}
else if(rand <= .30) { // retweet based on search
var params = {
q: “#geek”
, since: datestring()
, result_type: “mixed”
};

bot.retweet(params, function(err, reply) {
if(err) return handleError(err);
});
}
else if(rand <= .40) { // Chance D20

// Instantiate Chance so it can be used
var chance = new Chance();
var my_random_dice = chance.d20();

var params = ‘Just Rolled a D20 and got: ‘ + my_random_dice
bot.tweet(params, function(err, reply) {
if(err) return handleError(err);
});
}

else if(rand <= .50) { // prune a follower

bot.prune(function(err, reply) {
if(err) return handleError(err);
var name = reply.screen_name
});
}

else if(rand <= .60) { // follow someone

bot.mingle(function(err, reply) {
if(err) return handleError(err);
var name = reply.screen_name;
});
}

else if(rand <= .70) { // Chance Twitter

// Instantiate Chance so it can be used
var chance = new Chance();
var my_random_tweeter = chance.twitter();

var params = ‘Random Twitter handle I thought of ‘ + my_random_tweeter
bot.tweet(params, function(err, reply) {
if(err) return handleError(err);
});
}

else if(rand <= .80) { // Chance Domain

// Instantiate Chance so it can be used
var chance = new Chance();
var my_random_domain = chance.domain();

var params = ‘Random domain Name I thought of ‘ + my_random_domain
bot.tweet(params, function(err, reply) {
if(err) return handleError(err);
});
}

else if(rand <= .90) { // Chance Phone

// Instantiate Chance so it can be used
var chance = new Chance();
var my_random_phone = chance.phone();

var params = ‘is this a real number? ‘ + my_random_phone
bot.tweet(params, function(err, reply) {
if(err) return handleError(err);
});
}

else { // Chance zipcode

// Instantiate Chance so it can be used
var chance = new Chance();
var my_random_zipcode = chance.zip();

var params = ‘Random zipcode! ‘ + my_random_zipcode
bot.tweet(params, function(err, reply) {
if(err) return handleError(err);
});
}
}, 187523);

function handleError(err) {
console.error(‘response status:’, err.statusCode);
console.error(‘data:’, err.data);
}

RUN YOUR BOT

Now that you have the config1.js file saved in the node_modules/twit folder all you need to do is to copy my script above (the the file from here –> chancebot ) to the examples folder and run it (It assumes you are in the /node_modules/twit folder already). Make sure you change the .txt extension to a .js extension!

node examples/chancebot.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 187523 (3.12538333 minutes) to  40000 (40 seconds) or to something smaller, like 10000 (10 seconds). You could get banned by “spam tweeting” so I picked my number to eliminate that issue. feel free to change it to whatever you want though.

 WHAT ARE THE THINGS ITS DOING?

I have my bot do a few things:

  1. Tweet a random web color
  2. Tweet a random Hashtag i.e. #blort
  3. Retweet something based on a search string
  4. Roll a D20 Dice and tweet the result
  5. Unfollow someone not following back
  6. Follow someone from your followers list
  7. Tweet a Random generated Twitter Handle “@Someone”
  8. Tweet a Random Domain Name i.e. gerfliam.io
  9. Tweet a Random phone number i.e. 588-984-2818
  10. Tweet a Random zipcode i.e. 98271

I initially assign a random number from zero to 1.00 and I gave each of the above 10 items a 10% chance of happening.

And that’s it! you can see my Bot in action on Twitter at @G33k3rGeek .  I am amazed that I have over 13k tweets so far and 1600+ followers ( most I assume are other bots to be honest)

botstats

Thanks for reading this far!

 

Blogging is not dead. Its just a flesh wound

I just fired up Techmeme.com a few moments ago while waiting on a conference call to call me back. I blinked twice at the headlines of “Blogging Wanes as the Young Drift to Sites Like Twitter”. I nearly did a double take.

I pour a lot of my time and energy into my Podcast and creating a (hopefully) quality and fun product you can either gain some knowledge from or just laugh at and get some enjoyment out of a middle age guy trying to be nerdy and hip at the same time. Part of the show is not just the links to the mp3 and now videos. This URL at GeekTechLive.com I want to be your one stop shop for finding out whats rolling around in that vast ( because of the air) noggin of mine.  It was because of this that my heart nearly sunk all the way to my feet as I read that Blogs are dead…. Oh well Pack er in boys! Looks like I’m done.

Or am I?

On further study of the article I noticed a few points that should come to mind even if you don’t have a copy of  “how to lie with statistics” lying around for reference material. Most of the article is focusing on the youth of the world not blogging much anymore and doing more BookFacing and Tweetering and playing loud music and doing donuts on lawns, whatever that is. When I was in there “target crowd”  of  12-17 (here is where I date myself) I had more important things to do than Blog or game or chat up people I don’t know on Twittering BookFace. In fact there was no Internet and I usually was outside “doing” something.  Along comes solid state though and we all move indoors where its safe.

The thing is that if you read this article and assume that the Headline is inflammatory and meant to grab you you are right. The Times is right that the 12-17 crowd is more digitally social now and less blogified. But like I said, I was that age once and I was lazy at that age and If I had the choice of writing what I am writing now or summing it down to 140 characters I would be tweeting something like “Bl0ggin is Ded LOLz, chk out Times Article! LOLZ”. so there. I get it , but don’t go and over simplify the picture. As it turns out the full study done on blogging ends up showing that overall  young adults are doing less but people in the 30+ category (i.e. me) are actually doing more.

So Blogging is not Dead… its just a flesh wound.

Based in part on my reading of the Tech Meme Article on “Blogs wane and the young drift to sites like Twitter” here http://techme.me/BC0F

Nominate me for the 2011 Shorty Awards!

Geekulators! Mount up!

The ballot boxes are open people and I would really appreciate any support you can do for the show.  I know I have asked you to tell all your friends and follow me on twitter, use my coupon codes, even donate any spare dollar you have lying around via paypal, and now finally to tune into the Ustream live show for some up close and personal interactivity.

I have one more thing I need you to do for me. Please, Please, Please, If you like my show Go to http://shortyawards.com/geektechlive?category=tech and vote for me. I would greatly appreciate any and all support you can offer me. I think I have really brought some fun and excitement into the Tech and Entertainment categories with my podcast and now streaming broadcast and I hope you do too, so please take 30 seconds and click the link below and cast your vote for me for the 2011 Shorty Awards?

Thanks and see you all online weekly for more fun and chat about all things tech.

Nominate Chris Favero for a social media award in the Shorty Awards!Nominate Chris Favero for a social media award in the Shorty Awards tech category