@tiledesk/tiledesk-tybot-connector 0.4.2 → 0.5.0-rc2

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 (87) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/ExtApi.js +3 -13
  3. package/ExtUtil.js +0 -1
  4. package/Logger.js +86 -0
  5. package/TdCache.js +5 -3
  6. package/TiledeskClientTest.js +5 -28
  7. package/TiledeskExpression.js +6 -47
  8. package/index.js +87 -273
  9. package/logs/app.log +12983 -275
  10. package/logs/app1.log +62258 -0
  11. package/logs/app2.log +46280 -0
  12. package/logs/app3.log +28864 -0
  13. package/models/IntentForm.js +30 -44
  14. package/models/IntentsMachineFactory.js +4 -3
  15. package/models/MockBotsDataSource.js +1 -17
  16. package/models/MockTdCache.js +0 -9
  17. package/models/MongodbBotsDataSource.js +29 -53
  18. package/models/MongodbIntentsMachine.js +5 -4
  19. package/models/TiledeskChatbot.js +79 -258
  20. package/models/TiledeskChatbotConst.js +9 -0
  21. package/models/TiledeskChatbotUtil.js +180 -232
  22. package/models/TiledeskIntentsMachine.js +5 -14
  23. package/models/faqKbService.js +0 -1
  24. package/package.json +5 -2
  25. package/tiledeskChatbotPlugs/DirectivesChatbotPlug.js +66 -139
  26. package/tiledeskChatbotPlugs/FillParamsChatbotPlug.js +7 -13
  27. package/tiledeskChatbotPlugs/Filler.js +0 -1
  28. package/tiledeskChatbotPlugs/MarkbotChatbotPlug.js +12 -20
  29. package/tiledeskChatbotPlugs/MessagePipeline.js +5 -15
  30. package/tiledeskChatbotPlugs/SplitsChatbotPlug.js +4 -13
  31. package/tiledeskChatbotPlugs/WebhookChatbotPlug.js +21 -89
  32. package/tiledeskChatbotPlugs/directives/DirAddTags.js +15 -98
  33. package/tiledeskChatbotPlugs/directives/DirAiPrompt.js +3 -3
  34. package/tiledeskChatbotPlugs/directives/DirAskGPT.js +32 -57
  35. package/tiledeskChatbotPlugs/directives/DirAskGPTV2.js +46 -70
  36. package/tiledeskChatbotPlugs/directives/DirAssign.js +11 -22
  37. package/tiledeskChatbotPlugs/directives/DirAssignFromFunction.js +15 -11
  38. package/tiledeskChatbotPlugs/directives/DirAssistant.js +48 -97
  39. package/tiledeskChatbotPlugs/directives/DirBrevo.js +37 -68
  40. package/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js +8 -18
  41. package/tiledeskChatbotPlugs/directives/DirClose.js +3 -1
  42. package/tiledeskChatbotPlugs/directives/DirCode.js +15 -22
  43. package/tiledeskChatbotPlugs/directives/DirCondition.js +18 -24
  44. package/tiledeskChatbotPlugs/directives/DirConnectBlock.js +9 -13
  45. package/tiledeskChatbotPlugs/directives/DirContactUpdate.js +7 -19
  46. package/tiledeskChatbotPlugs/directives/DirCustomerio.js +30 -57
  47. package/tiledeskChatbotPlugs/directives/DirDeflectToHelpCenter.js +15 -20
  48. package/tiledeskChatbotPlugs/directives/DirDeleteVariable.js +7 -7
  49. package/tiledeskChatbotPlugs/directives/DirDepartment.js +13 -12
  50. package/tiledeskChatbotPlugs/directives/DirDisableInputText.js +2 -6
  51. package/tiledeskChatbotPlugs/directives/DirFireTiledeskEvent.js +4 -4
  52. package/tiledeskChatbotPlugs/directives/DirForm.js +15 -22
  53. package/tiledeskChatbotPlugs/directives/DirGptTask.js +38 -65
  54. package/tiledeskChatbotPlugs/directives/DirHubspot.js +27 -58
  55. package/tiledeskChatbotPlugs/directives/DirIfOnlineAgents.js +19 -26
  56. package/tiledeskChatbotPlugs/directives/DirIfOnlineAgentsV2.js +22 -40
  57. package/tiledeskChatbotPlugs/directives/DirIfOpenHours.js +17 -32
  58. package/tiledeskChatbotPlugs/directives/DirIntent.js +16 -33
  59. package/tiledeskChatbotPlugs/directives/DirJSONCondition.js +14 -13
  60. package/tiledeskChatbotPlugs/directives/DirLockIntent.js +7 -12
  61. package/tiledeskChatbotPlugs/directives/DirMake.js +20 -52
  62. package/tiledeskChatbotPlugs/directives/DirMessage.js +35 -28
  63. package/tiledeskChatbotPlugs/directives/DirMessageToBot.js +10 -20
  64. package/tiledeskChatbotPlugs/directives/DirMoveToAgent.js +4 -2
  65. package/tiledeskChatbotPlugs/directives/DirMoveToUnassigned.js +4 -2
  66. package/tiledeskChatbotPlugs/directives/DirQapla.js +21 -50
  67. package/tiledeskChatbotPlugs/directives/DirRandomReply.js +9 -17
  68. package/tiledeskChatbotPlugs/directives/DirRemoveCurrentBot.js +4 -0
  69. package/tiledeskChatbotPlugs/directives/DirReplaceBot.js +4 -1
  70. package/tiledeskChatbotPlugs/directives/DirReplaceBotV2.js +10 -21
  71. package/tiledeskChatbotPlugs/directives/DirReplaceBotV3.js +9 -19
  72. package/tiledeskChatbotPlugs/directives/DirReply.js +32 -35
  73. package/tiledeskChatbotPlugs/directives/DirReplyV2.js +27 -69
  74. package/tiledeskChatbotPlugs/directives/DirSendEmail.js +8 -9
  75. package/tiledeskChatbotPlugs/directives/DirSendWhatsapp.js +13 -12
  76. package/tiledeskChatbotPlugs/directives/DirSetAttribute.js +7 -4
  77. package/tiledeskChatbotPlugs/directives/DirSetAttributeV2.js +22 -75
  78. package/tiledeskChatbotPlugs/directives/DirSetConversationTags.js +14 -13
  79. package/tiledeskChatbotPlugs/directives/DirUnlockIntent.js +3 -3
  80. package/tiledeskChatbotPlugs/directives/DirWait.js +4 -5
  81. package/tiledeskChatbotPlugs/directives/DirWebRequest.js +13 -48
  82. package/tiledeskChatbotPlugs/directives/DirWebRequestV2.js +11 -76
  83. package/tiledeskChatbotPlugs/directives/DirWebResponse.js +34 -7
  84. package/tiledeskChatbotPlugs/directives/DirWhatsappByAttribute.js +11 -14
  85. package/tiledeskChatbotPlugs/directives/Directives.js +1 -3
  86. package/utils/winston.js +42 -0
  87. package/TdCache copy.js +0 -242
