@tiledesk/tiledesk-tybot-connector 0.2.601-rc1 → 0.3.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 (71) hide show
  1. package/CHANGELOG.md +378 -1
  2. package/ExtApi.js +6 -6
  3. package/TdCache copy.js +242 -0
  4. package/TdCache.js +81 -176
  5. package/TdCache_v3.js +261 -0
  6. package/TiledeskExpression.js +7 -3
  7. package/index.js +290 -43
  8. package/logs/app.log +279 -0
  9. package/models/IntentsMachineFactory.js +5 -2
  10. package/models/MockBotsDataSource.js +19 -11
  11. package/models/TiledeskChatbot.js +97 -79
  12. package/models/TiledeskChatbotConst.js +12 -17
  13. package/models/TiledeskChatbotUtil.js +353 -109
  14. package/models/TiledeskIntentsMachine.js +1 -1
  15. package/models/faqKbService.js +1 -1
  16. package/package.json +7 -6
  17. package/tiledeskChatbotPlugs/DirectivesChatbotPlug.js +172 -106
  18. package/tiledeskChatbotPlugs/Filler.js +13 -2
  19. package/tiledeskChatbotPlugs/TildeskContextForCodeOrchestrator.js +8 -0
  20. package/tiledeskChatbotPlugs/WebhookChatbotPlug.js +13 -7
  21. package/tiledeskChatbotPlugs/directives/DirAddTags.js +374 -0
  22. package/tiledeskChatbotPlugs/directives/DirAiPrompt.js +476 -0
  23. package/tiledeskChatbotPlugs/directives/DirAskGPT.js +16 -19
  24. package/tiledeskChatbotPlugs/directives/DirAskGPTV2.js +221 -34
  25. package/tiledeskChatbotPlugs/directives/DirAssign.js +0 -11
  26. package/tiledeskChatbotPlugs/directives/DirAssignFromFunction.js +11 -21
  27. package/tiledeskChatbotPlugs/directives/DirAssistant.js +728 -0
  28. package/tiledeskChatbotPlugs/directives/DirBrevo.js +353 -0
  29. package/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js +3 -30
  30. package/tiledeskChatbotPlugs/directives/DirClearTranscript.js +22 -0
  31. package/tiledeskChatbotPlugs/directives/DirClose.js +16 -3
  32. package/tiledeskChatbotPlugs/directives/DirCode.js +1 -1
  33. package/tiledeskChatbotPlugs/directives/DirCondition.js +0 -26
  34. package/tiledeskChatbotPlugs/directives/DirConnectBlock.js +183 -0
  35. package/tiledeskChatbotPlugs/directives/DirContactUpdate.js +121 -0
  36. package/tiledeskChatbotPlugs/directives/DirCustomerio.js +5 -8
  37. package/tiledeskChatbotPlugs/directives/DirDeflectToHelpCenter.js +11 -1
  38. package/tiledeskChatbotPlugs/directives/DirDepartment.js +15 -6
  39. package/tiledeskChatbotPlugs/directives/DirFireTiledeskEvent.js +17 -6
  40. package/tiledeskChatbotPlugs/directives/DirForm.js +12 -2
  41. package/tiledeskChatbotPlugs/directives/DirGptTask.js +83 -38
  42. package/tiledeskChatbotPlugs/directives/DirGptTask_OLD.js +4 -7
  43. package/tiledeskChatbotPlugs/directives/DirHubspot.js +5 -8
  44. package/tiledeskChatbotPlugs/directives/DirIfOnlineAgents.js +14 -27
  45. package/tiledeskChatbotPlugs/directives/DirIfOnlineAgentsV2.js +278 -0
  46. package/tiledeskChatbotPlugs/directives/DirIfOpenHours.js +147 -51
  47. package/tiledeskChatbotPlugs/directives/DirIfOpenHours_OLD.js +125 -0
  48. package/tiledeskChatbotPlugs/directives/DirIntent.js +8 -36
  49. package/tiledeskChatbotPlugs/directives/DirJSONCondition.js +5 -26
  50. package/tiledeskChatbotPlugs/directives/DirMessage.js +19 -17
  51. package/tiledeskChatbotPlugs/directives/DirMessageToBot.js +136 -0
  52. package/tiledeskChatbotPlugs/directives/DirMoveToAgent.js +20 -87
  53. package/tiledeskChatbotPlugs/directives/DirMoveToUnassigned.js +59 -0
  54. package/tiledeskChatbotPlugs/directives/DirQapla.js +6 -9
  55. package/tiledeskChatbotPlugs/directives/DirRandomReply.js +17 -7
  56. package/tiledeskChatbotPlugs/directives/DirRemoveCurrentBot.js +17 -7
  57. package/tiledeskChatbotPlugs/directives/DirReplaceBot.js +11 -2
  58. package/tiledeskChatbotPlugs/directives/DirReplaceBotV2.js +135 -21
  59. package/tiledeskChatbotPlugs/directives/DirReplaceBotV3.js +163 -0
  60. package/tiledeskChatbotPlugs/directives/DirReply.js +42 -9
  61. package/tiledeskChatbotPlugs/directives/DirReplyV2.js +347 -0
  62. package/tiledeskChatbotPlugs/directives/DirSendEmail.js +13 -23
  63. package/tiledeskChatbotPlugs/directives/DirSendWhatsapp.js +247 -0
  64. package/tiledeskChatbotPlugs/directives/DirSetAttributeV2.js +202 -15
  65. package/tiledeskChatbotPlugs/directives/DirSetConversationTags.js +13 -4
  66. package/tiledeskChatbotPlugs/directives/DirWait.js +21 -4
  67. package/tiledeskChatbotPlugs/directives/DirWebRequest.js +1 -2
  68. package/tiledeskChatbotPlugs/directives/DirWebRequestV2.js +166 -103
  69. package/tiledeskChatbotPlugs/directives/DirWhatsappByAttribute.js +2 -60
  70. package/tiledeskChatbotPlugs/directives/Directives.js +16 -1
  71. /package/tiledeskChatbotPlugs/directives/{DirOfflineHours.js → DEPRECATED_DirOfflineHours.js} +0 -0
