a blog for those who code

Sunday 24 July 2016

How to create Simple Twitter Bot in Node.js

In this post we will be discussing about creating a Twitter Bot in Node.js which will run at a specific time of the day or lets say every half an hour. A twitter-bot is a bot program used to produce automated posts on the Twitter micro blogging service.

Create Twitter Application

At first you need to create an application in Twitter. Go to http://dev.twitter.com/apps and login to your twitter account, you will see something like below.

It will ask you to create a new Twitter App. Once created you can see screen containing OAuth settings. We will need Consumer Key (API Key) and Consumer Secret (API Secret) from this page.

ALSO READ : How to fetch trending tweets in Nodejs

Install Cron and Twit

To create a Twitter Bot we have to install two packages Cron (Cron jobs for your node) and Twit (Twitter API client for node which supports both REST and Streaming API) as shown below :

Code to create Twitter Bot in Node.js

var cronJob = require('cron').CronJob;
var Twit = require('twit');

var twitterBot = new Twit({
  consumer_key: 'your_consumer_key',
  consumer_secret: 'your_consumer_secret_key',
  access_token: 'your_access_token',
  access_token_secret: 'your_access_token_secret'

var job = new cronJob({
    cronTime: '0 */30 * * * *',
    onTick: function() {
          {status: 'Coding Defined Blog at http://www.codingdefined.com'},
  function(err, data, response) {
    start: true,
    timeZone: 'Asia/Kolkata'


ALSO READ : How to Get Latest Tweets of a particular HashTag using Nodejs

In the above code at first we have created a new instance of Twit with our consumer key and access token key. Then we have started our Cron job which will run every 30 minutes and it will post an status in our Twitter account. We have setup start as true, which means posting in twitter will start as soon as the Cron job gets started.

Once successfully ran you will see an output as shown below ;

You can verify the status at the Twitter like below :

Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.


  1. Is there a way to get it to post a different link from the same blog each post? Or a random one, even if it repeats from time to time?

    1. Yes, it can be done. One method is to create a list of random tweets and then tweet it using Cron. Another method is to take advantage of retweets