@tiledesk/tiledesk-tybot-connector 0.5.0 → 2.0.0

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 (100) hide show
  1. package/ExtApi.js +4 -83
  2. package/ExtUtil.js +0 -1
  3. package/Logger.js +105 -0
  4. package/TdCache.js +5 -3
  5. package/TiledeskClientTest.js +5 -28
  6. package/TiledeskExpression.js +6 -47
  7. package/{models → engine}/IntentForm.js +30 -44
  8. package/{models → engine}/IntentsMachineFactory.js +5 -4
  9. package/{models → engine}/MongodbBotsDataSource.js +31 -55
  10. package/{models → engine}/MongodbIntentsMachine.js +6 -5
  11. package/{models → engine}/TiledeskChatbot.js +82 -259
  12. package/{models → engine}/TiledeskChatbotConst.js +9 -0
  13. package/{models → engine}/TiledeskIntentsMachine.js +5 -15
  14. package/{models → engine/mock}/MockBotsDataSource.js +3 -19
  15. package/{models → engine/mock}/MockTdCache.js +0 -9
  16. package/index.js +103 -380
  17. package/logs/app.log +12723 -277
  18. package/logs/app1.log +62258 -0
  19. package/logs/app2.log +46280 -0
  20. package/logs/app3.log +31686 -0
  21. package/logs/app4.log +46163 -0
  22. package/logs/app5.log +33173 -0
  23. package/models/faq.js +2 -5
  24. package/package.json +5 -2
  25. package/{TiledeskServices → services}/AIService.js +4 -3
  26. package/{models/faqKbService.js → services/FaqKbService.js} +1 -2
  27. package/{models/faqService.js → services/FaqService.js} +4 -3
  28. package/services/IntegrationService.js +43 -0
  29. package/services/TilebotService.js +47 -0
  30. package/tiledeskChatbotPlugs/DirectivesChatbotPlug.js +49 -135
  31. package/tiledeskChatbotPlugs/FillParamsChatbotPlug.js +8 -14
  32. package/tiledeskChatbotPlugs/Filler.js +0 -1
  33. package/tiledeskChatbotPlugs/MarkbotChatbotPlug.js +12 -20
  34. package/tiledeskChatbotPlugs/MessagePipeline.js +5 -15
  35. package/tiledeskChatbotPlugs/SplitsChatbotPlug.js +4 -13
  36. package/tiledeskChatbotPlugs/TiledeskRequestVariables.js +1 -1
  37. package/tiledeskChatbotPlugs/WebhookChatbotPlug.js +21 -89
  38. package/tiledeskChatbotPlugs/directives/DEPRECATED_DirSetAttribute.js +1 -1
  39. package/tiledeskChatbotPlugs/directives/DirAddTags.js +23 -140
  40. package/tiledeskChatbotPlugs/directives/DirAiPrompt.js +42 -128
  41. package/tiledeskChatbotPlugs/directives/DirAskGPT.js +37 -127
  42. package/tiledeskChatbotPlugs/directives/DirAskGPTV2.js +52 -145
  43. package/tiledeskChatbotPlugs/directives/DirAssign.js +12 -23
  44. package/tiledeskChatbotPlugs/directives/DirAssignFromFunction.js +16 -12
  45. package/tiledeskChatbotPlugs/directives/DirAssistant.js +56 -198
  46. package/tiledeskChatbotPlugs/directives/DirBrevo.js +41 -101
  47. package/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js +9 -19
  48. package/tiledeskChatbotPlugs/directives/DirClearTranscript.js +1 -1
  49. package/tiledeskChatbotPlugs/directives/DirClose.js +4 -2
  50. package/tiledeskChatbotPlugs/directives/DirCode.js +16 -23
  51. package/tiledeskChatbotPlugs/directives/DirCondition.js +19 -25
  52. package/tiledeskChatbotPlugs/directives/DirConnectBlock.js +9 -82
  53. package/tiledeskChatbotPlugs/directives/DirContactUpdate.js +10 -22
  54. package/tiledeskChatbotPlugs/directives/DirCustomerio.js +34 -89
  55. package/tiledeskChatbotPlugs/directives/DirDeflectToHelpCenter.js +17 -22
  56. package/tiledeskChatbotPlugs/directives/DirDeleteVariable.js +8 -8
  57. package/tiledeskChatbotPlugs/directives/DirDepartment.js +13 -12
  58. package/tiledeskChatbotPlugs/directives/DirDisableInputText.js +2 -6
  59. package/tiledeskChatbotPlugs/directives/DirFireTiledeskEvent.js +4 -4
  60. package/tiledeskChatbotPlugs/directives/DirForm.js +17 -24
  61. package/tiledeskChatbotPlugs/directives/DirGptTask.js +49 -139
  62. package/tiledeskChatbotPlugs/directives/DirGptTask_OLD.js +8 -53
  63. package/tiledeskChatbotPlugs/directives/DirHubspot.js +31 -91
  64. package/tiledeskChatbotPlugs/directives/DirIfOnlineAgents.js +19 -26
  65. package/tiledeskChatbotPlugs/directives/DirIfOnlineAgentsV2.js +24 -78
  66. package/tiledeskChatbotPlugs/directives/DirIfOpenHours.js +17 -68
  67. package/tiledeskChatbotPlugs/directives/DirIntent.js +6 -100
  68. package/tiledeskChatbotPlugs/directives/DirJSONCondition.js +15 -14
  69. package/tiledeskChatbotPlugs/directives/DirLockIntent.js +7 -12
  70. package/tiledeskChatbotPlugs/directives/DirMake.js +21 -53
  71. package/tiledeskChatbotPlugs/directives/DirMessage.js +35 -28
  72. package/tiledeskChatbotPlugs/directives/DirMessageToBot.js +8 -87
  73. package/tiledeskChatbotPlugs/directives/DirMoveToAgent.js +6 -4
  74. package/tiledeskChatbotPlugs/directives/DirMoveToUnassigned.js +6 -4
  75. package/tiledeskChatbotPlugs/directives/DirQapla.js +26 -120
  76. package/tiledeskChatbotPlugs/directives/DirRandomReply.js +11 -19
  77. package/tiledeskChatbotPlugs/directives/DirRemoveCurrentBot.js +4 -0
  78. package/tiledeskChatbotPlugs/directives/DirReplaceBot.js +5 -2
  79. package/tiledeskChatbotPlugs/directives/DirReplaceBotV2.js +12 -58
  80. package/tiledeskChatbotPlugs/directives/DirReplaceBotV3.js +11 -57
  81. package/tiledeskChatbotPlugs/directives/DirReply.js +36 -30
  82. package/tiledeskChatbotPlugs/directives/DirReplyV2.js +30 -72
  83. package/tiledeskChatbotPlugs/directives/DirSendEmail.js +9 -10
  84. package/tiledeskChatbotPlugs/directives/DirSendWhatsapp.js +15 -40
  85. package/tiledeskChatbotPlugs/directives/DirSetAttribute.js +8 -5
  86. package/tiledeskChatbotPlugs/directives/DirSetAttributeV2.js +25 -113
  87. package/tiledeskChatbotPlugs/directives/DirSetConversationTags.js +14 -13
  88. package/tiledeskChatbotPlugs/directives/DirUnlockIntent.js +3 -3
  89. package/tiledeskChatbotPlugs/directives/DirWait.js +5 -6
  90. package/tiledeskChatbotPlugs/directives/DirWebRequest.js +14 -49
  91. package/tiledeskChatbotPlugs/directives/DirWebRequestV2.js +22 -77
  92. package/tiledeskChatbotPlugs/directives/DirWebRequestV2_old.js +1 -1
  93. package/tiledeskChatbotPlugs/directives/DirWebResponse.js +11 -14
  94. package/tiledeskChatbotPlugs/directives/DirWhatsappByAttribute.js +13 -42
  95. package/tiledeskChatbotPlugs/directives/Directives.js +0 -3
  96. package/utils/HttpUtils.js +128 -0
  97. package/{models → utils}/TiledeskChatbotUtil.js +164 -234
  98. package/utils/winston.js +42 -0
  99. package/TiledeskServices/utils.js +0 -99
  100. /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,18 @@ 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));}
