Advertisement
jbjares2

sefanodejsapp

Jun 3rd, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.69 KB | None | 0 0
  1. 'use strict'
  2. /*eslint-disable no-param-reassign */
  3.  
  4. /* TODO Evitar if/else, utilizar mais comentarios e logar a aplicacao por inteira */
  5. /* TODO Modularizar a aplicacao para que cada funcionalidade possua seu proprio modulo a ser chamado como uma API */
  6. /* TODO Realizar teste para identificar como distiguir um usuari ocorretamente, se atraves do envent, entry, ou message ID para que as conversas nao sejam confundidas ou misturadas quando muitos usuarios estiverem acessando no mesmo momento */
  7. /* Importar libs */
  8. var express = require('express');
  9. var request = require('request');
  10. var bodyParser = require('body-parser');
  11. var watson = require('watson-developer-cloud');
  12. var SyncPromise = require('sync-promise');
  13. var app = express();
  14.  
  15. /* Define variaveis Globais */
  16. var contexid = {};
  17. var name = "";
  18. var conversation_id = "";
  19. //var sender = "";
  20. //var event = "";
  21.  
  22.  
  23. /* Define funcoes globais para tratamento do body de mensagens */
  24. app.use(bodyParser.urlencoded({ extended: false }));
  25. app.use(bodyParser.json());
  26.  
  27.  
  28. /* Define as variaveis de integracao com o Watson Assistant */
  29. var w_conversation = watson.conversation({
  30. url: 'https://gateway.watsonplatform.net/assistant/api',
  31. username: process.env.CONVERSATION_USERNAME || '9038adb5-b39b-4e9c-9c28-6cfb885e59fe',
  32. password: process.env.CONVERSATION_PASSWORD || 'AOxL2SCRwePZ',
  33. version: 'v1',
  34. version_date: '2016-07-11'
  35. });
  36. var workspace = process.env.WORKSPACE_ID || 'ab096c7d-f28c-41c2-b4cf-0d148af91d35';
  37.  
  38.  
  39. /* Define o metodo utilizado para configurar o webhook do Facebook - Utilizado unicamente no momento de configuracao da pagina do Facebbok */
  40. app.get('/webhook/', function (req, res) {
  41. if (req.query['hub.mode']==='subscribe' && req.query['hub.verify_token'] === 'teste') {
  42. res.status(200).send(req.query['hub.challenge']);
  43. }else{
  44. res.send('Erro de validação no token.');
  45. }
  46.  
  47. });
  48.  
  49. /* 1 */
  50. /* Funcao para realizar chamada rest para o facebook retornar o nome do usuario */
  51. var obterNomeusuarioDoFacebookAtravesDeChamadaRest = function(sender){
  52. request({
  53. url: 'https://graph.facebook.com/v3.0/'+ sender +'?fields=first_name',//v2.6
  54. qs: {access_token: token},
  55. method: 'GET'
  56. },
  57. function(error, response, body) {
  58. if (error) {
  59. console.log('Error sending message: ', error);
  60. } else if (response.body.error) {
  61. console.log('Error: ', response.body.error);
  62. }else{
  63. name = JSON.parse(body).first_name;
  64. console.log('User name:',name);
  65. }
  66. });
  67. }
  68.  
  69. /* 2 */
  70. /* Define o metodo utilizado para receber e tratar as mensagens vindas do facebook que irao ser enviadas ao Watson Assistant */
  71. /* Sempre passa por aqui assim que recebe uma mensagem do Facebbok e antes de chamar o W. Assistant */
  72. app.post('/webhook/', function (req, res) {
  73.  
  74. /* reseta as variaveis globais que devem ser especificas por usuario */
  75. var sender = null;
  76. var text = null;
  77. var name = null;
  78. var params = {};
  79.  
  80. /* Obtem o evento que contem a mensagem e outras informacoes enviadas pelo Facebook */
  81. var messaging_events = req.body.entry[0].messaging;
  82.  
  83.  
  84. //for (var i = 0; i < messaging_events.length; i++) {
  85.  
  86. /* Apos receber o evento trata a mensagem classificando por tipo */
  87. /* TODO Muito importante: descobrir como definir um ID unico para a conversacao do usuario, bem como o por que destes IDs estarem variando */
  88. var entry = req.body.entry[0];
  89. var event = req.body.entry[0].messaging[0];
  90. sender = event.sender.id;
  91.  
  92. if (event.message && event.message.text) {
  93. text = event.message.text;
  94. }
  95. if (event.postback && !text) {
  96. text = event.postback.payload;
  97. }
  98. if (event.message && event.message.attachments) {
  99. text = "A Aplicacao nao esta preparada para receber attachments!";
  100. }
  101.  
  102.  
  103. var payload = {
  104. workspace_id: workspace_ID //Watson Assistant Wokspace ID
  105.  
  106. };
  107.  
  108. params = {
  109. input: text,
  110. context:contexid
  111. };
  112.  
  113. if (params) {
  114. if (params.input) {
  115. params.input = params.input.replace("\n"," ");
  116. payload.input = { "text": params.input };
  117. }
  118. if (params.context) {
  119. payload.context = params.context;
  120. }
  121. }
  122. callWatson(payload, sender);
  123. //}
  124. res.sendStatus(200);
  125. });
  126.  
  127. function callWatson(payload, sender) {
  128. w_conversation.message(payload, function (err, convResults) {
  129. console.log(convResults);
  130.  
  131. if(convResults==null || convResults == undefined){
  132. return;
  133. }
  134. contexid = convResults.context;
  135.  
  136. if(convResults!=null && convResults != undefined){
  137. /* TODO Sincronizar chamada para que o nome do usuario seja chamado de forma sincrona e em seguinda o trecho de codigo que realiza a chamda ao W. Assistant e trata a mensagem */
  138. //obterNomeusuarioDoFacebookAtravesDeChamadaRest(sender);
  139. }
  140.  
  141. /* TODO encapsular os trecho de codigo abaixo da mesma forma que o treho que realiza a consulta ao nome do usuario e organizar dentro de uma chamda sincrona para que um execute somente apos o retorno do outro */
  142. /* Inicio do trecho de codigo que realiza a chamda ao W. Assistant e trata a mensagem */
  143. if(convResults.context !== null){
  144. conversation_id = convResults.context.conversation_id;
  145. }
  146.  
  147. if(convResults !== null && convResults.output !== null){
  148. var i = 0;
  149. while(i < convResults.output.text.length){
  150. if(convResults.output.context!=null && convResults.output.context != undefined && convResults.intents[0]!=null && convResults.intents[0]!= undefined){
  151. console.log("Context e Intents vindos do Watson Assistant nao sao nulos ou vazios. Retorno normal, completa.");
  152.  
  153. sendMessage(sender, convResults.output.text[i++], convResults.output.context, convResults.intents[0].intent); //***sendMessage(sender, convResults.output.text[i++],convResults.title);
  154. }
  155. if((convResults.output.context==null || convResults.output.context == undefined) && (convResults.intents[0]!=null && convResults.intents[0]!= undefined)){
  156. //console.log("Context nulo e Intents nao nulo vindos do Watson Assistant. Retorno apenas baseado em intents. ");
  157. //sendMessage(sender, convResults.output.text[i++], convResults.intents[0].intent); //***sendMessage(sender, convResults.output.text[i++],convResults.title);
  158. return;
  159. }
  160. if(convResults.intents[0]==null || convResults.intents[0]== undefined){
  161. console.log("Context nulo e Intents nulo vindos do Watson Assistant. Nenhum retorno sera executado!");
  162. return;
  163. }
  164.  
  165. }
  166. }
  167. /* Fim do trecho de codigo que realiza a chamda ao W. Assistant e trata a mensagem */
  168.  
  169. /* callback error */
  170. if (err) {
  171. console.error("Falha ao chamar o Wantson Assistant. Motivo: "+err);
  172. return;
  173. }
  174.  
  175. });
  176. }
  177.  
  178. var timer;
  179. function timeOut (sender,text_){
  180. function send(){
  181. text_ = "timeOut";
  182. var payload = {
  183. workspace_id: workspace_ID,
  184. input: {
  185. text:text_
  186. },
  187. context: contexid
  188. };
  189. callWatson(payload,sender);
  190. }
  191. timer = setTimeout(send,30000);
  192. }
  193. function stopTimeOut (){
  194. clearTimeout(timer);
  195. }
  196.  
  197. var text__ = null;
  198. function sendMessage(sender, text_,context_,intent) {
  199.  
  200. var find = /user_name/g;
  201. var confirm = text_.match(find);
  202. console.log('match: ',confirm);
  203.  
  204. if (confirm !== null){
  205. text__ = text_.replace(find, name);
  206. //console.log('user_first_name 2: ', name);
  207. }else {
  208. text__ = text_;
  209. }
  210. //----------------------------
  211. if (context_ != null){
  212. stopTimeOut();
  213. var messageData = {
  214. recipient: {id: sender},
  215. message:{
  216. text:text__,//text:text_
  217. quick_replies: context_
  218. }};
  219.  
  220. /* Evitar if/else, utilizar mais comentarios e logar a aplicacao por inteira */
  221. } else {
  222.  
  223. /*TODO Tornar esse codigo transparente para que funcione independente do tipo de dialogo */
  224. stopTimeOut();
  225. messageData = {
  226. recipient: {id: sender},
  227. message:{
  228. text: text__
  229. }};
  230. }
  231.  
  232. /*TODO Tornar esse codigo transparente para que funcione independente do tipo de dialogo */
  233. if (intent !== 'timeOut' && intent !== 'Agradecimentos'){
  234. timeOut(sender,text__);
  235. }
  236. request({
  237. url: 'https://graph.facebook.com/v3.0/me/messages',//v2.6
  238. qs: { access_token: token },
  239. method: 'POST',
  240. json: messageData
  241. }, function (error, response, body) {
  242. if (error) {
  243. console.log('Error sending message: ', error);
  244. } else if (response.body.error) {
  245. console.log('Error: ', response.body.error);
  246. }
  247. });
  248. }
  249.  
  250. var workspace_ID = "ab096c7d-f28c-41c2-b4cf-0d148af91d35";
  251. var token = "EAAF1G3WBdVYBAJWTZAe71r2shYpEJ6DZCnM2utHipiF7RdsnZAIiB7DhMf8FrkleXyY25q2ugUkDqdD2JL4bDZBrevoKWbDQH91QjjhvZAgzuJmZCErHEHoJWh3tbN5ZCFGu4o4XYbJ4dKpj7xWToqVecKL6zZBiex5bnxQIHuXHDQZDZD";
  252. var host = (process.env.VCAP_APP_HOST || 'localhost');
  253. var port = (process.env.VCAP_APP_PORT || 3001);
  254. app.listen(port, host);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement