Advertisement
Guest User

Untitled

a guest
May 23rd, 2017
560
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.58 KB | None | 0 0
  1. var fs = require('fs');
  2. var readline = require('readline');
  3. var google = require('googleapis');
  4. var googleAuth = require('google-auth-library');
  5. var atob = require('atob');
  6. var language = require('@google-cloud/language')({
  7. projectId: 'fine-balm-165720',
  8. keyFilename: 'MyProject.json'
  9. });
  10. global.fetch = require('node-fetch')
  11. var cc = require('cryptocompare')
  12.  
  13. // If modifying these scopes, delete your previously saved credentials
  14. // at ~/.credentials/gmail-nodejs-quickstart.json
  15. var SCOPES = ['https://mail.google.com/'];
  16. var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
  17. process.env.USERPROFILE) + '/.credentials/';
  18. var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';
  19.  
  20. // Load client secrets from a local file.
  21. fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  22. if (err) {
  23. console.log('Error loading client secret file: ' + err);
  24. return;
  25. }
  26. // Authorize a client with the loaded credentials, then call the
  27. // Gmail API.
  28. authorize(JSON.parse(content), listMessages);
  29. });
  30.  
  31. /**
  32. * Create an OAuth2 client with the given credentials, and then execute the
  33. * given callback function.
  34. *
  35. * @param {Object} credentials The authorization client credentials.
  36. * @param {function} callback The callback to call with the authorized client.
  37. */
  38. function authorize(credentials, callback) {
  39. var clientSecret = credentials.installed.client_secret;
  40. var clientId = credentials.installed.client_id;
  41. var redirectUrl = credentials.installed.redirect_uris[0];
  42. var auth = new googleAuth();
  43. var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
  44.  
  45. // Check if we have previously stored a token.
  46. fs.readFile(TOKEN_PATH, function (err, token) {
  47. if (err) {
  48. getNewToken(oauth2Client, callback);
  49. } else {
  50. oauth2Client.credentials = JSON.parse(token);
  51. callback(oauth2Client);
  52. }
  53. });
  54. }
  55.  
  56. /**
  57. * Get and store new token after prompting for user authorization, and then
  58. * execute the given callback with the authorized OAuth2 client.
  59. *
  60. * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
  61. * @param {getEventsCallback} callback The callback to call with the authorized
  62. * client.
  63. */
  64. function getNewToken(oauth2Client, callback) {
  65. var authUrl = oauth2Client.generateAuthUrl({
  66. access_type: 'offline',
  67. scope: SCOPES
  68. });
  69. console.log('Authorize this app by visiting this url: ', authUrl);
  70. var rl = readline.createInterface({
  71. input: process.stdin,
  72. output: process.stdout
  73. });
  74. rl.question('Enter the code from that page here: ', function (code) {
  75. rl.close();
  76. oauth2Client.getToken(code, function (err, token) {
  77. if (err) {
  78. console.log('Error while trying to retrieve access token', err);
  79. return;
  80. }
  81. oauth2Client.credentials = token;
  82. storeToken(token);
  83. callback(oauth2Client);
  84. });
  85. });
  86. }
  87.  
  88. /**
  89. * Store token to disk be used in later program executions.
  90. *
  91. * @param {Object} token The token to store to disk.
  92. */
  93. function storeToken(token) {
  94. try {
  95. fs.mkdirSync(TOKEN_DIR);
  96. } catch (err) {
  97. if (err.code != 'EEXIST') {
  98. throw err;
  99. }
  100. }
  101. fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  102. console.log('Token stored to ' + TOKEN_PATH);
  103. }
  104.  
  105. /**
  106. * Lists the messages content in the user's account.
  107. *
  108. * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
  109. * @param {labelIds} messages only from this label are displayed
  110. */
  111. var gmail = google.gmail('v1');
  112.  
  113. function listMessages(auth) {
  114. gmail.users.messages.list({
  115. auth: auth,
  116. userId: 'me',
  117. maxResults: '500',
  118. q: 'newsletter@coindesk.com',
  119. labelIds: 'INBOX'
  120. }, function (err, response) {
  121. if (err) {
  122. console.log('The API returned an error: ' + err);
  123. return;
  124. }
  125. var messages = response.messages;
  126. if (undefined !== messages && messages.length == 0) {
  127. console.log('Messages not found.');
  128. } else {
  129. getMessageBody(messages, auth)
  130. }
  131. });
  132. }
  133.  
  134. function getMessageBody(messages, auth) {
  135. if (undefined !== messages) {
  136. for (var i = 0; i < messages.length; i++) {
  137. var message = messages[i];
  138. gmail.users.messages.get({
  139. auth: auth,
  140. 'userId': 'me',
  141. 'id': message.id
  142. }, function (err, response) {
  143. if (err) {
  144. console.log('The API returned an error: ' + err);
  145. return;
  146. }
  147. var message = response.id
  148. //modifyMessage(message, auth); // Label change
  149. var body = response.payload.parts[0].body.data;
  150.  
  151.  
  152. var ss = language.detectSentiment(atob(body))
  153. .then((results) => {
  154. const sentiment = results[0];
  155.  
  156. //console.log(`Text: ${atob(body)}`); // VIEW TEXT MESSAGE
  157. console.log('ID:' + message + ` Sentiment score: ${sentiment.score}`);
  158. console.log(`Sentiment magnitude: ${sentiment.magnitude}`);
  159. console.log('');
  160.  
  161. })
  162. .catch((err) => {
  163. console.error('ERROR:', err);
  164. });
  165.  
  166. //CURRENT PRICE
  167. //var price = cc.price('BTC', ['USD', 'EUR'])
  168. // .then(prices => {
  169. // const price = prices;
  170. //})
  171.  
  172.  
  173. }
  174. );
  175. }
  176. }
  177. }
  178.  
  179. function modifyMessage(message, auth) {
  180. gmail.users.messages.modify({
  181. 'auth': auth,
  182. 'userId': 'me',
  183. 'id': message,
  184. 'resource': {
  185. "addLabelIds": [
  186. "Label_2"
  187. ],
  188. "removeLabelIds": [
  189. "INBOX"
  190. ]
  191. }
  192. }, function (err, response) {
  193. if (err) {
  194. console.log('The API returned an error: ' + err);
  195. return;
  196. }
  197. console.log('Success, label changed for message: ' + message)
  198. }
  199. );
  200. }
  201.  
  202.  
  203.  
  204. // TODO ADD EVERYTHING TO THIS FUCKING DATABASE
  205. function sql (){
  206. var pg = require('pg');
  207. var username = 'kfpyhrzizvnthq';
  208. var password = '23fb755df500316578d72b2a62b443e2d638e1b17e60407f1838804eba1d7897';
  209. var host = 'ec2-184-73-199-72.compute-1.amazonaws.com';
  210. var conStringPri = 'postgres://' + username + ':' + password + '@' + host +
  211. ':5432/d4et7h51ifgegu';
  212. pg.defaults.ssl = true;
  213.  
  214. var today = new Date().toISOString().
  215. replace(/T/, ' '). // replace T with a space
  216. replace(/\..+/, '') // delete the dot and everything after
  217.  
  218. pg.connect(conStringPri, function(err, client, done) {
  219. client.query('INSERT INTO antek(ID, DATE, SCORE, PRICE) values($1, $2, $3, $4)',
  220. [message, today, sentiment.score , price]);
  221.  
  222. }
  223.  
  224. );
  225. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement