a blog for those who code

Wednesday, 18 May 2016

How to Get Latest Tweets of a particular HashTag using Nodejs

In this post we are going to discuss about getting latest tweets of a particular hashtag using Node.js. Many online entities like twitter, facebook etc. format their response either in JSON or XML when exposing the APIs to the developers. In this post we will create an application in Nodejs where we will make requests to Twitter's Rest Service to get the current tweets of a particular hashtag.

Before going through the code I strongly recommend you to go through How to fetch trending tweets in Nodejs and Fetching Twitter Trends by places in Node.js which will give you a basic idea of how to get Consumer Key and Consumer Secret Key from Twitter Apps. For this example we have used hashtag : #SayItWithHugs

Code :

var https = require('https');
var headers = {
  'User-Agent': 'Coding Defined',
  Authorization: 'Bearer ' + require('./oauth.json').access_token
};

function jsonHandler(response, callback) {
  var json = '';
  response.setEncoding('utf8');
  if(response.statusCode === 200) {
    response.on('data', function(chunk) {
      json += chunk;
    }).on('end', function() {
      callback(JSON.parse(json));
    });
  } else {
    console.log('Error : ' + reseponse.statusCode);
  }
};

var trendOptions = {
  host: 'api.twitter.com',
  path: '/1.1/trends/place.json?id=23424848',
  headers: headers
};

var tweetDetails = {
  maxresults: 100,
  resultType: 'recent',
  options: {
    host: 'api.twitter.com',
    headers: headers,
  }
};

function callTwitter(options, callback){
  https.get(options, function(response) {
    jsonHandler(response, callback);
  }).on('error', function(e) {
    console.log('Error : ' + e.message);
  })
};

function fullTweetPath(query) {
  var path = '/1.1/search/tweets.json?q=%23SayItWithHugs';
  tweetDetails.options.path = path; 
};

callTwitter(trendOptions, function(trendsArray) {
  fullTweetPath();
  callTwitter(tweetDetails.options, function(tweetObj) {
    tweetObj.statuses.forEach(function(tweet) {
      console.log('\n' + tweet.text);
    })
  })
});

If you go through the above code, we have created a POST request with headers like user-agent, authorization, content-type and content-length. When we are getting a response with the status code of 200 ,we are adding the response to the oauthJsonFile (oauth.json). The oauth.json file will look like below

{"token_type":"bearer","access_token":"<Your_Unique_Access_Token>"}

We have created a function called jsonHandler() which will receive the response stream and convert JSON to object. Then we have created trendOptions object which will provide settings relevant to the Twitter API. As you can see in the path we have added an Id which is nothing but the places Id of India. The place_id is a place in the world. These IDs can be retrieved from geo/reverse_geocode.

Then we will create a function called callTwitter() which will show the tweets. When we run the above code we will get the result as :


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

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License