@tiledesk/tiledesk-tybot-connector 0.5.0 → 0.5.1-rc1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/ExtApi.js +4 -83
  3. package/ExtUtil.js +0 -1
  4. package/Logger.js +113 -0
  5. package/TdCache.js +5 -3
  6. package/TiledeskClientTest.js +5 -28
  7. package/TiledeskExpression.js +6 -47
  8. package/{models → engine}/IntentForm.js +30 -44
  9. package/{models → engine}/IntentsMachineFactory.js +5 -4
  10. package/{models → engine}/MongodbBotsDataSource.js +31 -55
  11. package/{models → engine}/MongodbIntentsMachine.js +6 -5
  12. package/{models → engine}/TiledeskChatbot.js +82 -259
  13. package/{models → engine}/TiledeskChatbotConst.js +9 -0
  14. package/{models → engine}/TiledeskIntentsMachine.js +5 -15
  15. package/{models → engine/mock}/MockBotsDataSource.js +2 -19
  16. package/{models → engine/mock}/MockTdCache.js +0 -9
  17. package/index.js +106 -380
  18. package/logs/app.log +11557 -277
  19. package/logs/app1.log +62258 -0
  20. package/logs/app2.log +46280 -0
  21. package/logs/app3.log +31686 -0
  22. package/logs/app4.log +46163 -0
  23. package/logs/app5.log +33173 -0
  24. package/models/faq.js +2 -5
  25. package/package.json +5 -2
  26. package/{TiledeskServices → services}/AIService.js +4 -3
  27. package/{models/faqKbService.js → services/FaqKbService.js} +1 -2
  28. package/{models/faqService.js → services/FaqService.js} +4 -3
  29. package/services/IntegrationService.js +43 -0
  30. package/services/TilebotService.js +47 -0
  31. package/tiledeskChatbotPlugs/DirectivesChatbotPlug.js +68 -142
  32. package/tiledeskChatbotPlugs/FillParamsChatbotPlug.js +8 -14
  33. package/tiledeskChatbotPlugs/Filler.js +0 -1
  34. package/tiledeskChatbotPlugs/MarkbotChatbotPlug.js +12 -20
  35. package/tiledeskChatbotPlugs/MessagePipeline.js +5 -15
  36. package/tiledeskChatbotPlugs/SplitsChatbotPlug.js +4 -13
  37. package/tiledeskChatbotPlugs/TiledeskRequestVariables.js +1 -1
  38. package/tiledeskChatbotPlugs/WebhookChatbotPlug.js +21 -89
  39. package/tiledeskChatbotPlugs/directives/DEPRECATED_DirSetAttribute.js +1 -1
  40. package/tiledeskChatbotPlugs/directives/DirAddTags.js +23 -140
  41. package/tiledeskChatbotPlugs/directives/DirAiPrompt.js +42 -128
  42. package/tiledeskChatbotPlugs/directives/DirAskGPT.js +37 -127
  43. package/tiledeskChatbotPlugs/directives/DirAskGPTV2.js +52 -145
  44. package/tiledeskChatbotPlugs/directives/DirAssign.js +12 -23
  45. package/tiledeskChatbotPlugs/directives/DirAssignFromFunction.js +16 -12
  46. package/tiledeskChatbotPlugs/directives/DirAssistant.js +56 -198
  47. package/tiledeskChatbotPlugs/directives/DirBrevo.js +41 -101
  48. package/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js +9 -19
  49. package/tiledeskChatbotPlugs/directives/DirClearTranscript.js +1 -1
  50. package/tiledeskChatbotPlugs/directives/DirClose.js +4 -2
  51. package/tiledeskChatbotPlugs/directives/DirCode.js +16 -23
  52. package/tiledeskChatbotPlugs/directives/DirCondition.js +19 -25
  53. package/tiledeskChatbotPlugs/directives/DirConnectBlock.js +9 -82
  54. package/tiledeskChatbotPlugs/directives/DirContactUpdate.js +10 -22
  55. package/tiledeskChatbotPlugs/directives/DirCustomerio.js +34 -89
  56. package/tiledeskChatbotPlugs/directives/DirDeflectToHelpCenter.js +17 -22
  57. package/tiledeskChatbotPlugs/directives/DirDeleteVariable.js +8 -8
  58. package/tiledeskChatbotPlugs/directives/DirDepartment.js +13 -12
  59. package/tiledeskChatbotPlugs/directives/DirDisableInputText.js +2 -6
  60. package/tiledeskChatbotPlugs/directives/DirFireTiledeskEvent.js +4 -4
  61. package/tiledeskChatbotPlugs/directives/DirForm.js +17 -24
  62. package/tiledeskChatbotPlugs/directives/DirGptTask.js +49 -139
  63. package/tiledeskChatbotPlugs/directives/DirGptTask_OLD.js +8 -53
  64. package/tiledeskChatbotPlugs/directives/DirHubspot.js +31 -91
  65. package/tiledeskChatbotPlugs/directives/DirIfOnlineAgents.js +19 -26
  66. package/tiledeskChatbotPlugs/directives/DirIfOnlineAgentsV2.js +24 -78
  67. package/tiledeskChatbotPlugs/directives/DirIfOpenHours.js +17 -68
  68. package/tiledeskChatbotPlugs/directives/DirIntent.js +12 -104
  69. package/tiledeskChatbotPlugs/directives/DirJSONCondition.js +15 -14
  70. package/tiledeskChatbotPlugs/directives/DirLockIntent.js +7 -12
  71. package/tiledeskChatbotPlugs/directives/DirMake.js +21 -53
  72. package/tiledeskChatbotPlugs/directives/DirMessage.js +35 -28
  73. package/tiledeskChatbotPlugs/directives/DirMessageToBot.js +8 -87
  74. package/tiledeskChatbotPlugs/directives/DirMoveToAgent.js +6 -4
  75. package/tiledeskChatbotPlugs/directives/DirMoveToUnassigned.js +6 -4
  76. package/tiledeskChatbotPlugs/directives/DirQapla.js +26 -120
  77. package/tiledeskChatbotPlugs/directives/DirRandomReply.js +11 -19
  78. package/tiledeskChatbotPlugs/directives/DirRemoveCurrentBot.js +4 -0
  79. package/tiledeskChatbotPlugs/directives/DirReplaceBot.js +5 -2
  80. package/tiledeskChatbotPlugs/directives/DirReplaceBotV2.js +12 -58
  81. package/tiledeskChatbotPlugs/directives/DirReplaceBotV3.js +11 -57
  82. package/tiledeskChatbotPlugs/directives/DirReply.js +34 -37
  83. package/tiledeskChatbotPlugs/directives/DirReplyV2.js +30 -72
  84. package/tiledeskChatbotPlugs/directives/DirSendEmail.js +9 -10
  85. package/tiledeskChatbotPlugs/directives/DirSendWhatsapp.js +15 -40
  86. package/tiledeskChatbotPlugs/directives/DirSetAttribute.js +8 -5
  87. package/tiledeskChatbotPlugs/directives/DirSetAttributeV2.js +25 -113
  88. package/tiledeskChatbotPlugs/directives/DirSetConversationTags.js +14 -13
  89. package/tiledeskChatbotPlugs/directives/DirUnlockIntent.js +3 -3
  90. package/tiledeskChatbotPlugs/directives/DirWait.js +5 -6
  91. package/tiledeskChatbotPlugs/directives/DirWebRequest.js +14 -49
  92. package/tiledeskChatbotPlugs/directives/DirWebRequestV2.js +22 -77
  93. package/tiledeskChatbotPlugs/directives/DirWebRequestV2_old.js +1 -1
  94. package/tiledeskChatbotPlugs/directives/DirWebResponse.js +23 -64
  95. package/tiledeskChatbotPlugs/directives/DirWhatsappByAttribute.js +13 -42
  96. package/tiledeskChatbotPlugs/directives/Directives.js +1 -3
  97. package/utils/HttpUtils.js +128 -0
  98. package/{models → utils}/TiledeskChatbotUtil.js +140 -234
  99. package/utils/winston.js +42 -0
  100. package/TdCache copy.js +0 -242
  101. package/TiledeskServices/utils.js +0 -99
  102. /package/{models → engine/mock}/MockIntentsMachine.js +0 -0