144
115
 
145
116
  let intentsMachine;
146
117
  let backupMachine;
147
118
  if (!staticBots) {
148
119
  intentsMachine = IntentsMachineFactory.getMachine(bot, botId, projectId, log);
149
120
  backupMachine = IntentsMachineFactory.getBackupMachine(bot, botId, projectId, log);
150
- if (log) {console.log("Created backupMachine:", backupMachine);}
121
+ winston.debug("(tybotRoute) Created backupMachine:", backupMachine)
151
122
  }
152
123
  else {
153
124
  intentsMachine = {}
154
125
  }
155
126
 
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
127
  const chatbot = new TiledeskChatbot({
177
128
  botsDataSource: botsDS,
178
129
  intentsFinder: intentsMachine,
@@ -189,11 +140,8 @@ router.post('/ext/:botid', async (req, res) => {
189
140
  MAX_EXECUTION_TIME: MAX_EXECUTION_TIME,
190
141
  log: log
191
142
  });
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
- // }
143
+ winston.verbose("(tybotRoute) Message text: " + message.text)
144
+
197
145
  await TiledeskChatbotUtil.updateRequestAttributes(chatbot, token, message, projectId, requestId);
198
146
  if (requestId.startsWith("support-group-")) {
199
147
  await TiledeskChatbotUtil.updateConversationTranscript(chatbot, message);
@@ -204,23 +152,19 @@ router.post('/ext/:botid', async (req, res) => {
204
152
  reply = await chatbot.replyToMessage(message);
205
153
  }
206
154
  catch(err) {
207
- console.error("(tybotRoute) An error occurred replying to message:", JSON.stringify(message), "\nError:", err );
155
+ winston.error("(tybotRoute) An error occurred replying to message: ", err);
208
156
  return;
209
157
  }
210
158
  if (!reply) {
211
- if (log) { console.log("(tybotRoute) No reply. Stop flow.") }
159
+ winston.verbose("(tybotRoute) No reply. Stop flow.")
212
160
  return;
213
161
  }
214
162
 
215
- // console.log("reply is:", reply);
216
- // if (reply.attributes.intent_info.intent_id) {
217
- // process.exit(1)
218
- // }
219
163
  if (reply.actions && reply.actions.length > 0) { // structured actions (coming from chatbot designer)
220
164
  try {
221
- if (log) {console.log("the actions:", JSON.stringify(reply.actions));}
165
+ winston.debug("(tybotRoute) Reply actions: ", reply.actions)
222
166
  let directives = TiledeskChatbotUtil.actionsToDirectives(reply.actions);
223
- if (log) {console.log("the directives:", JSON.stringify(directives));}
167
+ winston.debug("(tybotRoute) the directives:", directives)
224
168
  let directivesPlug = new DirectivesChatbotPlug(
225
169
  {
226
170
  message: message,
@@ -237,15 +181,15 @@ router.post('/ext/:botid', async (req, res) => {
237
181
  }
238
182
  );
239
183
  directivesPlug.processDirectives( () => {
240
- if (log) {console.log("Actions - Directives executed.");}
184
+ winston.verbose("(tybotRoute) Actions - Directives executed.");
241
185
  });
242
186
  }
243
187
  catch (error) {
244
- console.error("Error while processing actions:", error);
188
+ winston.error("(tybotRoute) Error while processing actions:", error);
245
189
  }
246
190
  }
247
191
  else { // text answer (parse text directives to get actions)
248
- if (log) {console.log("an answer:", reply.text);}
192
+ winston.verbose("(tybotRoute) No actions. Reply text: ", reply.text)
249
193
  reply.triggeredByMessageId = messageId;
250
194
  if (!reply.attributes) {
251
195
  reply.attributes = {}
@@ -260,9 +204,7 @@ router.post('/ext/:botid', async (req, res) => {
260
204
  log: false
261
205
  });
262
206
  apiext.sendSupportMessageExt(reply, projectId, requestId, token, () => {
263
- if (log) {
264
- //console.log("SupportMessageExt() reply sent:", JSON.stringify(reply));
265
- }
207
+ winston.verbose("(tybotRoute) sendSupportMessageExt reply sent: ", reply)
266
208
  });
267
209
  }
268
210
 
@@ -273,13 +215,15 @@ router.post('/ext/:projectId/requests/:requestId/messages', async (req, res) =>
273
215
  const projectId = req.params.projectId;
274
216
  const requestId = req.params.requestId;
275
217
  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);}
218
+
219
+ winston.verbose("(tybotRoute) POST /ext/:projectId/requests/:requestId/messages called: " + requestId)
220
+ winston.debug("(tybotRoute) projectId " + projectId)
221
+ winston.debug("(tybotRoute) token " + token)
222
+ winston.debug("(tybotRoute) req.headers " + req.headers)
223
+ winston.debug("(tybotRoute) projectId " + projectId)
280
224
 
281
225
  let answer = req.body;
282
- if (log) {console.log("/ext => answer on sendSupportMessageExt:", JSON.stringify(answer));}
226
+ winston.verbose("(tybotRoute) answer on sendSupportMessageExt: ", answer);
283
227
  const tdclient = new TiledeskClient({
284
228
  projectId: projectId,
285
229
  token: token,
@@ -287,81 +231,57 @@ router.post('/ext/:projectId/requests/:requestId/messages', async (req, res) =>
287
231
  APIKEY: "___",
288
232
  log: false
289
233
  });
234
+
290
235
  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
236
  try {
310
237
  request = await tdclient.getRequestById(requestId);
311
- // console.log("Cache request found.");
312
238
  }
313
239
  catch(err) {
314
- console.error("/ext => Request not found:", requestId);
240
+ winston.error("(tybotRoute) request not found with id " + requestId);
315
241
  }
316
- // if (log) {console.log("(No tdcache) Got request with APIs");}
317
- // }
242
+
318
243
  if (!request) {
319
- if (log) {console.log("/ext => Creating new Request. Chatbot-pure directives still work. Tiledesk specific directives don't");}
244
+ winston.verbose("(tybotRoute) Creating new Request. Chatbot-pure directives still work. Tiledesk specific directives don't")
320
245
  const request_botId_key = "tilebot:botId_requests:" + requestId;
321
246
  const botId = await tdcache.get(request_botId_key);
322
- if (log) {console.log("/ext => current botId [" + request_botId_key + "]:", botId);}
247
+ winston.verbose("(tybotRoute) current botId [" + request_botId_key + "]:" + botId)
323
248
  request = {
324
249
  request_id: requestId,
325
250
  id_project: projectId,
326
251
  bot_id: botId
327
252
  }
328
253
  }
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
- }
254
+ winston.debug("(tybotRoute) request: ", request);
255
+ winston.debug("(tybotRoute) API_ENDPOINT: " + API_ENDPOINT);
256
+ winston.debug("(tybotRoute) request: " + TILEBOT_ENDPOINT);
257
+
334
258
  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));}
259
+
338
260
  const original_answer_text = answer.text;
339
261
  const bot_answer = await ExtUtil.execPipelineExt(request, answer, directivesPlug, tdcache, log);
340
- if (log) {console.log("/ext => bot_answer", JSON.stringify(bot_answer))}
262
+ winston.debug("(tybotRoute) bot_answer: ", bot_answer);
263
+
341
264
  if (bot_answer) {
342
- if (log) {console.log("/ext => adding to bot_answer original_answer_text:", JSON.stringify(original_answer_text));}
265
+ winston.debug("(tybotRoute) adding to bot_answer original_answer_text: ", original_answer_text);
343
266
  if (!bot_answer.attributes) {
344
267
  bot_answer.attributes = {};
345
268
  }
346
- // if (!bot_answer.text) {
347
- // bot_answer.text = "..."
348
- // }
269
+
349
270
  bot_answer.attributes["_raw_message"] = original_answer_text;
350
- // if (log) {console.log("bot_answer", JSON.stringify(bot_answer));}
351
271
  tdclient.sendSupportMessage(requestId, bot_answer, (err, response) => {
352
- if (log) {console.log("/ext => bot_answer sent:", JSON.stringify(bot_answer));}
272
+ winston.verbose("(tybotRoute) Bot answer sent")
353
273
  if (err) {
354
- console.error("/ext => Error sending message", JSON.stringify(err));
274
+ winston.error("(tybotRoute) Error sending message", err);
355
275
  }
356
- directivesPlug.processDirectives( () => {
357
- if (log) {console.log("After message - Directives executed.");}
276
+ directivesPlug.processDirectives(() => {
277
+ winston.verbose("(tybotRoute) Directives executed")
358
278
  });
359
279
  });
360
280
  }
361
281
  else {
362
- if (log) {console.log("/ext => !bot_answer");}
363
- directivesPlug.processDirectives( () => {
364
- if (log) {console.log("Directives executed.");}
282
+ winston.verbose("(tybotRoute) No bot_answer")
283
+ directivesPlug.processDirectives(() => {
284
+ winston.verbose("(tybotRoute) Directives executed")
365
285
  });
366
286
  }
367
287
 
@@ -391,73 +311,12 @@ router.get('/ext/reserved/parameters/requests/:requestid', async (req, res) => {
391
311
  res.send(parameters);
392
312
  }
393
313
  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
314
  const userParams = TiledeskChatbotUtil.userFlowAttributes(parameters);
440
315
  res.send(userParams);
441
316
  }
442
317
  });
443
318
 
444
319
  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
320
 
462
321
  const requestId = req.params.requestid;
463
322
  if (!requestId) {
@@ -467,14 +326,13 @@ router.get('/ext/parameters/requests/:requestid', async (req, res) => {
467
326
  const request_parts = requestId.split("-");
468
327
  if (request_parts && request_parts.length >= 4) {
469
328
  const project_id = request_parts[2];
470
- // console.log("ProjectId:", project_id);
471
329
  if (project_id !== "656054000410fa00132e5dcc") { //&& project_id !== "ANOTHER P_ID"
472
330
  res.status(401).send("Unauthorized");
473
331
  return;
474
332
  }
475
333
  }
476
- else if (!request_parts || ( request_parts && request_parts.length < 4) ) {
477
- res.status(500).send("Invalid request ID");
334
+ else if (!request_parts || (request_parts && request_parts.length < 4) ) {
335
+ res.status(500).send("Invalid request id " + requestId);
478
336
  return;
479
337
  }
480
338
  const parameters = await TiledeskChatbot.allParametersStatic(tdcache, requestId);
@@ -486,45 +344,7 @@ router.get('/ext/parameters/requests/:requestid', async (req, res) => {
486
344
  res.send(parameters);
487
345
  }
488
346
  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
- }
347
+ const userParams = TiledeskChatbotUtil.userFlowAttributes(parameters);
528
348
  res.send(userParams);
529
349
  }
530
350
  });
@@ -538,7 +358,8 @@ router.get('/test/webrequest/get/plain/:username', async (req, res) => {
538
358
  });
539
359
 
540
360
  router.post('/test/webrequest/post/plain', async (req, res) => {
541
- console.log("/post/plain req.body:", req.body);
361
+ winston.verbose("(tybotRoute) POST /test/webrequest/post/plain called");
362
+ winston.debug("(tybotRoute) POST /test/webrequest/post/plain req.body:", req.body);
542
363
  if (req && req.body && req.body.name) {
543
364
  res.send("Your name is " + req.body.name);
544
365
  }
@@ -548,16 +369,14 @@ router.post('/test/webrequest/post/plain', async (req, res) => {
548
369
  });
549
370
 
550
371
  router.post('/echobot', (req, res) => {
551
- //console.log('echobot message body.payload: ', JSON.stringify(req.body.payload));
372
+ winston.verbose("(tybotRoute) POST /echobot called");
373
+ winston.debug("(tybotRoute) POST /echobot req.body: ", req.body.payload);
374
+
552
375
  const message = req.body.payload;
553
376
  const token = req.body.token;
554
377
  const requestId = message.request.request_id;
555
378
  const projectId = message.id_project;
556
379
 
557
- // console.log("/echobot projectId:", projectId);
558
- // console.log("/echobot requestId:", requestId);
559
- // console.log("/echobot token:", token);
560
-
561
380
  const tdclient = new TiledeskClient({
562
381
  projectId: projectId,
563
382
  token: token,
@@ -574,10 +393,7 @@ router.post('/echobot', (req, res) => {
574
393
  }
575
394
  tdclient.sendSupportMessage(requestId, msg, (err, response) => {
576
395
  if (err) {
577
- console.error("Error sending message:"); //, err);
578
- }
579
- else {
580
- //console.log("message sent.");
396
+ winston.error("(tybotRoute) Error sending message"); //, err);
581
397
  }
582
398
  });
583
399
  });
@@ -588,6 +404,10 @@ router.post('/block/:project_id/:bot_id/:block_id', async (req, res) => {
588
404
  const bot_id = req.params.bot_id;
589
405
  const block_id = req.params.block_id;
590
406
  const body = req.body;
407
+
408
+ winston.verbose("(tybotRoute) POST /block/:project_id/:bot_id/:block_id called");
409
+ winston.debug("(tybotRoute) POST /block/:project_id/:bot_id/:block_id req.body: ", body);
410
+
591
411
  const async = body.async;
592
412
  const token = body.token;
593
413
  delete body.async;
@@ -614,88 +434,49 @@ router.post('/block/:project_id/:bot_id/:block_id', async (req, res) => {
614
434
  }
615
435
 
616
436
  if (async) {
617
- console.log("Async webhook");
618
- sendMessageToBot(TILEBOT_ENDPOINT, message, bot_id, (err, resbody) => {
437
+ winston.verbose("Async webhook");
438
+ tilebotService.sendMessageToBot(message, bot_id, (err, resbody) => {
619
439
  if (err) {
620
- console.error("Async err:\n", err);
440
+ winston.error("Async webhook err:\n", err);
621
441
  return res.status(500).send({ success: false, error: err });
622
442
  }
623
443
  return res.status(200).send({ success: true });
624
444
  })
625
445
  } else {
626
446
 
627
- console.log("Sync webhook. Subscribe and await for reply...")
447
+ winston.verbose("Sync webhook. Subscribe and await for reply...")
628
448
  const topic = `/webhooks/${request_id}`;
629
449
 
630
450
  try {
631
451
 
632
452
  const listener = async (message, topic) => {
633
- console.log("Web response is: ", message, "for topic", topic);
453
+ winston.debug("Web response is: " + JSON.stringify(message) + " for topic " + topic);
634
454
  await tdcache.unsubscribe(topic, listener);
635
455
 
636
456
  let json = JSON.parse(message);
637
457
  let status = json.status ? json.status : 200;
638
- console.log("Web response status: ", status);
458
+ winston.debug("Web response status: " + status);
639
459
 
640
460
  return res.status(status).send(json.payload);
641
461
  }
642
462
  await tdcache.subscribe(topic, listener);
643
463
 
644
464
  } catch(err) {
645
- console.error("Error cache subscribe ", err);
465
+ winston.error("Error cache subscribe ", err);
646
466
  return res.status(500).send({ success: false, error: "Error during cache subscription"})
647
467
  }
648
468
 
649
- sendMessageToBot(TILEBOT_ENDPOINT, message, bot_id, () => {
650
- console.log("Sync webhook message sent: ", message);
469
+ tilebotService.sendMessageToBot(message, bot_id, () => {
470
+ winston.debug("Sync webhook message sent: ", message);
651
471
  })
652
472
  }
653
473
 
654
474
  });
655
475
 
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
476
 
696
477
  async function startApp(settings, completionCallback) {
697
- console.log("Starting Tilebot...");
698
- // console.log("Starting Tilebot with Settings:", settings);
478
+ winston.info("(Tilebot) Starting Tilebot..")
479
+
699
480
  if (settings.bots) { // static bots data source
700
481
  staticBots = settings.bots;
701
482
  }
@@ -710,7 +491,7 @@ async function startApp(settings, completionCallback) {
710
491
  }
711
492
  else {
712
493
  API_ENDPOINT = settings.API_ENDPOINT;
713
- console.log("(Tilebot) settings.API_ENDPOINT:", API_ENDPOINT);
494
+ winston.info("(Tilebot) settings.API_ENDPOINT:" + API_ENDPOINT);
714
495
  }
715
496
 
716
497
  if (!settings.TILEBOT_ENDPOINT) {
@@ -719,8 +500,7 @@ async function startApp(settings, completionCallback) {
719
500
  else {
720
501
  TILEBOT_ENDPOINT = settings.TILEBOT_ENDPOINT
721
502
  }
722
- console.log("(Tilebot) settings.TILEBOT_ENDPOINT:", TILEBOT_ENDPOINT);
723
-
503
+ winston.info("(Tilebot) settings.TILEBOT_ENDPOINT:" + TILEBOT_ENDPOINT);
724
504
 
725
505
  if (settings.REDIS_HOST && settings.REDIS_PORT) {
726
506
  tdcache = new TdCache({
@@ -736,8 +516,7 @@ async function startApp(settings, completionCallback) {
736
516
  else {
737
517
  log = true;
738
518
  }
739
- console.log("(Tilebot) log:", log);
740
-
519
+ winston.info("(Tilebot) Log: " + log);
741
520
 
742
521
  if (process.env.CHATBOT_MAX_STEPS) {
743
522
  MAX_STEPS = Number(process.env.CHATBOT_MAX_STEPS);
@@ -747,49 +526,34 @@ async function startApp(settings, completionCallback) {
747
526
  MAX_EXECUTION_TIME = Number(process.env.CHATBOT_MAX_EXECUTION_TIME);// test // prod1000 * 3600 * 4; // 4 hours
748
527
  }
749
528
 
750
- console.log("(Tilebot) MAX_STEPS: ", MAX_STEPS)
751
- console.log("(Tilebot) MAX_EXECUTION_TIME: ", MAX_EXECUTION_TIME)
752
-
529
+ winston.info("(Tilebot) MAX_STEPS: " + MAX_STEPS);
530
+ winston.info("(Tilebot) MAX_EXECUTION_TIME: " + MAX_EXECUTION_TIME);
531
+
753
532
  var pjson = require('./package.json');
754
- console.log("(Tilebot) Starting Tilebot connector v" + pjson.version);
533
+ winston.info("(Tilebot) Starting Tilebot connector v" + pjson.version);
755
534
 
756
535
  if (!staticBots) {
757
- console.log("(Tilebot) Connecting to mongodb...");
536
+ winston.info("(Tilebot) Connecting to MongoDB...");
758
537
  // connection =
759
538
  mongoose.connect(settings.MONGODB_URI, { "useNewUrlParser": true, "autoIndex": false }, async (err) => {
760
539
  if (err) {
761
- console.error('(Tilebot) Failed to connect to MongoDB on ' + settings.MONGODB_URI + " ", err);
540
+ winston.error('(Tilebot) Failed to connect to MongoDB on ' + settings.MONGODB_URI + " ", err);
762
541
  }
763
542
  else {
764
- console.log("(Tilebot) mongodb connection ok.");
543
+ winston.info("(Tilebot) MongoDB Connected");
765
544
  await connectRedis();
766
- console.info("Tilebot started.");
545
+ winston.info("(Tilebot) Tilebot started");
546
+
767
547
  if (completionCallback) {
768
548
  completionCallback();
769
549
  }
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
550
  }
787
551
  });
788
552
  }
789
553
  else {
790
- console.log("(Tilebot) Using static bots.");
554
+ winston.info("(Tilebot) Using static bots");
791
555
  await connectRedis();
792
- console.info("Tilebot started.");
556
+ winston.info("(Tilebot) Tilebot started");
793
557
  if (completionCallback) {
794
558
  completionCallback();
795
559
  }
@@ -799,15 +563,15 @@ async function startApp(settings, completionCallback) {
799
563
  async function connectRedis() {
800
564
  if (tdcache) {
801
565
  try {
802
- console.log("(Tilebot) Connecting Redis...");
566
+ winston.info("(Tilebot) Connecting Redis...");
803
567
  await tdcache.connect();
804
568
  }
805
569
  catch (error) {
806
570
  tdcache = null;
807
- console.error("(Tilebot) Redis connection error:", error);
571
+ winston.error("(Tilebot) Redis connection error: ", error);
808
572
  process.exit(1);
809
573
  }
810
- console.log("(Tilebot) Redis connected.");
574
+ winston.info("(Tilebot) Redis connected");
811
575
  }
812
576
  return;
813
577
  }
@@ -831,47 +595,10 @@ async function checkRequest(request_id, id_project) {
831
595
  // WARNING! Move this function in models/TiledeskChatbotUtil.js
832
596
  }
833
597
 
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
598
  function myrequest(options, callback, log) {
871
- if (log) {
872
- console.log("API URL:", options.url);
873
- console.log("** Options:", JSON.stringify(options));
874
- }
599
+ winston.verbose("(tybotRoute) myrequest API URL:" + options.url);
600
+ winston.debug("(tybotRoute) myrequest Options:", options);
601
+
875
602
  axios(
876
603
  {
877
604
  url: options.url,
@@ -881,11 +608,8 @@ function myrequest(options, callback, log) {
881
608
  headers: options.headers
882
609
  })
883
610
  .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
- }
611
+ winston.verbose("Response for url:" + options.url);
612
+ winston.debug("Response headers:\n", res.headers);
889
613
  if (res && res.status == 200 && res.data) {
890
614
  if (callback) {
891
615
  callback(null, res.data);
@@ -896,9 +620,8 @@ function myrequest(options, callback, log) {
896
620
  callback(TiledeskClient.getErr({ message: "Response status not 200" }, options, res), null, null);
897
621
  }
898
622
  }
899
- })
900
- .catch((error) => {
901
- console.error("(tybotRoute index) An error occurred:", JSON.stringify(error), "url:", options.url);
623
+ }).catch((error) => {
624
+ winston.error("(tybotRoute index) An error occurred: ", error);
902
625
  if (callback) {
903
626
  callback(error, null, null);
904
627
  }