package/index.js CHANGED
@@ -12,6 +12,8 @@ const { MongodbBotsDataSource } = require('./models/MongodbBotsDataSource.js');
12
12
  const { MockBotsDataSource } = require('./models/MockBotsDataSource.js');
13
13
  const { TiledeskChatbotConst } = require('./models/TiledeskChatbotConst');
14
14
  const { IntentsMachineFactory } = require('./models/IntentsMachineFactory');
15
+ const { v4: uuidv4 } = require('uuid');
16
+ let axios = require('axios');
15
17
  // let parser = require('accept-language-parser');
16
18
 
17
19
  router.use(bodyParser.json({limit: '50mb'}));
@@ -19,6 +21,8 @@ router.use(bodyParser.urlencoded({ extended: true , limit: '50mb'}));
19
21
 
20
22
  let log = false;
21
23
  let tdcache = null;
24
+ let MAX_STEPS = 1000;
25
+ let MAX_EXECUTION_TIME = 1000 * 3600 * 8;
22
26
 
23
27
  // DEV
24
28
  // const { MessagePipeline } = require('./tiledeskChatbotPlugs/MessagePipeline');
@@ -28,18 +32,23 @@ const { DirectivesChatbotPlug } = require('./tiledeskChatbotPlugs/DirectivesChat
28
32
  let mongoose = require('mongoose');
29
33
  // const { Directives } = require('./tiledeskChatbotPlugs/directives/Directives.js');
30
34
  const { TiledeskChatbotUtil } = require('./models/TiledeskChatbotUtil.js'); //require('@tiledesk/tiledesk-chatbot-util');
31
- let APIURL = null;
35
+ let API_ENDPOINT = null;
36
+ let TILEBOT_ENDPOINT = null;
32
37
  let staticBots;
33
38
 
34
39
  router.post('/ext/:botid', async (req, res) => {
40
+ const botId = req.params.botid;
41
+ if (log) {console.log("(tybotRoute) POST /ext/:botid called: ", botId);}
42
+ if(!botId || botId === "null" || botId === "undefined"){
43
+ return res.status(400).send({"success": false, error: "Required parameters botid not found. Value is 'null' or 'undefined'"})
44
+ }
45
+
35
46
  if (req && req.body && req.body.payload && req.body.payload.request && req.body.payload.request.snapshot) {
36
47
  delete req.body.payload.request.snapshot;
37
48
  console.log("Removed req.body.payload.request.snapshot field");
38
49
  }
39
50
  if (log) {console.log("REQUEST BODY:", JSON.stringify(req.body));}
40
-
41
- const botId = req.params.botid;
42
- if (log) {console.log(" :", botId);}
51
+
43
52
  const message = req.body.payload;
44
53
  const messageId = message._id;
45
54
  //const faq_kb = req.body.hook; now it is "bot"
@@ -68,9 +77,8 @@ router.post('/ext/:botid', async (req, res) => {
68
77
  res.status(200).send({"success":true});
69
78
  }
70
79
  else {
71
- res.status(400).send({"success": false, error: "Request id is invalid"});
72
- // console.log("request id, projectId:", requestId, projectId)
73
- // process.exit(0)
80
+ res.status(400).send({"success": false, error: "Request id is invalid:" + requestId + " for projectId:" + projectId + "chatbotId:" + botId});
81
+ return;
74
82
  }
75
83
 
76
84
  const request_botId_key = "tilebot:botId_requests:" + requestId;
@@ -107,19 +115,23 @@ router.post('/ext/:botid', async (req, res) => {
107
115
  }
108
116
 
109
117
  // get the bot metadata
110
- let bot = null;
111
- try {
112
- // bot = await botsDS.getBotById(botId);
113
- // bot = await botById(botId, projectId, tdcache, botsDS);
114
- bot = await botsDS.getBotByIdCache(botId, tdcache);
115
- // console.log("getBotByIdCache ---> bot: ", JSON.stringify(bot, null, 2))
116
- }
117
- catch(error) {
118
- console.error("Error getting botId:", botId);
119
- console.error("Error getting bot was:", error);
118
+ let bot = await botsDS.getBotByIdCache(botId, tdcache).catch((err)=> {
119
+ Promise.reject(err);
120
120
  return;
121
- }
122
- if (log) {console.log("bot found:", JSON.stringify(bot));}
121
+ });
122
+ // let bot = null;
123
+ // try {
124
+ // // bot = await botsDS.getBotById(botId);
125
+ // // bot = await botById(botId, projectId, tdcache, botsDS);
126
+ // bot = await botsDS.getBotByIdCache(botId, tdcache);
127
+ // // console.log("getBotByIdCache ---> bot: ", JSON.stringify(bot, null, 2))
128
+ // }
129
+ // catch(error) {
130
+ // console.error("Error getting botId:", botId);
131
+ // console.error("Error getting bot was:", error);
132
+ // return;
133
+ // }
134
+ // if (log) {console.log("bot found:", JSON.stringify(bot));}
123
135
 
124
136
  let intentsMachine;
125
137
  let backupMachine;
@@ -159,11 +171,13 @@ router.post('/ext/:botid', async (req, res) => {
159
171
  botId: botId,
160
172
  bot: bot,
161
173
  token: token,
162
- APIURL: APIURL,
174
+ APIURL: API_ENDPOINT,
163
175
  APIKEY: "___",
164
176
  tdcache: tdcache,
165
177
  requestId: requestId,
166
178
  projectId: projectId,
179
+ MAX_STEPS: MAX_STEPS,
180
+ MAX_EXECUTION_TIME: MAX_EXECUTION_TIME,
167
181
  log: log
168
182
  });
169
183
  if (log) {console.log("MESSAGE CONTAINS:", message.text);}
@@ -171,20 +185,22 @@ router.post('/ext/:botid', async (req, res) => {
171
185
  // if (log) {console.log("forced conversion of \\\\start /start");}
172
186
  // message.text = "/start";
173
187
  // }
174
- await TiledeskChatbotUtil.updateRequestAttributes(chatbot, message, projectId, requestId);
175
- await TiledeskChatbotUtil.updateConversationTranscript(chatbot, message);
188
+ await TiledeskChatbotUtil.updateRequestAttributes(chatbot, token, message, projectId, requestId);
189
+ if (requestId.startsWith("support-group-")) {
190
+ await TiledeskChatbotUtil.updateConversationTranscript(chatbot, message);
191
+ }
176
192
 
177
193
  let reply = null;
178
194
  try {
179
195
  reply = await chatbot.replyToMessage(message);
180
196
  }
181
197
  catch(err) {
182
- console.error("An error occurred replying to message:", JSON.stringify(message), "\nError:", err );
198
+ console.error("(tybotRoute) An error occurred replying to message:", JSON.stringify(message), "\nError:", err );
199
+ return;
183
200
  }
184
201
  if (!reply) {
185
- reply = {
186
- "text": "No messages found. Is 'defaultFallback' intent missing?"
187
- }
202
+ if (log) { console.log("(tybotRoute) No reply. Stop flow.") }
203
+ return;
188
204
  }
189
205
 
190
206
  // console.log("reply is:", reply);
@@ -203,11 +219,11 @@ router.post('/ext/:botid', async (req, res) => {
203
219
  directives: directives,
204
220
  chatbot: chatbot,
205
221
  supportRequest: message.request,
206
- TILEDESK_API_ENDPOINT: APIURL,
207
- TILEBOT_ENDPOINT:process.env.TYBOT_ENDPOINT,
222
+ API_ENDPOINT: API_ENDPOINT,
223
+ TILEBOT_ENDPOINT:TILEBOT_ENDPOINT,
208
224
  token: token,
209
225
  log: log,
210
- HELP_CENTER_API_ENDPOINT: process.env.HELP_CENTER_API_ENDPOINT,
226
+ // HELP_CENTER_API_ENDPOINT: process.env.HELP_CENTER_API_ENDPOINT,
211
227
  cache: tdcache
212
228
  }
213
229
  );
@@ -229,12 +245,9 @@ router.post('/ext/:botid', async (req, res) => {
229
245
  reply.attributes.splits = true;
230
246
  reply.attributes.markbot = true;
231
247
  reply.attributes.fillParams = true;
232
- let extEndpoint = `${APIURL}/modules/tilebot/`;
233
- if (process.env.TYBOT_ENDPOINT) {
234
- extEndpoint = `${process.env.TYBOT_ENDPOINT}`;
235
- }
248
+
236
249
  const apiext = new ExtApi({
237
- ENDPOINT: extEndpoint,
250
+ TILEBOT_ENDPOINT: TILEBOT_ENDPOINT,
238
251
  log: false
239
252
  });
240
253
  apiext.sendSupportMessageExt(reply, projectId, requestId, token, () => {
@@ -261,7 +274,7 @@ router.post('/ext/:projectId/requests/:requestId/messages', async (req, res) =>
261
274
  const tdclient = new TiledeskClient({
262
275
  projectId: projectId,
263
276
  token: token,
264
- APIURL: APIURL,
277
+ APIURL: API_ENDPOINT,
265
278
  APIKEY: "___",
266
279
  log: false
267
280
  });
@@ -306,10 +319,10 @@ router.post('/ext/:projectId/requests/:requestId/messages', async (req, res) =>
306
319
  }
307
320
  if (log) {
308
321
  console.log("/ext request....", JSON.stringify(request));
309
- console.log("/ext APIURL....", APIURL);
310
- console.log("/ext process.env.TYBOT_ENDPOINT....", process.env.TYBOT_ENDPOINT);
322
+ console.log("/ext API_ENDPOINT....", API_ENDPOINT);
323
+ console.log("/ext process.env.TILEBOT_ENDPOINT....", TILEBOT_ENDPOINT);
311
324
  }
312
- let directivesPlug = new DirectivesChatbotPlug({supportRequest: request, TILEDESK_API_ENDPOINT: APIURL, TILEBOT_ENDPOINT:process.env.TYBOT_ENDPOINT, token: token, log: log, HELP_CENTER_API_ENDPOINT: process.env.HELP_CENTER_API_ENDPOINT, cache: tdcache});
325
+ 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});
313
326
  // let directivesPlug = null;
314
327
  // PIPELINE-EXT
315
328
  // if (log) {console.log("answer to process:", JSON.stringify(answer));}
@@ -329,7 +342,7 @@ router.post('/ext/:projectId/requests/:requestId/messages', async (req, res) =>
329
342
  tdclient.sendSupportMessage(requestId, bot_answer, (err, response) => {
330
343
  if (log) {console.log("/ext => bot_answer sent:", JSON.stringify(bot_answer));}
331
344
  if (err) {
332
- console.error("/ext => Error sending message", err);
345
+ console.error("/ext => Error sending message", JSON.stringify(err));
333
346
  }
334
347
  directivesPlug.processDirectives( () => {
335
348
  if (log) {console.log("After message - Directives executed.");}
@@ -358,8 +371,103 @@ router.get('/message/context/:messageid', async (req, res) => {
358
371
  }
359
372
  });
360
373
 
374
+ router.get('/ext/reserved/parameters/requests/:requestid', async (req, res) => {
375
+ const requestId = req.params.requestid;
376
+ const parameters = await TiledeskChatbot.allParametersStatic(tdcache, requestId);
377
+ if (parameters === null) {
378
+ res.send([]);
379
+ return;
380
+ }
381
+ if (req.query.all != null) {
382
+ res.send(parameters);
383
+ }
384
+ else {
385
+ // const RESERVED = [
386
+ // TiledeskChatbotConst.REQ_CHATBOT_NAME_KEY,
387
+ // TiledeskChatbotConst.REQ_CHAT_URL,
388
+ // TiledeskChatbotConst.REQ_CITY_KEY,
389
+ // TiledeskChatbotConst.REQ_COUNTRY_KEY,
390
+ // TiledeskChatbotConst.REQ_DEPARTMENT_ID_KEY,
391
+ // TiledeskChatbotConst.REQ_DEPARTMENT_NAME_KEY,
392
+ // TiledeskChatbotConst.REQ_END_USER_ID_KEY,
393
+ // TiledeskChatbotConst.REQ_END_USER_IP_ADDRESS_KEY,
394
+ // TiledeskChatbotConst.REQ_LAST_MESSAGE_ID_KEY,
395
+ // TiledeskChatbotConst.REQ_LAST_USER_TEXT_KEY,
396
+ // TiledeskChatbotConst.REQ_PROJECT_ID_KEY,
397
+ // TiledeskChatbotConst.REQ_REQUEST_ID_KEY,
398
+ // TiledeskChatbotConst.REQ_USER_AGENT_KEY,
399
+ // TiledeskChatbotConst.REQ_USER_LANGUAGE_KEY,
400
+ // TiledeskChatbotConst.REQ_USER_SOURCE_PAGE_KEY,
401
+ // TiledeskChatbotConst.REQ_LAST_USER_MESSAGE_TYPE_KEY,
402
+ // TiledeskChatbotConst.REQ_TRANSCRIPT_KEY,
403
+ // TiledeskChatbotConst.REQ_LAST_USER_MESSAGE_KEY,
404
+ // TiledeskChatbot.REQ_DECODED_JWT_KEY,
405
+ // "lastUserImageURL", // image
406
+ // "lastUserImageName", // image
407
+ // "lastUserImageWidth", // image
408
+ // "lastUserImageHeight", // image
409
+ // "lastUserImageType", // image
410
+ // "lastUserDocumentURL", // file
411
+ // "lastUserDocumentName", // file
412
+ // "lastUserDocumentType", // file
413
+ // "ticketId",
414
+ // TiledeskChatbotConst.REQ_CHAT_CHANNEL,
415
+ // "user_lead_id",
416
+ // "lastUserText",
417
+ // TiledeskChatbotConst.REQ_REQUESTER_IS_AUTHENTICATED_KEY,
418
+ // "userInput"
419
+ // ]
420
+ // let userParams = {};
421
+ // if (parameters) {
422
+ // for (const [key, value] of Object.entries(parameters)) {
423
+ // // console.log(key, value);
424
+ // // There is a bug that moves the requestId as a key in request attributes, so: && !key.startsWith("support-group-")
425
+ // if (!key.startsWith("_") && !RESERVED.some(e => e === key) && !key.startsWith("support-group-")) {
426
+ // userParams[key] = value;
427
+ // }
428
+ // }
429
+ // }
430
+ const userParams = TiledeskChatbotUtil.userFlowAttributes(parameters);
431
+ res.send(userParams);
432
+ }
433
+ });
434
+
361
435
  router.get('/ext/parameters/requests/:requestid', async (req, res) => {
436
+ // console.log("Checking authorization...");
437
+ // const authorization = req.headers["authorization"];
438
+ // if (!authorization) {
439
+ // console.log("No authorization header...");
440
+ // res.status(401).send("Unauthorized");
441
+ // return;
442
+ // }
443
+ // const token = req.headers["authorization"];
444
+ // const publicKey = process.env.GLOBAL_SECRET_OR_PUB_KEY;
445
+ // console.log("Got public key:", publicKey);
446
+ // const _decoded = null;
447
+ // jwt.verify(token, publicKey, function (err, decoded) {
448
+ // _decoded = decoded;
449
+ // });
450
+ // console.log("Authorization header field checking", req.headers["authorization"]);
451
+
452
+
362
453
  const requestId = req.params.requestid;
454
+ if (!requestId) {
455
+ res.status(404).send("Not found");
456
+ return;
457
+ }
458
+ const request_parts = requestId.split("-");
459
+ if (request_parts && request_parts.length >= 4) {
460
+ const project_id = request_parts[2];
461
+ // console.log("ProjectId:", project_id);
462
+ if (project_id !== "656054000410fa00132e5dcc") { //&& project_id !== "ANOTHER P_ID"
463
+ res.status(401).send("Unauthorized");
464
+ return;
465
+ }
466
+ }
467
+ else if (!request_parts || ( request_parts && request_parts.length < 4) ) {
468
+ res.status(500).send("Invalid request ID");
469
+ return;
470
+ }
363
471
  const parameters = await TiledeskChatbot.allParametersStatic(tdcache, requestId);
364
472
  if (parameters === null) {
365
473
  res.send([]);
@@ -371,6 +479,7 @@ router.get('/ext/parameters/requests/:requestid', async (req, res) => {
371
479
  else {
372
480
  const RESERVED = [
373
481
  TiledeskChatbotConst.REQ_CHATBOT_NAME_KEY,
482
+ TiledeskChatbotConst.REQ_CHATBOT_ID_KEY,
374
483
  TiledeskChatbotConst.REQ_CHAT_URL,
375
484
  TiledeskChatbotConst.REQ_CITY_KEY,
376
485
  TiledeskChatbotConst.REQ_COUNTRY_KEY,
@@ -443,7 +552,7 @@ router.post('/echobot', (req, res) => {
443
552
  const tdclient = new TiledeskClient({
444
553
  projectId: projectId,
445
554
  token: token,
446
- APIURL: APIURL,
555
+ APIURL: API_ENDPOINT,
447
556
  APIKEY: "___",
448
557
  log: false
449
558
  });
@@ -464,9 +573,49 @@ router.post('/echobot', (req, res) => {
464
573
  });
465
574
  });
466
575
 
576
+ // draft webhook
577
+ router.post('/block/:project_id/:bot_id/:block_id', async (req, res) => {
578
+ const project_id = req.params['project_id'];
579
+ const bot_id = req.params['bot_id'];
580
+ const block_id = req.params['block_id'];
581
+ const body = req.body;
582
+ if (this.log) {
583
+ console.log("/block/ .heders:", JSON.stringify(req.headers));
584
+ console.log("/block/ .body:", JSON.stringify(body));
585
+ }
586
+
587
+ // console.log('/block/:project_id/:bot_id/:block_id:', project_id, "/", bot_id, "/", block_id);
588
+ // console.log('/block/:project_id/:bot_id/:block_id.body', body);
589
+
590
+ // invoke block
591
+ // unique ID for each execution
592
+ const execution_id = uuidv4().replace(/-/g, '');
593
+ const request_id = "automation-request-" + project_id + "-" + execution_id;
594
+ const command = "/" + block_id;
595
+ let request = {
596
+ "payload": {
597
+ "recipient": request_id,
598
+ "text": command,
599
+ "id_project": project_id,
600
+ "request": {
601
+ "request_id": request_id
602
+ },
603
+ "attributes": {
604
+ "payload": body
605
+ }
606
+ },
607
+ "token": "NO-TOKEN"
608
+ }
609
+ if (this.log) {console.log("sendMessageToBot()...", JSON.stringify(request));}
610
+ sendMessageToBot(TILEBOT_ENDPOINT, request, bot_id, async () => {
611
+ res.status(200).send({"success":true});
612
+ return;
613
+ });
614
+ });
615
+
467
616
  async function startApp(settings, completionCallback) {
468
617
  console.log("Starting Tilebot...");
469
- //console.log("Starting Tilebot with Settings:", settings);
618
+ // console.log("Starting Tilebot with Settings:", settings);
470
619
  if (settings.bots) { // static bots data source
471
620
  staticBots = settings.bots;
472
621
  }
@@ -480,10 +629,19 @@ async function startApp(settings, completionCallback) {
480
629
  throw new Error("settings.API_ENDPOINT is mandatory id no settings.bots.");
481
630
  }
482
631
  else {
483
- APIURL = settings.API_ENDPOINT;
484
- console.log("(Tilebot) settings.API_ENDPOINT:", APIURL);
632
+ API_ENDPOINT = settings.API_ENDPOINT;
633
+ console.log("(Tilebot) settings.API_ENDPOINT:", API_ENDPOINT);
485
634
  }
486
635
 
636
+ if (!settings.TILEBOT_ENDPOINT) {
637
+ TILEBOT_ENDPOINT = `${API_ENDPOINT}/modules/tilebot`
638
+ }
639
+ else {
640
+ TILEBOT_ENDPOINT = settings.TILEBOT_ENDPOINT
641
+ }
642
+ console.log("(Tilebot) settings.TILEBOT_ENDPOINT:", TILEBOT_ENDPOINT);
643
+
644
+
487
645
  if (settings.REDIS_HOST && settings.REDIS_PORT) {
488
646
  tdcache = new TdCache({
489
647
  host: settings.REDIS_HOST,
@@ -499,6 +657,19 @@ async function startApp(settings, completionCallback) {
499
657
  log = true;
500
658
  }
501
659
  console.log("(Tilebot) log:", log);
660
+
661
+
662
+ if (process.env.CHATBOT_MAX_STEPS) {
663
+ MAX_STEPS = Number(process.env.CHATBOT_MAX_STEPS);
664
+ }
665
+
666
+ if (process.env.CHATBOT_MAX_EXECUTION_TIME) {
667
+ MAX_EXECUTION_TIME = Number(process.env.CHATBOT_MAX_EXECUTION_TIME);// test // prod1000 * 3600 * 4; // 4 hours
668
+ }
669
+
670
+ console.log("(Tilebot) MAX_STEPS: ", MAX_STEPS)
671
+ console.log("(Tilebot) MAX_EXECUTION_TIME: ", MAX_EXECUTION_TIME)
672
+
502
673
  var pjson = require('./package.json');
503
674
  console.log("(Tilebot) Starting Tilebot connector v" + pjson.version);
504
675
 
@@ -580,4 +751,80 @@ async function checkRequest(request_id, id_project) {
580
751
  // WARNING! Move this function in models/TiledeskChatbotUtil.js
581
752
  }
582
753
 
754
+ /**
755
+ * A stub to send message to the "ext/botId" endpoint, hosted by tilebot on:
756
+ * /${TILEBOT_ROUTE}/ext/${botId}
757
+ *
758
+ * @param {Object} message. The message to send
759
+ * @param {string} botId. Tiledesk botId
760
+ * @param {string} token. User token
761
+ */
762
+ function sendMessageToBot(TILEBOT_ENDPOINT, message, botId, callback) {
763
+ // const jwt_token = this.fixToken(token);
764
+ const url = `${TILEBOT_ENDPOINT}/ext/${botId}`;
765
+ console.log("sendMessageToBot URL", url);
766
+ const HTTPREQUEST = {
767
+ url: url,
768
+ headers: {
769
+ 'Content-Type': 'application/json'
770
+ },
771
+ json: message,
772
+ method: 'POST'
773
+ };
774
+ myrequest(
775
+ HTTPREQUEST,
776
+ function (err, resbody) {
777
+ if (err) {
778
+ if (callback) {
779
+ callback(err);
780
+ }
781
+ }
782
+ else {
783
+ if (callback) {
784
+ callback(null, resbody);
785
+ }
786
+ }
787
+ }, false
788
+ );
789
+ }
790
+
791
+ function myrequest(options, callback, log) {
792
+ if (log) {
793
+ console.log("API URL:", options.url);
794
+ console.log("** Options:", JSON.stringify(options));
795
+ }
796
+ axios(
797
+ {
798
+ url: options.url,
799
+ method: options.method,
800
+ data: options.json,
801
+ params: options.params,
802
+ headers: options.headers
803
+ })
804
+ .then((res) => {
805
+ if (log) {
806
+ console.log("Response for url:", options.url);
807
+ console.log("Response headers:\n", JSON.stringify(res.headers));
808
+ //console.log("******** Response for url:", res);
809
+ }
810
+ if (res && res.status == 200 && res.data) {
811
+ if (callback) {
812
+ callback(null, res.data);
813
+ }
814
+ }
815
+ else {
816
+ if (callback) {
817
+ callback(TiledeskClient.getErr({ message: "Response status not 200" }, options, res), null, null);
818
+ }
819
+ }
820
+ })
821
+ .catch((error) => {
822
+ console.error("(tybotRoute index) An error occurred:", JSON.stringify(error), "url:", options.url);
823
+ if (callback) {
824
+ callback(error, null, null);
825
+ }
826
+ }
827
+ );
828
+ }
829
+
583
830
  module.exports = { router: router, startApp: startApp};