package/index.js CHANGED
@@ -1,17 +1,16 @@
1
1
  const express = require('express');
2
2
  const router = express.Router();
3
3
  const bodyParser = require('body-parser');
4
+ const winston = require('./utils/winston.js')
4
5
  const { TiledeskClient } = require('@tiledesk/tiledesk-client');
5
6
  const { ExtApi } = require('./ExtApi.js');
6
7
  const { ExtUtil } = require('./ExtUtil.js');
7
8
  const { TdCache } = require('./TdCache.js');
8
- const { TiledeskChatbot } = require('./models/TiledeskChatbot.js');
9
- const { MongodbBotsDataSource } = require('./models/MongodbBotsDataSource.js');
10
- // const { MongodbIntentsMachine } = require('./models/MongodbIntentsMachine.js');
11
- // const { TiledeskIntentsMachine } = require('./models/TiledeskIntentsMachine.js');
12
- const { MockBotsDataSource } = require('./models/MockBotsDataSource.js');
13
- const { TiledeskChatbotConst } = require('./models/TiledeskChatbotConst');
14
- const { IntentsMachineFactory } = require('./models/IntentsMachineFactory');
9
+ const { TiledeskChatbot } = require('./engine/TiledeskChatbot.js');
10
+ const { MongodbBotsDataSource } = require('./engine/MongodbBotsDataSource.js');
11
+ const { MockBotsDataSource } = require('./engine/mock/MockBotsDataSource.js');
12
+ const { TiledeskChatbotConst } = require('./engine/TiledeskChatbotConst.js');
13
+ const { IntentsMachineFactory } = require('./engine/IntentsMachineFactory.js');
15
14
  const { v4: uuidv4 } = require('uuid');
16
15
  let axios = require('axios');
17
16
  // let parser = require('accept-language-parser');
