Skip to content

Instantly share code, notes, and snippets.

@Hiteshm01
Last active June 17, 2016 18:52
Show Gist options
  • Save Hiteshm01/d7adb3a1259cd3700e89007cd8027621 to your computer and use it in GitHub Desktop.
Save Hiteshm01/d7adb3a1259cd3700e89007cd8027621 to your computer and use it in GitHub Desktop.
var Twitter = require('twitter');
var Sentiment = require('sentiment');
var debug = require('debug')('stream');
var request = require('request');
var config = {
consumer_key: '<Please your tokens here>',
consumer_secret: '<Please your tokens here>',
access_token_key: '<Please your tokens here>',
access_token_secret: '<Please your tokens here>',
};
var BrandTweet = {
streamData: function() {
// Counter variable to keep a count of each emotion
var counter = {
flipkart: {
total: 0,
postive: 0,
negative: 0
},
paytm: {
total: 0,
postive: 0,
negative: 0
},
snapdeal: {
total: 0,
postive: 0,
negative: 0
},
amazon: {
total: 0,
postive: 0,
negative: 0
},
};
// Initialze client with developer keys
var client = new Twitter(config);
// Create a stream object from client specifying filtering on statuses
var stream = client.stream('statuses/filter', {
// and specify brands which you want to monitor, in comma seperated keywords
track: 'flipkart,paytm,snapdeal,amazon'
});
// Use data event tracker for stream listener to listen to real time tweets on mentioned brand name mentions
stream.on('data', function(tweet) {
// Pass tweet text to Sentiment library for analysis
Sentiment(tweet.text, function(err, res) {
var state;
// Result from sentiment library is negative for negative sentiments and postive for postive sentiments, update accordingly
if (res.score > 0) {
state = 'Positive';
debug(state + ' - ' + tweet.text);
} else if (res.score < 0) {
state = 'Negative';
debug(state + ' - ' + tweet.text);
} else {
state = 'Cant say';
}
try {
// Update individual object of counter for analysis later
if (tweet.text.toLowerCase().indexOf('flipkart') > -1) {
updateCounter(counter, 'flipkart', state);
} else if (tweet.text.toLowerCase().indexOf('paytm') > -1) {
updateCounter(counter, 'paytm', state);
} else if (tweet.text.toLowerCase().indexOf('snapdeal') > -1) {
updateCounter(counter, 'snapdeal', state);
} else if (tweet.text.toLowerCase().indexOf('amazon') > -1) {
updateCounter(counter, 'amazon', state);
}
} catch (e) {}
console.log(JSON.stringify(counter, null, 4));
});
});
stream.on('error', function(error) {
throw error;
});
}
};
function updateCounter(counter, key, state) {
counter[key].total++;
if (state === 'Positive') {
counter[key].postive++;
} else if (state === 'Negative') {
counter[key].negative--;
}
}
module.exports = BrandTweet;
(function() {
if (require.main === module) {
BrandTweet.streamData();
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment