Sentimental Analysis of Twitter posts using NodeJS & Google Language APIs

This post was inspired by Keith McNulty's post on medium. The idea is to further simplify the approach by using NPM packages to read twitter feed and then use Google Language APIs .

Sentimental Analysis of Twitter posts using NodeJS & Google Language APIs

This post was inspired by Keith McNulty's post on medium regarding sentimental analysis of twitter posts related to Australia's political situation. The idea is to further simplify the approach by using NPM packages to read twitter feed and then use Google Language APIs to get the score on the sentimental analysis of twitter post.

To start with, create a new NodeJS project using npm init.

Install, npm twitter package using npm install twitter.

To use this package, you need to create an app on https://developer.twitter.com/en/apps

Create the app and copy the required credentials to a safe location.

const Twitter = require('twitter');

let client = new Twitter({
    consumer_key: 'enter_your_consumer_key_here',
    consumer_secret: 'enter_your_consumer_secret_here',
    access_token_key: 'enter_your_access_token_key_here',
    access_token_secret: 'enter_your_access_token_secret_here'
  });

Use the above code in your node entry file, can be index.js or any other. Replace the twitter access credentials from the details you got from twitter app creation earlier.

client.get('search/tweets', {q: 'javascript', lang: 'en', count: 100, result_type: 'popular'}, async function(error, tweets, response) {
          console.log(tweets.statuses[0].text)
});

Use the above code to extract popular tweets for keyword 'javascript'. You can tweak the parameters as needed to get the exact set of tweets.

let options1 = { method: 'POST',
url: 'https://language.googleapis.com/v1beta2/documents:analyzeSentiment?key=enter_your_google_cloud_access_credentials_key',
      headers:
          {   'cache-control': 'no-cache',
              'content-type': 'application/json' },
      body:
          {
            'document':{
            'type':'PLAIN_TEXT',
            'content': tline
          }
        },
      json: true };

      request(options1, function (error, response, body) {
      if (body.error != 'undefined') {
        console.log(body.documentSentiment.score);
      } 
    });

On Google cloud, create credentials to use the language API. Replace the access key in the third line of the above code with the key obtained from Google Cloud. Also, you will have replace the 'PLAIN_TEXT' in the line 9 with the tweet extracted from the twitter in the earlier code. You can put them in loop and get score for each tweet extracted from the twitter.

Score : ranges from -1.0 (very negative) to 1.0 (very positive)

I have interests in Alexa, Angular / AngularJS, NodeJS, Ethereum Blockchain, ChatBOTS and many more. When not with technologies, sing & play guitar. Read more post at http://www.dudistan.com/