@@ -32,24 +31,26 @@ const { DirectivesChatbotPlug } = require('./tiledeskChatbotPlugs/DirectivesChat
32
31
  // THE IMPORT
33
32
  let mongoose = require('mongoose');
34
33
  // const { Directives } = require('./tiledeskChatbotPlugs/directives/Directives.js');
35
- const { TiledeskChatbotUtil } = require('./models/TiledeskChatbotUtil.js'); //require('@tiledesk/tiledesk-chatbot-util');
36
- const AiService = require('./TiledeskServices/AIService.js');
34
+ const { TiledeskChatbotUtil } = require('./utils/TiledeskChatbotUtil.js'); //require('@tiledesk/tiledesk-chatbot-util');
35
+
36
+ const AiService = require('./services/AIService.js');
37
+ const tilebotService = require('./services/TilebotService.js');
38
+
37
39
  let API_ENDPOINT = null;
38
40
  let TILEBOT_ENDPOINT = null;
39
41
  let staticBots;
40
42
 
41
43
  router.post('/ext/:botid', async (req, res) => {
42
44
  const botId = req.params.botid;
43
- if (log) {console.log("(tybotRoute) POST /ext/:botid called: ", botId);}
45
+ winston.verbose("(tybotRoute) POST /ext/:botid called: " + botId)
44
46
  if(!botId || botId === "null" || botId === "undefined"){
45
47
  return res.status(400).send({"success": false, error: "Required parameters botid not found. Value is 'null' or 'undefined'"})
46
48
  }
47
49
 
48
50
  if (req && req.body && req.body.payload && req.body.payload.request && req.body.payload.request.snapshot) {
49
51
  delete req.body.payload.request.snapshot;
50
- console.log("Removed req.body.payload.request.snapshot field");
51
52
  }
52
- if (log) {console.log("REQUEST BODY:", JSON.stringify(req.body));}
53
+ winston.verbose("(tybotRoute) Request Body: ", req.body);
53
54
 
54
55
  const message = req.body.payload;
55
56
  const messageId = message._id;
@@ -57,7 +58,7 @@ router.post('/ext/:botid', async (req, res) => {
57
58
  const token = req.body.token;
58
59
  const requestId = message.request.request_id;
59
60
  const projectId = message.id_project;
60
- if (log) {console.log("message.id_project:", message.id_project);}
61
+ winston.verbose("(tybotRoute) message.id_project: " + message.id_project)
61
62
 
62
63
  // adding info for internal context workflow
63
64
  message.request.bot_id = botId;
@@ -74,7 +75,7 @@ router.post('/ext/:botid', async (req, res) => {
74
75
  let isAudio = TiledeskChatbotUtil.isAudioMessage(message)
75
76
  if(isAudio){
76
77
  let responseText = await aiService.speechToText(message.metadata.src).catch(err => {
77
- if(log) console.log('(index.js) aiService.speechToText error: ', err)
78
+ winston.error('(index.js) aiService.speechToText error: ', err)
78
79
  })
79
80
  if(responseText && responseText.text)
80
81
  message.text = responseText.text
@@ -97,30 +98,13 @@ router.post('/ext/:botid', async (req, res) => {
97
98
  {EX: 604800} // 7 days
98
99
  );
99
100
 
100
- // NEXTTTTTTT
101
- // const message_context = {
102
- // projectId: projectId,
103
- // requestId: requestId,
104
- // token: token
105
- // }
106
- // const message_context_key = "tiledesk:messages:context:" + messageId;
107
- // await tdcache.set(
108
- // message_context_key,
109
- // JSON.stringify(message_context),
110
- // {EX: 86400}
111
- // );
112
- // if (log) {console.log("message context saved for messageid:", message_context_key)}
113
- // provide a http method for set/get message context, authenticated with tiledesk token and APIKEY.
114
- // NEXTTTTTTT
115
-
116
101
  let botsDS;
117
102
  if (!staticBots) {
118
103
  botsDS = new MongodbBotsDataSource({projectId: projectId, botId: botId, log: log});
119
- if (log) {console.log("botsDS created with Mongo");}
104
+ winston.verbose("(tybotRoute) botsDS created with Mongo");
120
105
  }
121
106
  else {
122
107
  botsDS = new MockBotsDataSource(staticBots);
123
- // console.log("botDA.data.........", botsDS.data);
124
108
  }
125
109
 
126
110
  // get the bot metadata
@@ -128,51 +112,21 @@ router.post('/ext/:botid', async (req, res) => {
128
112
  Promise.reject(err);
129
113
  return;
130
114
  });
131
- // let bot = null;
132
- // try {
133
- // // bot = await botsDS.getBotById(botId);
134
- // // bot = await botById(botId, projectId, tdcache, botsDS);
135
- // bot = await botsDS.getBotByIdCache(botId, tdcache);
136
- // // console.log("getBotByIdCache ---> bot: ", JSON.stringify(bot, null, 2))
137
- // }
138
- // catch(error) {
139
- // console.error("Error getting botId:", botId);
140
- // console.error("Error getting bot was:", error);
141
- // return;
142
- // }
143
- // if (log) {console.log("bot found:", JSON.stringify(bot));}
115
+
116
+ winston.debug("(tybotRoute) Bot found: ", bot)
117
+
144
118
 
145
119
  let intentsMachine;
146
120
  let backupMachine;
147
121
  if (!staticBots) {
148
122
  intentsMachine = IntentsMachineFactory.getMachine(bot, botId, projectId, log);
149
123
  backupMachine = IntentsMachineFactory.getBackupMachine(bot, botId, projectId, log);
150
- if (log) {console.log("Created backupMachine:", backupMachine);}
124
+ winston.debug("(tybotRoute) Created backupMachine:", backupMachine)
151
125
  }
152
126
  else {
153
127
  intentsMachine = {}
154
128
  }
155
129
 
156
- // let intentsMachine;
157
- // if (!staticBots) {
158
- // if (log) {console.log("intentsMachine to MongoDB");}
159
- // intentsMachine = new MongodbIntentsMachine({projectId: projectId, language: bot.language, log});
160
- // if (bot.intentsEngine === "tiledesk-ai") {
161
- // if (log) {console.log("intentsMachine to tiledesk-ai");}
162
- // intentsMachine = new TiledeskIntentsMachine(
163
- // {
164
- // //projectId: projectId,
165
- // //language: bot.language,
166
- // botId: botId
167
- // //TILEBOT_AI_ENDPOINT: process.env.TILEBOT_AI_ENDPOINT
168
- // });
169
- // }
170
- // }
171
- // else {
172
- // intentsMachine = {}
173
- // }
174
- //const intentsMachine = new TiledeskIntentsMachine({API_ENDPOINT: "https://MockIntentsMachine.tiledesk.repl.co", log: true});
175
- // console.log("the bot is:", bot)
176
130
  const chatbot = new TiledeskChatbot({
177
131
  botsDataSource: botsDS,
178
132
  intentsFinder: intentsMachine,
@@ -189,11 +143,8 @@ router.post('/ext/:botid', async (req, res) => {
189
143
  MAX_EXECUTION_TIME: MAX_EXECUTION_TIME,
190
144
  log: log
191
145
  });
192
- if (log) {console.log("MESSAGE CONTAINS:", message.text);}
193
- // if (message.text === "\\\\start") { // patch for the misleading \\start training phrase
194
- // if (log) {console.log("forced conversion of \\\\start /start");}
195
- // message.text = "/start";
196
- // }
146
+ winston.verbose("(tybotRoute) Message text: " + message.text)
147
+
197
148
  await TiledeskChatbotUtil.updateRequestAttributes(chatbot, token, message, projectId, requestId);
198
149
  if (requestId.startsWith("support-group-")) {
199
150
  await TiledeskChatbotUtil.updateConversationTranscript(chatbot, message);
@@ -204,23 +155,19 @@ router.post('/ext/:botid', async (req, res) => {
204
155
  reply = await chatbot.replyToMessage(message);
205
156
  }
206
157
  catch(err) {
207
- console.error("(tybotRoute) An error occurred replying to message:", JSON.stringify(message), "\nError:", err );
158
+ winston.error("(tybotRoute) An error occurred replying to message: ", err);
208
159
  return;
209
160
  }
210
161
  if (!reply) {
211
- if (log) { console.log("(tybotRoute) No reply. Stop flow.") }
162
+ winston.verbose("(tybotRoute) No reply. Stop flow.")
212
163
  return;
213
164
  }
214
165
 
215
- // console.log("reply is:", reply);
216
- // if (reply.attributes.intent_info.intent_id) {
217
- // process.exit(1)
218
- // }
219
166
  if (reply.actions && reply.actions.length > 0) { // structured actions (coming from chatbot designer)
220
167
  try {
221
- if (log) {console.log("the actions:", JSON.stringify(reply.actions));}
168
+ winston.debug("(tybotRoute) Reply actions: ", reply.actions)
222
169
  let directives = TiledeskChatbotUtil.actionsToDirectives(reply.actions);
223
- if (log) {console.log("the directives:", JSON.stringify(directives));}
170
+ winston.debug("(tybotRoute) the directives:", directives)
224
171
  let directivesPlug = new DirectivesChatbotPlug(
225
172
  {
226
173
  message: message,
@@ -237,15 +184,15 @@ router.post('/ext/:botid', async (req, res) => {
237
184
  }
238
185
  );
239
186
  directivesPlug.processDirectives( () => {
240
- if (log) {console.log("Actions - Directives executed.");}
187
+ winston.verbose("(tybotRoute) Actions - Directives executed.");
241
188
  });
242
189
  }
243
190
  catch (error) {
244
- console.error("Error while processing actions:", error);
191
+ winston.error("(tybotRoute) Error while processing actions:", error);
245
192
  }
246
193
  }
247
194
  else { // text answer (parse text directives to get actions)
248
- if (log) {console.log("an answer:", reply.text);}
195
+ winston.verbose("(tybotRoute) No actions. Reply text: ", reply.text)
249
196
  reply.triggeredByMessageId = messageId;
250
197
  if (!reply.attributes) {
251
198
  reply.attributes = {}
@@ -260,9 +207,7 @@ router.post('/ext/:botid', async (req, res) => {
260
207
  log: false
261
208
  });
262
209
  apiext.sendSupportMessageExt(reply, projectId, requestId, token, () => {
263
- if (log) {
264
- //console.log("SupportMessageExt() reply sent:", JSON.stringify(reply));
265
- }
210
+ winston.verbose("(tybotRoute) sendSupportMessageExt reply sent: ", reply)
266
211
  });
267
212
  }
268
213
 
@@ -273,13 +218,15 @@ router.post('/ext/:projectId/requests/:requestId/messages', async (req, res) =>
273
218
  const projectId = req.params.projectId;
274
219
  const requestId = req.params.requestId;
275
220
  const token = req.headers["authorization"];
276
- if (log) {console.log("/ext projectId:", projectId);}
277
- if (log) {console.log("/ext requestId:", requestId);}
278
- if (log) {console.log("/ext req.headers:", req.headers);}
279
- if (log) {console.log("/ext token:", token);}
221
+
222
+ winston.verbose("(tybotRoute) POST /ext/:projectId/requests/:requestId/messages called: " + requestId)
223
+ winston.debug("(tybotRoute) projectId " + projectId)
224
+ winston.debug("(tybotRoute) token " + token)
225
+ winston.debug("(tybotRoute) req.headers " + req.headers)
226
+ winston.debug("(tybotRoute) projectId " + projectId)
280
227
 
281
228
  let answer = req.body;
282
- if (log) {console.log("/ext => answer on sendSupportMessageExt:", JSON.stringify(answer));}
229
+ winston.verbose("(tybotRoute) answer on sendSupportMessageExt: ", answer);
283
230
  const tdclient = new TiledeskClient({
284
231
  projectId: projectId,
285
232
  token: token,
@@ -287,81 +234,57 @@ router.post('/ext/:projectId/requests/:requestId/messages', async (req, res) =>
287
234
  APIKEY: "___",
288
235
  log: false
289
236
  });
237
+
290
238
  let request;
291
- // const request_key = "tilebot:" + requestId;
292
- // if (log) {console.log("request_key:", request_key);}
293
- // if (tdcache) {
294
- // request = await tdcache.getJSON(request_key)
295
- // if (log) {console.log("Request from cache:", JSON.stringify(request));}
296
- // if (!request) {
297
- // if (log) {console.log("!Request from cache", requestId);}
298
- // try {
299
- // request = await tdclient.getRequestById(requestId);
300
- // }
301
- // catch(err) {
302
- // console.error("Error getting the request:", err)
303
- // }
304
- // if (log) {console.log("Got request with APIs (after no cache hit)");}
305
- // }
306
- // }
307
- // else {
308
- // if (log) {console.log("No tdcache. Getting request with APIs", requestId);}
309
239
  try {
310
240
  request = await tdclient.getRequestById(requestId);
311
- // console.log("Cache request found.");
312
241
  }
313
242
  catch(err) {
314
- console.error("/ext => Request not found:", requestId);
243
+ winston.error("(tybotRoute) request not found with id " + requestId);
315
244
  }
316
- // if (log) {console.log("(No tdcache) Got request with APIs");}
317
- // }
245
+
318
246
  if (!request) {
319
- if (log) {console.log("/ext => Creating new Request. Chatbot-pure directives still work. Tiledesk specific directives don't");}
247
+ winston.verbose("(tybotRoute) Creating new Request. Chatbot-pure directives still work. Tiledesk specific directives don't")
320
248
  const request_botId_key = "tilebot:botId_requests:" + requestId;
321
249
  const botId = await tdcache.get(request_botId_key);
322
- if (log) {console.log("/ext => current botId [" + request_botId_key + "]:", botId);}
250
+ winston.verbose("(tybotRoute) current botId [" + request_botId_key + "]:" + botId)
323
251
  request = {
324
252
  request_id: requestId,
325
253
  id_project: projectId,
326
254
  bot_id: botId
327
255
  }
328
256
  }
329
- if (log) {
330
- console.log("/ext request....", JSON.stringify(request));
331
- console.log("/ext API_ENDPOINT....", API_ENDPOINT);
332
- console.log("/ext process.env.TILEBOT_ENDPOINT....", TILEBOT_ENDPOINT);
333
- }
257
+ winston.debug("(tybotRoute) request: ", request);
258
+ winston.debug("(tybotRoute) API_ENDPOINT: " + API_ENDPOINT);
259
+ winston.debug("(tybotRoute) request: " + TILEBOT_ENDPOINT);
260
+
334
261
  let directivesPlug = new DirectivesChatbotPlug({supportRequest: request, API_ENDPOINT: API_ENDPOINT, TILEBOT_ENDPOINT: TILEBOT_ENDPOINT, token: token, log: log, HELP_CENTER_API_ENDPOINT: process.env.HELP_CENTER_API_ENDPOINT, cache: tdcache});
335
- // let directivesPlug = null;
336
- // PIPELINE-EXT
337
- // if (log) {console.log("answer to process:", JSON.stringify(answer));}
262
+
338
263
  const original_answer_text = answer.text;
339
264
  const bot_answer = await ExtUtil.execPipelineExt(request, answer, directivesPlug, tdcache, log);
340
- if (log) {console.log("/ext => bot_answer", JSON.stringify(bot_answer))}
265
+ winston.debug("(tybotRoute) bot_answer: ", bot_answer);
266
+
341
267
  if (bot_answer) {
342
- if (log) {console.log("/ext => adding to bot_answer original_answer_text:", JSON.stringify(original_answer_text));}
268
+ winston.debug("(tybotRoute) adding to bot_answer original_answer_text: ", original_answer_text);
343
269
  if (!bot_answer.attributes) {
344
270
  bot_answer.attributes = {};
345
271
  }
346
- // if (!bot_answer.text) {
347
- // bot_answer.text = "..."
348
- // }
272
+
349
273
  bot_answer.attributes["_raw_message"] = original_answer_text;
350
- // if (log) {console.log("bot_answer", JSON.stringify(bot_answer));}
351
274
  tdclient.sendSupportMessage(requestId, bot_answer, (err, response) => {
352
- if (log) {console.log("/ext => bot_answer sent:", JSON.stringify(bot_answer));}
275
+ winston.verbose("(tybotRoute) Bot answer sent")
353
276
  if (err) {
354
- console.error("/ext => Error sending message", JSON.stringify(err));
277
+ winston.error("(tybotRoute) Error sending message", err);
355
278
  }
356
- directivesPlug.processDirectives( () => {
357
- if (log) {console.log("After message - Directives executed.");}
279
+ directivesPlug.processDirectives(() => {
280
+ winston.verbose("(tybotRoute) Directives executed")
358
281
  });
359
282
  });
360
283
  }
361
284
  else {
362
- if (log) {console.log("/ext => !bot_answer");}
363
- directivesPlug.processDirectives( () => {
364
- if (log) {console.log("Directives executed.");}
285
+ winston.verbose("(tybotRoute) No bot_answer")
286
+ directivesPlug.processDirectives(() => {
287
+ winston.verbose("(tybotRoute) Directives executed")
365
288
  });
366
289
  }
367
290
 
@@ -391,73 +314,12 @@ router.get('/ext/reserved/parameters/requests/:requestid', async (req, res) => {
391
314
  res.send(parameters);
392
315
  }
393
316
  else {
394
- // const RESERVED = [
395
- // TiledeskChatbotConst.REQ_CHATBOT_NAME_KEY,
396
- // TiledeskChatbotConst.REQ_CHAT_URL,
397
- // TiledeskChatbotConst.REQ_CITY_KEY,
398
- // TiledeskChatbotConst.REQ_COUNTRY_KEY,
399
- // TiledeskChatbotConst.REQ_DEPARTMENT_ID_KEY,
400
- // TiledeskChatbotConst.REQ_DEPARTMENT_NAME_KEY,
401
- // TiledeskChatbotConst.REQ_END_USER_ID_KEY,
402
- // TiledeskChatbotConst.REQ_END_USER_IP_ADDRESS_KEY,
403
- // TiledeskChatbotConst.REQ_LAST_MESSAGE_ID_KEY,
404
- // TiledeskChatbotConst.REQ_LAST_USER_TEXT_KEY,
405
- // TiledeskChatbotConst.REQ_PROJECT_ID_KEY,
406
- // TiledeskChatbotConst.REQ_REQUEST_ID_KEY,
407
- // TiledeskChatbotConst.REQ_USER_AGENT_KEY,
408
- // TiledeskChatbotConst.REQ_USER_LANGUAGE_KEY,
409
- // TiledeskChatbotConst.REQ_USER_SOURCE_PAGE_KEY,
410
- // TiledeskChatbotConst.REQ_LAST_USER_MESSAGE_TYPE_KEY,
411
- // TiledeskChatbotConst.REQ_TRANSCRIPT_KEY,
412
- // TiledeskChatbotConst.REQ_LAST_USER_MESSAGE_KEY,
413
- // TiledeskChatbot.REQ_DECODED_JWT_KEY,
414
- // "lastUserImageURL", // image
415
- // "lastUserImageName", // image
416
- // "lastUserImageWidth", // image
417
- // "lastUserImageHeight", // image
418
- // "lastUserImageType", // image
419
- // "lastUserDocumentURL", // file
420
- // "lastUserDocumentName", // file
421
- // "lastUserDocumentType", // file
422
- // "ticketId",
423
- // TiledeskChatbotConst.REQ_CHAT_CHANNEL,
424
- // "user_lead_id",
425
- // "lastUserText",
426
- // TiledeskChatbotConst.REQ_REQUESTER_IS_AUTHENTICATED_KEY,
427
- // "userInput"
428
- // ]
429
- // let userParams = {};
430
- // if (parameters) {
431
- // for (const [key, value] of Object.entries(parameters)) {
432
- // // console.log(key, value);
433
- // // There is a bug that moves the requestId as a key in request attributes, so: && !key.startsWith("support-group-")
434
- // if (!key.startsWith("_") && !RESERVED.some(e => e === key) && !key.startsWith("support-group-")) {
435
- // userParams[key] = value;
436
- // }
437
- // }
438
- // }
439
317
  const userParams = TiledeskChatbotUtil.userFlowAttributes(parameters);
440
318
  res.send(userParams);
441
319
  }
442
320
  });
443
321
 
444
322
  router.get('/ext/parameters/requests/:requestid', async (req, res) => {
445
- // console.log("Checking authorization...");
446
- // const authorization = req.headers["authorization"];
447
- // if (!authorization) {
448
- // console.log("No authorization header...");
449
- // res.status(401).send("Unauthorized");
450
- // return;
451
- // }
452
- // const token = req.headers["authorization"];
453
- // const publicKey = process.env.GLOBAL_SECRET_OR_PUB_KEY;
454
- // console.log("Got public key:", publicKey);
455
- // const _decoded = null;
456
- // jwt.verify(token, publicKey, function (err, decoded) {
457
- // _decoded = decoded;
458
- // });
459
- // console.log("Authorization header field checking", req.headers["authorization"]);
460
-
461
323
 
462
324
  const requestId = req.params.requestid;
463
325
  if (!requestId) {
@@ -467,14 +329,13 @@ router.get('/ext/parameters/requests/:requestid', async (req, res) => {
467
329
  const request_parts = requestId.split("-");
468
330
  if (request_parts && request_parts.length >= 4) {
469
331
  const project_id = request_parts[2];
470
- // console.log("ProjectId:", project_id);
471
332
  if (project_id !== "656054000410fa00132e5dcc") { //&& project_id !== "ANOTHER P_ID"
472
333
  res.status(401).send("Unauthorized");
473
334
  return;
474
335
  }
475
336
  }
476
- else if (!request_parts || ( request_parts && request_parts.length < 4) ) {
477
- res.status(500).send("Invalid request ID");
337
+ else if (!request_parts || (request_parts && request_parts.length < 4) ) {
338
+ res.status(500).send("Invalid request id " + requestId);
478
339
  return;
479
340
  }
480
341
  const parameters = await TiledeskChatbot.allParametersStatic(tdcache, requestId);
@@ -486,45 +347,7 @@ router.get('/ext/parameters/requests/:requestid', async (req, res) => {
486
347
  res.send(parameters);
487
348
  }
488
349
  else {
489
- const RESERVED = [
490
- TiledeskChatbotConst.REQ_CHATBOT_NAME_KEY,
491
- TiledeskChatbotConst.REQ_CHATBOT_ID_KEY,
492
- TiledeskChatbotConst.REQ_CHAT_URL,
493
- TiledeskChatbotConst.REQ_CITY_KEY,
494
- TiledeskChatbotConst.REQ_COUNTRY_KEY,
495
- TiledeskChatbotConst.REQ_DEPARTMENT_ID_KEY,
496
- TiledeskChatbotConst.REQ_DEPARTMENT_NAME_KEY,
497
- TiledeskChatbotConst.REQ_END_USER_ID_KEY,
498
- TiledeskChatbotConst.REQ_END_USER_IP_ADDRESS_KEY,
499
- TiledeskChatbotConst.REQ_LAST_MESSAGE_ID_KEY,
500
- TiledeskChatbotConst.REQ_LAST_USER_TEXT_KEY,
501
- TiledeskChatbotConst.REQ_PROJECT_ID_KEY,
502
- TiledeskChatbotConst.REQ_REQUEST_ID_KEY,
503
- TiledeskChatbotConst.REQ_USER_AGENT_KEY,
504
- TiledeskChatbotConst.REQ_USER_LANGUAGE_KEY,
505
- TiledeskChatbotConst.REQ_USER_SOURCE_PAGE_KEY,
506
- TiledeskChatbotConst.REQ_LAST_USER_MESSAGE_TYPE_KEY,
507
- TiledeskChatbotConst.REQ_TRANSCRIPT_KEY,
508
- TiledeskChatbotConst.REQ_LAST_USER_MESSAGE_KEY,
509
- "lastUserImageURL", // image
510
- "lastUserImageName", // image
511
- "lastUserImageWidth", // image
512
- "lastUserImageHeight", // image
513
- "lastUserImageType", // image
514
- "lastUserDocumentURL", // file
515
- "lastUserDocumentName", // file
516
- "lastUserDocumentType" // file
517
- ]
518
- let userParams = {};
519
- if (parameters) {
520
- for (const [key, value] of Object.entries(parameters)) {
521
- // console.log(key, value);
522
- // There is a bug that moves the requestId as a key in request attributes, so: && !key.startsWith("support-group-")
523
- if (!key.startsWith("_") && !RESERVED.some(e => e === key) && !key.startsWith("support-group-")) {
524
- userParams[key] = value;
525
- }
526
- }
527
- }
350
+ const userParams = TiledeskChatbotUtil.userFlowAttributes(parameters);
528
351
  res.send(userParams);
529
352
  }
530
353
  });
@@ -538,7 +361,8 @@ router.get('/test/webrequest/get/plain/:username', async (req, res) => {
538
361
  });
539
362
 
540
363
  router.post('/test/webrequest/post/plain', async (req, res) => {
541
- console.log("/post/plain req.body:", req.body);
364
+ winston.verbose("(tybotRoute) POST /test/webrequest/post/plain called");
365
+ winston.debug("(tybotRoute) POST /test/webrequest/post/plain req.body:", req.body);
542
366
  if (req && req.body && req.body.name) {
543
367
  res.send("Your name is " + req.body.name);
544
368
  }
@@ -548,16 +372,14 @@ router.post('/test/webrequest/post/plain', async (req, res) => {
548
372
  });
549
373
 
550
374
  router.post('/echobot', (req, res) => {
551
- //console.log('echobot message body.payload: ', JSON.stringify(req.body.payload));
375
+ winston.verbose("(tybotRoute) POST /echobot called");
376
+ winston.debug("(tybotRoute) POST /echobot req.body: ", req.body.payload);
377
+
552
378
  const message = req.body.payload;
553
379
  const token = req.body.token;
554
380
  const requestId = message.request.request_id;
555
381
  const projectId = message.id_project;
556
382
 
557
- // console.log("/echobot projectId:", projectId);
558
- // console.log("/echobot requestId:", requestId);
559
- // console.log("/echobot token:", token);
560
-
561
383
  const tdclient = new TiledeskClient({
562
384
  projectId: projectId,
563
385
  token: token,
@@ -574,10 +396,7 @@ router.post('/echobot', (req, res) => {
574
396
  }
575
397
  tdclient.sendSupportMessage(requestId, msg, (err, response) => {
576
398
  if (err) {
577
- console.error("Error sending message:"); //, err);
578
- }
579
- else {
580
- //console.log("message sent.");
399
+ winston.error("(tybotRoute) Error sending message"); //, err);
581
400
  }
582
401
  });
583
402
  });
@@ -588,6 +407,10 @@ router.post('/block/:project_id/:bot_id/:block_id', async (req, res) => {
588
407
  const bot_id = req.params.bot_id;
589
408
  const block_id = req.params.block_id;
590
409
  const body = req.body;
410
+
411
+ winston.verbose("(tybotRoute) POST /block/:project_id/:bot_id/:block_id called");
412
+ winston.debug("(tybotRoute) POST /block/:project_id/:bot_id/:block_id req.body: ", body);
413
+
591
414
  const async = body.async;
592
415
  const token = body.token;
593
416
  delete body.async;
@@ -614,88 +437,49 @@ router.post('/block/:project_id/:bot_id/:block_id', async (req, res) => {
614
437
  }
615
438
 
616
439
  if (async) {
617
- console.log("Async webhook");
618
- sendMessageToBot(TILEBOT_ENDPOINT, message, bot_id, (err, resbody) => {
440
+ winston.verbose("Async webhook");
441
+ tilebotService.sendMessageToBot(message, bot_id, (err, resbody) => {
619
442
  if (err) {
620
- console.error("Async err:\n", err);
443
+ winston.error("Async webhook err:\n", err);
621
444
  return res.status(500).send({ success: false, error: err });
622
445
  }
623
446
  return res.status(200).send({ success: true });
624
447
  })
625
448
  } else {
626
449
 
627
- console.log("Sync webhook. Subscribe and await for reply...")
450
+ winston.verbose("Sync webhook. Subscribe and await for reply...")
628
451
  const topic = `/webhooks/${request_id}`;
629
452
 
630
453
  try {
631
454
 
632
455
  const listener = async (message, topic) => {
633
- console.log("Web response is: ", message, "for topic", topic);
456
+ winston.debug("Web response is: " + JSON.stringify(message) + " for topic " + topic);
634
457
  await tdcache.unsubscribe(topic, listener);
635
458
 
636
459
  let json = JSON.parse(message);
637
460
  let status = json.status ? json.status : 200;
638
- console.log("Web response status: ", status);
461
+ winston.debug("Web response status: " + status);
639
462
 
640
463
  return res.status(status).send(json.payload);
641
464
  }
642
465
  await tdcache.subscribe(topic, listener);
643
466
 
644
467
  } catch(err) {
645
- console.error("Error cache subscribe ", err);
468
+ winston.error("Error cache subscribe ", err);
646
469
  return res.status(500).send({ success: false, error: "Error during cache subscription"})
647
470
  }
648
471
 
649
- sendMessageToBot(TILEBOT_ENDPOINT, message, bot_id, () => {
650
- console.log("Sync webhook message sent: ", message);
472
+ tilebotService.sendMessageToBot(message, bot_id, () => {
473
+ winston.debug("Sync webhook message sent: ", message);
651
474
  })
652
475
  }
653
476
 
654
477
  });
655
478
 
656
- // draft webhook
657
- // router.post('/block/:project_id/:bot_id/:block_id', async (req, res) => {
658
- // const project_id = req.params['project_id'];
659
- // const bot_id = req.params['bot_id'];
660
- // const block_id = req.params['block_id'];
661
- // const body = req.body;
662
- // if (this.log) {
663
- // console.log("/block/ .heders:", JSON.stringify(req.headers));
664
- // console.log("/block/ .body:", JSON.stringify(body));
665
- // }
666
-
667
- // // console.log('/block/:project_id/:bot_id/:block_id:', project_id, "/", bot_id, "/", block_id);
668
- // // console.log('/block/:project_id/:bot_id/:block_id.body', body);
669
-
670
- // // invoke block
671
- // // unique ID for each execution
672
- // const execution_id = uuidv4().replace(/-/g, '');
673
- // const request_id = "automation-request-" + project_id + "-" + execution_id;
674
- // const command = "/" + block_id;
675
- // let request = {
676
- // "payload": {
677
- // "recipient": request_id,
678
- // "text": command,
679
- // "id_project": project_id,
680
- // "request": {
681
- // "request_id": request_id
682
- // },
683
- // "attributes": {
684
- // "payload": body
685
- // }
686
- // },
687
- // "token": "NO-TOKEN"
688
- // }
689
- // if (this.log) {console.log("sendMessageToBot()...", JSON.stringify(request));}
690
- // sendMessageToBot(TILEBOT_ENDPOINT, request, bot_id, async () => {
691
- // res.status(200).send({"success":true});
692
- // return;
693
- // });
694
- // });
695
479
 
696
480
  async function startApp(settings, completionCallback) {
697
- console.log("Starting Tilebot...");
698
- // console.log("Starting Tilebot with Settings:", settings);
481
+ winston.info("(Tilebot) Starting Tilebot..")
482
+
699
483
  if (settings.bots) { // static bots data source
700
484
  staticBots = settings.bots;
701
485
  }
@@ -710,7 +494,7 @@ async function startApp(settings, completionCallback) {
710
494
  }
711
495
  else {
712
496
  API_ENDPOINT = settings.API_ENDPOINT;
713
- console.log("(Tilebot) settings.API_ENDPOINT:", API_ENDPOINT);
497
+ winston.info("(Tilebot) settings.API_ENDPOINT:" + API_ENDPOINT);
714
498
  }
715
499
 
716
500
  if (!settings.TILEBOT_ENDPOINT) {
@@ -719,8 +503,7 @@ async function startApp(settings, completionCallback) {
719
503
  else {
720
504
  TILEBOT_ENDPOINT = settings.TILEBOT_ENDPOINT
721
505
  }
722
- console.log("(Tilebot) settings.TILEBOT_ENDPOINT:", TILEBOT_ENDPOINT);
723
-
506
+ winston.info("(Tilebot) settings.TILEBOT_ENDPOINT:" + TILEBOT_ENDPOINT);
724
507
 
725
508
  if (settings.REDIS_HOST && settings.REDIS_PORT) {
726
509
  tdcache = new TdCache({
@@ -736,8 +519,7 @@ async function startApp(settings, completionCallback) {
736
519
  else {
737
520
  log = true;
738
521
  }
739
- console.log("(Tilebot) log:", log);
740
-
522
+ winston.info("(Tilebot) Log: " + log);
741
523
 
742
524
  if (process.env.CHATBOT_MAX_STEPS) {
743
525
  MAX_STEPS = Number(process.env.CHATBOT_MAX_STEPS);
@@ -747,49 +529,34 @@ async function startApp(settings, completionCallback) {
747
529
  MAX_EXECUTION_TIME = Number(process.env.CHATBOT_MAX_EXECUTION_TIME);// test // prod1000 * 3600 * 4; // 4 hours
748
530
  }
749
531
 
750
- console.log("(Tilebot) MAX_STEPS: ", MAX_STEPS)
751
- console.log("(Tilebot) MAX_EXECUTION_TIME: ", MAX_EXECUTION_TIME)
752
-
532
+ winston.info("(Tilebot) MAX_STEPS: " + MAX_STEPS);
533
+ winston.info("(Tilebot) MAX_EXECUTION_TIME: " + MAX_EXECUTION_TIME);
534
+
753
535
  var pjson = require('./package.json');
754
- console.log("(Tilebot) Starting Tilebot connector v" + pjson.version);
536
+ winston.info("(Tilebot) Starting Tilebot connector v" + pjson.version);
755
537
 
756
538
  if (!staticBots) {
757
- console.log("(Tilebot) Connecting to mongodb...");
539
+ winston.info("(Tilebot) Connecting to MongoDB...");
758
540
  // connection =
759
541
  mongoose.connect(settings.MONGODB_URI, { "useNewUrlParser": true, "autoIndex": false }, async (err) => {
760
542
  if (err) {
761
- console.error('(Tilebot) Failed to connect to MongoDB on ' + settings.MONGODB_URI + " ", err);
543
+ winston.error('(Tilebot) Failed to connect to MongoDB on ' + settings.MONGODB_URI + " ", err);
762
544
  }
763
545
  else {
764
- console.log("(Tilebot) mongodb connection ok.");
546
+ winston.info("(Tilebot) MongoDB Connected");
765
547
  await connectRedis();
766
- console.info("Tilebot started.");
548
+ winston.info("(Tilebot) Tilebot started");
549
+
767
550
  if (completionCallback) {
768
551
  completionCallback();
769
552
  }
770
- // if (tdcache) {
771
- // try {
772
- // console.log("(Tilebot) Connecting Redis...");
773
- // await tdcache.connect();
774
- // }
775
- // catch (error) {
776
- // tdcache = null;
777
- // console.error("(Tilebot) Redis connection error:", error);
778
- // process.exit(1);
779
- // }
780
- // console.log("(Tilebot) Redis connected.");
781
- // }
782
- // console.info("Tilebot started.");
783
- // if (completionCallback) {
784
- // completionCallback();
785
- // }
786
553
  }
787
554
  });
788
555
  }
789
556
  else {
790
- console.log("(Tilebot) Using static bots.");
557
+ winston.info("(Tilebot) Using static bots");
791
558
  await connectRedis();
792
- console.info("Tilebot started.");
559
+ winston.info("(Tilebot) Tilebot started");
793
560
  if (completionCallback) {
794
561
  completionCallback();
795
562
  }
@@ -799,15 +566,15 @@ async function startApp(settings, completionCallback) {
799
566
  async function connectRedis() {
800
567
  if (tdcache) {
801
568
  try {
802
- console.log("(Tilebot) Connecting Redis...");
569
+ winston.info("(Tilebot) Connecting Redis...");
803
570
  await tdcache.connect();
804
571
  }
805
572
  catch (error) {
806
573
  tdcache = null;
807
- console.error("(Tilebot) Redis connection error:", error);
574
+ winston.error("(Tilebot) Redis connection error: ", error);
808
575
  process.exit(1);
809
576
  }
810
- console.log("(Tilebot) Redis connected.");
577
+ winston.info("(Tilebot) Redis connected");
811
578
  }
812
579
  return;
813
580
  }
@@ -831,47 +598,10 @@ async function checkRequest(request_id, id_project) {
831
598
  // WARNING! Move this function in models/TiledeskChatbotUtil.js
832
599
  }
833
600
 
834
- /**
835
- * A stub to send message to the "ext/botId" endpoint, hosted by tilebot on:
836
- * /${TILEBOT_ROUTE}/ext/${botId}
837
- *
838
- * @param {Object} message. The message to send
839
- * @param {string} botId. Tiledesk botId
840
- * @param {string} token. User token
841
- */
842
- function sendMessageToBot(TILEBOT_ENDPOINT, message, botId, callback) {
843
- const url = `${TILEBOT_ENDPOINT}/ext/${botId}`;
844
- console.log("sendMessageToBot URL", url);
845
- const HTTPREQUEST = {
846
- url: url,
847
- headers: {
848
- 'Content-Type': 'application/json'
849
- },
850
- json: message,
851
- method: 'POST'
852
- };
853
- myrequest(
854
- HTTPREQUEST,
855
- function (err, resbody) {
856
- if (err) {
857
- if (callback) {
858
- callback(err);
859
- }
860
- }
861
- else {
862
- if (callback) {
863
- callback(null, resbody);
864
- }
865
- }
866
- }, false
867
- );
868
- }
869
-
870
601
  function myrequest(options, callback, log) {
871
- if (log) {
872
- console.log("API URL:", options.url);
873
- console.log("** Options:", JSON.stringify(options));
874
- }
602
+ winston.verbose("(tybotRoute) myrequest API URL:" + options.url);
603
+ winston.debug("(tybotRoute) myrequest Options:", options);
604
+
875
605
  axios(
876
606
  {
877
607
  url: options.url,
@@ -881,11 +611,8 @@ function myrequest(options, callback, log) {
881
611
  headers: options.headers
882
612
  })
883
613
  .then((res) => {
884
- if (log) {
885
- console.log("Response for url:", options.url);
886
- console.log("Response headers:\n", JSON.stringify(res.headers));
887
- //console.log("******** Response for url:", res);
888
- }
614
+ winston.verbose("Response for url:" + options.url);
615
+ winston.debug("Response headers:\n", res.headers);
889
616
  if (res && res.status == 200 && res.data) {
890
617
  if (callback) {
891
618
  callback(null, res.data);
@@ -896,9 +623,8 @@ function myrequest(options, callback, log) {
896
623
  callback(TiledeskClient.getErr({ message: "Response status not 200" }, options, res), null, null);
897
624
  }
898
625
  }
899
- })
900
- .catch((error) => {
901
- console.error("(tybotRoute index) An error occurred:", JSON.stringify(error), "url:", options.url);
626
+ }).catch((error) => {
627
+ winston.error("(tybotRoute index) An error occurred: ", error);
902
628
  if (callback) {
903
629
  callback(error, null, null);
904
630
  }