Skip to content

Commit

Permalink
Merge pull request #1 from PLG-Works/poc
Browse files Browse the repository at this point in the history
Version 1.0.0
  • Loading branch information
kedarchandrayan authored Jun 16, 2022
2 parents cfa0b04 + c9cf596 commit f968acc
Show file tree
Hide file tree
Showing 21 changed files with 2,366 additions and 1 deletion.
94 changes: 94 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
module.exports = {
env: {
browser: true,
es6: true,
node: true
},
extends: 'eslint:recommended',
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly'
},
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module'
},
rules: {
'linebreak-style': ['error', 'unix'],
quotes: ['error', 'single'],
semi: ['error', 'always'],
'no-var': 'error',
'block-scoped-var': 'error',
curly: 'error',
'default-case': 'error',
'dot-notation': 'error',
'no-empty-function': 'error',
'no-else-return': 'error',
'no-eval': 'error',
'no-extra-bind': 'error',
'no-extra-label': 'error',
'no-implied-eval': 'error',
'no-invalid-this': 'error',
'no-multi-spaces': 'error',
'no-new': 'error',
'no-new-func': 'error',
'no-new-wrappers': 'error',
'no-return-assign': 'error',
'no-return-await': 'error',
'no-self-compare': 'error',
'no-sequences': 'error',
'no-throw-literal': 'error',
'no-useless-call': 'error',
'no-useless-catch': 'error',
'no-useless-concat': 'error',
'no-with': 'error',
'no-void': 'error',
'prefer-promise-reject-errors': 'error',
yoda: 'error',
'prefer-const': 'error',
//"prefer-arrow-callback": "error",
'handle-callback-err': 'error',
'no-async-promise-executor': 'error',
'no-case-declarations': 'error',
'no-shadow': 'error',
'no-undef-init': 'error',
'no-undefined': 'error',
'no-use-before-define': 'error',
'no-new-require': 'error',
'no-process-env': 'error',
// 'no-sync': 'error',
strict: 'error',
'arrow-spacing': 'error',
'no-floating-decimal': 'error',
'no-buffer-constructor': 'error',
// "no-mixed-requires": ["error", { "grouping": true }],
'max-classes-per-file': ['error', 1],
'arrow-body-style': ['error', 'as-needed'],
'no-confusing-arrow': ['error', { allowParens: true }],
'no-duplicate-imports': 'error',
'no-useless-computed-key': 'error',
'no-useless-constructor': 'error',
'no-useless-rename': 'error',
// "prefer-destructuring": "error",
// "prefer-template": "error",
'capitalized-comments': ['error'],
'consistent-this': ['error', 'oThis'],
'eol-last': ['error', 'always'],
'id-length': ['error', { min: 2 }],
'key-spacing': ['error', { beforeColon: false, afterColon: true }],
'lines-around-comment': ['error', { beforeBlockComment: false, beforeLineComment: false }],
'lines-between-class-members': ['error', 'always'],
'no-array-constructor': 'error',
'max-depth': ['error', 4],
'max-lines-per-function': ['error', { max: 80, skipBlankLines: true, skipComments: true }],
'no-lonely-if': 'error',
'no-multiple-empty-lines': 'error',
'no-negated-condition': 'error',
'no-new-object': 'error',
'no-trailing-spaces': 'error',
'no-unneeded-ternary': 'error',
'operator-assignment': ['error', 'always'],
'padding-line-between-statements': ['error', { blankLine: 'always', prev: '*', next: 'return' }],
'spaced-comment': ['error', 'always', { exceptions: ['-', '+'] }]
}
};
84 changes: 84 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock
package-lock.json