package/index.js CHANGED
@@ -1,6 +1,7 @@
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');
@@ -40,24 +41,24 @@ let staticBots;
40
41
 
41
42
  router.post('/ext/:botid', async (req, res) => {
42
43
  const botId = req.params.botid;
43
- if (log) {console.log("(tybotRoute) POST /ext/:botid called: ", botId);}
44
+ winston.verbose("(tybotRoute) POST /ext/:botid called: " + botId)
44
45
  if(!botId || botId === "null" || botId === "undefined"){
45
46
  return res.status(400).send({"success": false, error: "Required parameters botid not found. Value is 'null' or 'undefined'"})
46
47
  }
47
48
 
48
49
  if (req && req.body && req.body.payload && req.body.payload.request && req.body.payload.request.snapshot) {
49
50
  delete req.body.payload.request.snapshot;
50
- console.log("Removed req.body.payload.request.snapshot field");
51
51
  }
52
- if (log) {console.log("REQUEST BODY:", JSON.stringify(req.body));}
52
+ winston.verbose("(tybotRoute) Request Body: ", req.body);
53
53
 
54
+
54
55
  const message = req.body.payload;
55
56
  const messageId = message._id;
56
57
  //const faq_kb = req.body.hook; now it is "bot"
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;
@@ -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,6 +112,8 @@ router.post('/ext/:botid', async (req, res) => {
128
112
  Promise.reject(err);
129
113
  return;
130
114
  });
115
+
116
+ winston.debug("(tybotRoute) Bot found:" + bot)
131
117
  // let bot = null;
132
118
  // try {
133
119
  // // bot = await botsDS.getBotById(botId);
@@ -147,32 +133,12 @@ router.post('/ext/:botid', async (req, res) => {
147
133
  if (!staticBots) {
148
134
  intentsMachine = IntentsMachineFactory.getMachine(bot, botId, projectId, log);
149
135
  backupMachine = IntentsMachineFactory.getBackupMachine(bot, botId, projectId, log);
150
- if (log) {console.log("Created backupMachine:", backupMachine);}
136
+ winston.debug("(tybotRoute) Created backupMachine:", backupMachine)
151
137
  }
152
138
  else {
153
139
  intentsMachine = {}
154
140
  }
155
141
 
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
142
  const chatbot = new TiledeskChatbot({
177
143
  botsDataSource: botsDS,
178
144
  intentsFinder: intentsMachine,
@@ -189,11 +155,8 @@ router.post('/ext/:botid', async (req, res) => {
189
155
  MAX_EXECUTION_TIME: MAX_EXECUTION_TIME,
190
156
  log: log
191
157
  });
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
- // }
158
+ winston.verbose("(tybotRoute) Message text: " + message.text)
159
+
197
160
  await TiledeskChatbotUtil.updateRequestAttributes(chatbot, token, message, projectId, requestId);
198
161
  if (requestId.startsWith("support-group-")) {
199
162
  await TiledeskChatbotUtil.updateConversationTranscript(chatbot, message);
@@ -204,7 +167,7 @@ router.post('/ext/:botid', async (req, res) => {
204
167
  reply = await chatbot.replyToMessage(message);
205
168
  }
206
169
  catch(err) {
207
- console.error("(tybotRoute) An error occurred replying to message:", JSON.stringify(message), "\nError:", err );
170
+ winston.error("(tybotRoute) An error occurred replying to message: ", err);
208
171
  return;
209
172
  }
210
173
  if (!reply) {
@@ -212,15 +175,11 @@ router.post('/ext/:botid', async (req, res) => {
212
175
  return;
213
176
  }
214
177
 
215
- // console.log("reply is:", reply);
216
- // if (reply.attributes.intent_info.intent_id) {
217
- // process.exit(1)
218
- // }
219
178
  if (reply.actions && reply.actions.length > 0) { // structured actions (coming from chatbot designer)
220
179
  try {
221
- if (log) {console.log("the actions:", JSON.stringify(reply.actions));}
180
+ winston.debug("(tybotRoute) Reply actions: ", reply.actions)
222
181
  let directives = TiledeskChatbotUtil.actionsToDirectives(reply.actions);
223
- if (log) {console.log("the directives:", JSON.stringify(directives));}
182
+ winston.debug("(tybotRoute) the directives:", directives)
224
183
  let directivesPlug = new DirectivesChatbotPlug(
225
184
  {
226
185
  message: message,
@@ -237,15 +196,15 @@ router.post('/ext/:botid', async (req, res) => {
237
196
  }
238
197
  );
239
198
  directivesPlug.processDirectives( () => {
240
- if (log) {console.log("Actions - Directives executed.");}
199
+ winston.verbose("(tybotRoute) Actions - Directives executed.");
241
200
  });
242
201
  }
243
202
  catch (error) {
244
- console.error("Error while processing actions:", error);
203
+ winston.error("(tybotRoute) Error while processing actions:", error);
245
204
  }
246
205
  }
247
206
  else { // text answer (parse text directives to get actions)
248
- if (log) {console.log("an answer:", reply.text);}
207
+ winston.verbose("(tybotRoute) No actions. Reply text: ", reply.text)
249
208
  reply.triggeredByMessageId = messageId;
250
209
  if (!reply.attributes) {
251
210
  reply.attributes = {}
@@ -260,9 +219,7 @@ router.post('/ext/:botid', async (req, res) => {
260
219
  log: false
261
220
  });
262
221
  apiext.sendSupportMessageExt(reply, projectId, requestId, token, () => {
263
- if (log) {
264
- //console.log("SupportMessageExt() reply sent:", JSON.stringify(reply));
265
- }
222
+ winston.verbose("(tybotRoute) sendSupportMessageExt reply sent: ", reply)
266
223
  });
267
224
  }
268
225
 
@@ -273,13 +230,15 @@ router.post('/ext/:projectId/requests/:requestId/messages', async (req, res) =>
273
230
  const projectId = req.params.projectId;
274
231
  const requestId = req.params.requestId;
275
232
  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);}
233
+
234
+ winston.verbose("(tybotRoute) POST /ext/:projectId/requests/:requestId/messages called: " + requestId)
235
+ winston.debug("(tybotRoute) projectId " + projectId)
236
+ winston.debug("(tybotRoute) token " + token)
237
+ winston.debug("(tybotRoute) req.headers " + req.headers)
238
+ winston.debug("(tybotRoute) projectId " + projectId)
280
239
 
281
240
  let answer = req.body;
282
- if (log) {console.log("/ext => answer on sendSupportMessageExt:", JSON.stringify(answer));}
241
+ winston.verbose("(tybotRoute) answer on sendSupportMessageExt: ", answer);
283
242
  const tdclient = new TiledeskClient({
284
243
  projectId: projectId,
285
244
  token: token,
@@ -287,81 +246,57 @@ router.post('/ext/:projectId/requests/:requestId/messages', async (req, res) =>
287
246
  APIKEY: "___",
288
247
  log: false
289
248
  });
249
+
290
250
  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
251
  try {
310
252
  request = await tdclient.getRequestById(requestId);
311
- // console.log("Cache request found.");
312
253
  }
313
254
  catch(err) {
314
- console.error("/ext => Request not found:", requestId);
255
+ winston.error("(tybotRoute) request not found with id " + requestId);
315
256
  }
316
- // if (log) {console.log("(No tdcache) Got request with APIs");}
317
- // }
257
+
318
258
  if (!request) {
319
- if (log) {console.log("/ext => Creating new Request. Chatbot-pure directives still work. Tiledesk specific directives don't");}
259
+ winston.verbose("(tybotRoute) Creating new Request. Chatbot-pure directives still work. Tiledesk specific directives don't")
320
260
  const request_botId_key = "tilebot:botId_requests:" + requestId;
321
261
  const botId = await tdcache.get(request_botId_key);
322
- if (log) {console.log("/ext => current botId [" + request_botId_key + "]:", botId);}
262
+ winston.verbose("(tybotRoute) current botId [" + request_botId_key + "]:" + botId)
323
263
  request = {
324
264
  request_id: requestId,
325
265
  id_project: projectId,
326
266
  bot_id: botId
327
267
  }
328
268
  }
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
- }
269
+ winston.debug("(tybotRoute) request: ", request);
270
+ winston.debug("(tybotRoute) API_ENDPOINT: " + API_ENDPOINT);
271
+ winston.debug("(tybotRoute) request: " + TILEBOT_ENDPOINT);
272
+
334
273
  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));}
274
+
338
275
  const original_answer_text = answer.text;
339
276
  const bot_answer = await ExtUtil.execPipelineExt(request, answer, directivesPlug, tdcache, log);
340
- if (log) {console.log("/ext => bot_answer", JSON.stringify(bot_answer))}
277
+ winston.debug("(tybotRoute) bot_answer: ", bot_answer);
278
+
341
279
  if (bot_answer) {
342
- if (log) {console.log("/ext => adding to bot_answer original_answer_text:", JSON.stringify(original_answer_text));}
280
+ winston.debug("(tybotRoute) adding to bot_answer original_answer_text: ", original_answer_text);
343
281
  if (!bot_answer.attributes) {
344
282
  bot_answer.attributes = {};
345
283
  }
346
- // if (!bot_answer.text) {
347
- // bot_answer.text = "..."
348
- // }
284
+
349
285
  bot_answer.attributes["_raw_message"] = original_answer_text;
350
- // if (log) {console.log("bot_answer", JSON.stringify(bot_answer));}
351
286
  tdclient.sendSupportMessage(requestId, bot_answer, (err, response) => {
352
- if (log) {console.log("/ext => bot_answer sent:", JSON.stringify(bot_answer));}
287
+ winston.verbose("(tybotRoute) Bot answer sent")
353
288
  if (err) {
354
- console.error("/ext => Error sending message", JSON.stringify(err));
289
+ winston.error("(tybotRoute) Error sending message", err);
355
290
  }
356
- directivesPlug.processDirectives( () => {
357
- if (log) {console.log("After message - Directives executed.");}
291
+ directivesPlug.processDirectives(() => {
292
+ winston.verbose("(tybotRoute) Directives executed")
358
293
  });
359
294
  });
360
295
  }
361
296
  else {
362
- if (log) {console.log("/ext => !bot_answer");}
363
- directivesPlug.processDirectives( () => {
364
- if (log) {console.log("Directives executed.");}
297
+ winston.verbose("(tybotRoute) No bot_answer")
298
+ directivesPlug.processDirectives(() => {
299
+ winston.verbose("(tybotRoute) Directives executed")
365
300
  });
366
301
  }
367
302
 
@@ -391,73 +326,12 @@ router.get('/ext/reserved/parameters/requests/:requestid', async (req, res) => {
391
326
  res.send(parameters);
392
327
  }
393
328
  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
329
  const userParams = TiledeskChatbotUtil.userFlowAttributes(parameters);
440
330
  res.send(userParams);
441
331
  }
442
332
  });
443
333
 
444
334
  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
335
 
462
336
  const requestId = req.params.requestid;
463
337
  if (!requestId) {
@@ -467,14 +341,13 @@ router.get('/ext/parameters/requests/:requestid', async (req, res) => {
467
341
  const request_parts = requestId.split("-");
468
342
  if (request_parts && request_parts.length >= 4) {
469
343
  const project_id = request_parts[2];
470
- // console.log("ProjectId:", project_id);
471
344
  if (project_id !== "656054000410fa00132e5dcc") { //&& project_id !== "ANOTHER P_ID"
472
345
  res.status(401).send("Unauthorized");
473
346
  return;
474
347
  }
475
348
  }
476
- else if (!request_parts || ( request_parts && request_parts.length < 4) ) {
477
- res.status(500).send("Invalid request ID");
349
+ else if (!request_parts || (request_parts && request_parts.length < 4) ) {
350
+ res.status(500).send("Invalid request id " + requestId);
478
351
  return;
479
352
  }
480
353
  const parameters = await TiledeskChatbot.allParametersStatic(tdcache, requestId);
@@ -486,45 +359,7 @@ router.get('/ext/parameters/requests/:requestid', async (req, res) => {
486
359
  res.send(parameters);
487
360
  }
488
361
  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
- }
362
+ const userParams = TiledeskChatbotUtil.userFlowAttributes(parameters);
528
363
  res.send(userParams);
529
364
  }
530
365
  });
@@ -538,7 +373,8 @@ router.get('/test/webrequest/get/plain/:username', async (req, res) => {
538
373
  });
539
374
 
540
375
  router.post('/test/webrequest/post/plain', async (req, res) => {
541
- console.log("/post/plain req.body:", req.body);
376
+ winston.verbose("(tybotRoute) POST /test/webrequest/post/plain called");
377
+ winston.debug("(tybotRoute) POST /test/webrequest/post/plain req.body:", req.body);
542
378
  if (req && req.body && req.body.name) {
543
379
  res.send("Your name is " + req.body.name);
544
380
  }
@@ -548,16 +384,14 @@ router.post('/test/webrequest/post/plain', async (req, res) => {
548
384
  });
549
385
 
550
386
  router.post('/echobot', (req, res) => {
551
- //console.log('echobot message body.payload: ', JSON.stringify(req.body.payload));
387
+ winston.verbose("(tybotRoute) POST /echobot called");
388
+ winston.debug("(tybotRoute) POST /echobot req.body: ", req.body.payload);
389
+
552
390
  const message = req.body.payload;
553
391
  const token = req.body.token;
554
392
  const requestId = message.request.request_id;
555
393
  const projectId = message.id_project;
556
394
 
557
- // console.log("/echobot projectId:", projectId);
558
- // console.log("/echobot requestId:", requestId);
559
- // console.log("/echobot token:", token);
560
-
561
395
  const tdclient = new TiledeskClient({
562
396
  projectId: projectId,
563
397
  token: token,
@@ -574,10 +408,7 @@ router.post('/echobot', (req, res) => {
574
408
  }
575
409
  tdclient.sendSupportMessage(requestId, msg, (err, response) => {
576
410
  if (err) {
577
- console.error("Error sending message:"); //, err);
578
- }
579
- else {
580
- //console.log("message sent.");
411
+ winston.error("(tybotRoute) Error sending message"); //, err);
581
412
  }
582
413
  });
583
414
  });
@@ -588,6 +419,10 @@ router.post('/block/:project_id/:bot_id/:block_id', async (req, res) => {
588
419
  const bot_id = req.params.bot_id;
589
420
  const block_id = req.params.block_id;
590
421
  const body = req.body;
422
+
423
+ winston.verbose("(tybotRoute) POST /block/:project_id/:bot_id/:block_id called");
424
+ winston.debug("(tybotRoute) POST /block/:project_id/:bot_id/:block_id req.body: ", body);
425
+
591
426
  const async = body.async;
592
427
  const token = body.token;
593
428
  delete body.async;
@@ -694,8 +529,8 @@ router.post('/block/:project_id/:bot_id/:block_id', async (req, res) => {
694
529
  // });
695
530
 
696
531
  async function startApp(settings, completionCallback) {
697
- console.log("Starting Tilebot...");
698
- // console.log("Starting Tilebot with Settings:", settings);
532
+ winston.info("(Tilebot) Starting Tilebot..")
533
+
699
534
  if (settings.bots) { // static bots data source
700
535
  staticBots = settings.bots;
701
536
  }
@@ -710,7 +545,7 @@ async function startApp(settings, completionCallback) {
710
545
  }
711
546
  else {
712
547
  API_ENDPOINT = settings.API_ENDPOINT;
713
- console.log("(Tilebot) settings.API_ENDPOINT:", API_ENDPOINT);
548
+ winston.info("(Tilebot) settings.API_ENDPOINT:" + API_ENDPOINT);
714
549
  }
715
550
 
716
551
  if (!settings.TILEBOT_ENDPOINT) {
@@ -719,8 +554,7 @@ async function startApp(settings, completionCallback) {
719
554
  else {
720
555
  TILEBOT_ENDPOINT = settings.TILEBOT_ENDPOINT
721
556
  }
722
- console.log("(Tilebot) settings.TILEBOT_ENDPOINT:", TILEBOT_ENDPOINT);
723
-
557
+ winston.info("(Tilebot) settings.TILEBOT_ENDPOINT:" + TILEBOT_ENDPOINT);
724
558
 
725
559
  if (settings.REDIS_HOST && settings.REDIS_PORT) {
726
560
  tdcache = new TdCache({
@@ -736,8 +570,7 @@ async function startApp(settings, completionCallback) {
736
570
  else {
737
571
  log = true;
738
572
  }
739
- console.log("(Tilebot) log:", log);
740
-
573
+ winston.info("(Tilebot) Log: " + log);
741
574
 
742
575
  if (process.env.CHATBOT_MAX_STEPS) {
743
576
  MAX_STEPS = Number(process.env.CHATBOT_MAX_STEPS);
@@ -747,49 +580,34 @@ async function startApp(settings, completionCallback) {
747
580
  MAX_EXECUTION_TIME = Number(process.env.CHATBOT_MAX_EXECUTION_TIME);// test // prod1000 * 3600 * 4; // 4 hours
748
581
  }
749
582
 
750
- console.log("(Tilebot) MAX_STEPS: ", MAX_STEPS)
751
- console.log("(Tilebot) MAX_EXECUTION_TIME: ", MAX_EXECUTION_TIME)
752
-
583
+ winston.info("(Tilebot) MAX_STEPS: " + MAX_STEPS);
584
+ winston.info("(Tilebot) MAX_EXECUTION_TIME: " + MAX_EXECUTION_TIME);
585
+
753
586
  var pjson = require('./package.json');
754
- console.log("(Tilebot) Starting Tilebot connector v" + pjson.version);
587
+ winston.info("(Tilebot) Starting Tilebot connector v" + pjson.version);
755
588
 
756
589
  if (!staticBots) {
757
- console.log("(Tilebot) Connecting to mongodb...");
590
+ winston.info("(Tilebot) Connecting to MongoDB...");
758
591
  // connection =
759
592
  mongoose.connect(settings.MONGODB_URI, { "useNewUrlParser": true, "autoIndex": false }, async (err) => {
760
593
  if (err) {
761
- console.error('(Tilebot) Failed to connect to MongoDB on ' + settings.MONGODB_URI + " ", err);
594
+ winston.error('(Tilebot) Failed to connect to MongoDB on ' + settings.MONGODB_URI + " ", err);
762
595
  }
763
596
  else {
764
- console.log("(Tilebot) mongodb connection ok.");
597
+ winston.info("(Tilebot) MongoDB Connected");
765
598
  await connectRedis();
766
- console.info("Tilebot started.");
599
+ winston.info("(Tilebot) Tilebot started");
600
+
767
601
  if (completionCallback) {
768
602
  completionCallback();
769
603
  }
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
604
  }
787
605
  });
788
606
  }
789
607
  else {
790
- console.log("(Tilebot) Using static bots.");
608
+ winston.info("(Tilebot) Using static bots");
791
609
  await connectRedis();
792
- console.info("Tilebot started.");
610
+ winston.info("(Tilebot) Tilebot started");
793
611
  if (completionCallback) {
794
612
  completionCallback();
795
613
  }
@@ -799,15 +617,15 @@ async function startApp(settings, completionCallback) {
799
617
  async function connectRedis() {
800
618
  if (tdcache) {
801
619
  try {
802
- console.log("(Tilebot) Connecting Redis...");
620
+ winston.info("(Tilebot) Connecting Redis...");
803
621
  await tdcache.connect();
804
622
  }
805
623
  catch (error) {
806
624
  tdcache = null;
807
- console.error("(Tilebot) Redis connection error:", error);
625
+ winston.error("(Tilebot) Redis connection error: ", error);
808
626
  process.exit(1);
809
627
  }
810
- console.log("(Tilebot) Redis connected.");
628
+ winston.info("(Tilebot) Redis connected");
811
629
  }
812
630
  return;
813
631
  }
@@ -840,8 +658,9 @@ async function checkRequest(request_id, id_project) {
840
658
  * @param {string} token. User token
841
659
  */
842
660
  function sendMessageToBot(TILEBOT_ENDPOINT, message, botId, callback) {
661
+
843
662
  const url = `${TILEBOT_ENDPOINT}/ext/${botId}`;
844
- console.log("sendMessageToBot URL", url);
663
+ winston.verbose("sendMessageToBot URL" + url);
845
664
  const HTTPREQUEST = {
846
665
  url: url,
847
666
  headers: {
@@ -868,10 +687,9 @@ function sendMessageToBot(TILEBOT_ENDPOINT, message, botId, callback) {
868
687
  }
869
688
 
870
689
  function myrequest(options, callback, log) {
871
- if (log) {
872
- console.log("API URL:", options.url);
873
- console.log("** Options:", JSON.stringify(options));
874
- }
690
+ winston.verbose("(tybotRoute) myrequest API URL:" + options.url);
691
+ winston.debug("(tybotRoute) myrequest Options:", options);
692
+
875
693
  axios(
876
694
  {
877
695
  url: options.url,
@@ -881,11 +699,8 @@ function myrequest(options, callback, log) {
881
699
  headers: options.headers
882
700
  })
883
701
  .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
- }
702
+ winston.verbose("Response for url:" + options.url);
703
+ winston.debug("Response headers:\n", res.headers);
889
704
  if (res && res.status == 200 && res.data) {
890
705
  if (callback) {
891
706
  callback(null, res.data);
@@ -896,9 +711,8 @@ function myrequest(options, callback, log) {
896
711
  callback(TiledeskClient.getErr({ message: "Response status not 200" }, options, res), null, null);
897
712
  }
898
713
  }
899
- })
900
- .catch((error) => {
901
- console.error("(tybotRoute index) An error occurred:", JSON.stringify(error), "url:", options.url);
714
+ }).catch((error) => {
715
+ winston.error("(tybotRoute index) An error occurred: ", error);
902
716
  if (callback) {
903
717
  callback(error, null, null);
904
718
  }