# SDK
/.idea
/.idea/*
.DS_Store

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Test Folder
test/

# Dev Folder
.dev

# Debug log from npm
npm-debug.log
.vscode

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# Editor / IDE files
/.idea
/.idea/*
.vscode

# Report files
/reports
/reports/*

12 changes: 12 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"printWidth": 120,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": true,
"arrowParens": "always",
"parser": "flow",
"proseWrap": "preserve"
}
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## Brand-Monitoring v1.0.0
This is the very first release of this package.
- getStats method added which gives NPS results for a twitter account.

9 changes: 9 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright © 2022 PLG Works

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
88 changes: 87 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,87 @@
# brand-monitoring
# Brand Monitoring
![npm version](https://img.shields.io/npm/v/@plgworks/brand-monitoring.svg?style=flat)

Brand Monitor helps you understand your twitter audience better. This module provides you with number of promoters & detractors, [Net Promoter Score (NPS)](https://en.wikipedia.org/wiki/Net_promoter_score) and the total number of tweets within a particular time duration.

## Approach

Using [Twitter API](https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-mentions), we gather the tweet mentions of a particular account. These tweets are searched within a given time duration. Sentiments analysis of these tweets is done using [AWS Comprehend](https://docs.aws.amazon.com/comprehend/latest/dg/API_BatchDetectSentiment.html), to gather promoters and detractors.

## Prerequisites
- [Twitter Developer App](https://developer.twitter.com/en/docs/twitter-api/getting-started/getting-access-to-the-twitter-api)
- [AWS Comprehend](https://docs.aws.amazon.com/comprehend/index.html)

## Install

```shell script
npm install @plgworks/brand-monitoring --save
```

## Initialize
```js
const BrandMonitoring = require('@plgworks/brand-monitoring');

const twitterApiConfig = {
bearerToken: '<bearerToken>'
};

const awsComprehendConfig = {
region: '<region>',
accessKeyId: '<accessKeyId>',
secretAccessKey: '<secretAccessKey>'
};

const brandmonitoring = new BrandMonitoring(twitterApiConfig, awsComprehendConfig);
```

### Initialization Params
- **twitterApiConfig** Object which has following key(s).

- **bearerToken**: Used to have a more secure point of entry to use Twitter APIs, and can be obtained from the developer portal inside the keys and tokens section of your Twitter App's settings.

- **awsComprehendConfig** Object which contains AWS Comprehend access credentials. It has following keys.

- **region**: AWS region.
- **accessKeyId**: AWS uses this to verify your identity and grant or deny you access to specific resources.
- **secretAccessKey**: AWS uses this to verify your identity and grant or deny you access to specific resources.

## Get Statistics
Once the Brand Monitoring module is initialized, the next step is to perform sentimental analysis on tweets.

```js
const reportParams = {
twitterUsername: '<twitterUsername>',
startTimestamp: '<startTimestamp>',
endTimestamp: '<endTimestamp>',
awsThreshold: {
positive: '<positive>',
negative: '<negative>'
}
};

const stats = await brandmonitoring.getStats(reportParams).catch(function(err) {
console.log('Error:: --------- ', err);
});
```

**reportParams** Object with following keys.
- **twitterUsername**: Twitter username for which you want to generate the stats. Example: @PLGWorks
- **startTimestamp**: Start timestamp used to search tweets
- **endTimestamp**: End timestamp used to search tweets
- **awsThreshold**: (Optional) Object which contains AWS Comprehend sentiment score threshold values. Default positive value is 0.55 and negative value is 0.40
- **positive**: Range is from 0 to 1. If sentiment is positive and the sentiment score is greater than this threshold, then we consider the tweet as positive (i.e. promoter).
- **negative**: Range is from 0 to 1. If sentiment is negative and the sentiment score is greater than this threshold, then we consider the tweet as negative (i.e. detractor).

## Success Response
`getStats` method returns a promise which returns a stats object as shown in the following.
```js
console.log(stats);

// stats is a object which looks like this:
// {
// nps: -8.333333333333336,
// promotersCount: 14,
// detractorsCount: 21,
// totalTweets: 84
// }
```
1 change: 1 addition & 0 deletions VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1.0.0
35 changes: 35 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const rootPrefix = '.',
GetStats = require(rootPrefix + '/lib/GetStats'),
configProvider = require(rootPrefix + '/lib/configProvider');

/**
* Class exposed by this package
*
* @class BrandMonitoring
*/
class BrandMonitoring {
constructor(twitterApiConfig, awsComprehendConfig) {
// Saving the params in-memory via configProvider
configProvider.setConfig('twitterApiConfig', twitterApiConfig);
configProvider.setConfig('awsComprehendConfig', awsComprehendConfig);
}

/**
* Get statistics.
*
* @return {Promise<void>}
*/
getStats(reportParams) {
const params = {
twitterUsername: reportParams.twitterUsername,
startTimestamp: reportParams.startTimestamp,
endTimestamp: reportParams.endTimestamp
};

configProvider.setConfig('awsThreshold', reportParams.awsThreshold);

return new GetStats(params).perform();
}
}

module.exports = BrandMonitoring;
Loading

0 comments on commit f968acc

Please sign in to comment.