@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
@@ -1,14 +1,14 @@
1
1
  // let Faq = require('./faq');
2
2
  // let Faq_kb = require('./faq_kb');
3
- // const { ExtApi } = require('../ExtApi.js');
4
- const { MessagePipeline } = require('../tiledeskChatbotPlugs/MessagePipeline');
5
3
  // const { DirectivesChatbotPlug } = require('../tiledeskChatbotPlugs/DirectivesChatbotPlug');
4
+ const { MessagePipeline } = require('../tiledeskChatbotPlugs/MessagePipeline');
6
5
  const { WebhookChatbotPlug } = require('../tiledeskChatbotPlugs/WebhookChatbotPlug');
7
6
  const { TiledeskClient } = require('@tiledesk/tiledesk-client');
8
7
  const { IntentForm } = require('./IntentForm.js');
9
- const { TiledeskChatbotUtil } = require('./TiledeskChatbotUtil.js');
8
+ const { TiledeskChatbotUtil } = require('../utils/TiledeskChatbotUtil.js');
10
9
  const { DirLockIntent } = require('../tiledeskChatbotPlugs/directives/DirLockIntent');
11
10
  const { DirUnlockIntent } = require('../tiledeskChatbotPlugs/directives/DirUnlockIntent');
11
+ const winston = require('../utils/winston');
12
12
 
13
13
  class TiledeskChatbot {
14
14
 
@@ -49,86 +49,45 @@ class TiledeskChatbot {
49
49
  let lead = null;
50
50
  if (message.request) {
51
51
  this.request = message.request;
52
- // lead = message.request.lead;
53
- // if (lead && lead.fullname) {
54
- // if (this.log) {console.log("lead.fullname => params.userFullname:", lead.fullname)}
55
- // await this.addParameter("userFullname", lead.fullname);
56
- // }
57
- // if (lead && lead.email) {
58
- // if (this.log) {console.log("lead.email => params.userEmail:", lead.email)}
59
- // await this.addParameter("userEmail", lead.email);
60
- // }
61
52
  }
62
- // if (this.log) {
63
- // console.log("replyToMessage() > lead found:", JSON.stringify(lead));
64
- // }
65
53
 
66
54
  // reset lockedIntent on direct user invocation ( /intent or action => this only?)
67
55
  if (message.sender != "_tdinternal") {
68
56
  try {
69
- // if (this.log) {console.log("Checking locked intent reset on explicit intent invokation.");}
70
- // if (message.text.startsWith("/")) {
71
- // if (this.log) {console.log("RESETTING LOCKED INTENT. Intent was explicitly invoked with / command...", message.text);}
72
- // await this.unlockIntent(this.requestId);
73
- // await this.unlockAction(this.requestId);
74
- // if (this.log) {console.log("RESET LOCKED INTENT. Intent was explicitly invoked with / command:", message.text);}
75
- // }
76
- if (this.log) {console.log("Checking locked intent reset on action invocation.");}
57
+ winston.verbose("(TiledeskChatbot) Checking locked intent reset on action invocation")
77
58
  if (message.attributes && message.attributes.action) {
78
- if (this.log) {console.log("Message has action:", message.attributes.action)}
79
- if (this.log) {console.log("RESETTING LOCKED INTENT. Intent was explicitly invoked with an action:", message.attributes.action);}
59
+ winston.debug("(TiledeskChatbot) Message has action: " + message.attributes.action)
80
60
  await this.unlockIntent(this.requestId);
81
61
  await this.unlockAction(this.requestId);
82
- // console.log("RESET LOCKED INTENT.");
83
- if (this.log) {console.log("RESET LOCKED INTENT. Intent was explicitly invoked with an action:", message.attributes.action);}
62
+ winston.debug("(TiledeskChatbot) Reset locked intent. Intent was explicitly invoked with an action: " + message.attributes.action)
84
63
  }
85
64
  } catch(error) {
86
- console.error("Error resetting locked intent:", error);
65
+ winston.error("(TiledeskChatbot) Error resetting locked intent: ", error)
87
66
  }
88
67
  }
89
68
 
90
- // resetting any noInput timeout setting userInput = true
91
- // if (message.sender != "_tdinternal") {
92
- // if (this.log) {console.log("resetting any noInput timeout setting userInput = (false?)", await this.getParameter(TiledeskChatbotConst.USER_INPUT) );}
93
- // try {
94
- // // await this.addParameter(TiledeskChatbotConst.USER_INPUT, true); // set userInput
95
- // await this.deleteParameter(TiledeskChatbotConst.USER_INPUT); // reset userInput
96
- // if (this.log) {console.log("userInput?", await this.getParameter(TiledeskChatbotConst.USER_INPUT) );}
97
- // } catch(error) {
98
- // console.error("Error resetting userInput:", error);
99
- // }
100
- // }
101
-
102
69
  // any external invocation restarts the steps counter
103
70
  try {
104
71
  if (message.sender != "_tdinternal") {
105
- if (this.log) {
106
- console.log("Resetting current step by request message:", message.text);
107
- }
72
+ winston.verbose("(TiledeskChatbot) Resetting current step by request message: " + message.text);
108
73
  await TiledeskChatbot.resetStep(this.tdcache, this.requestId);
109
74
  await TiledeskChatbot.resetStarted(this.tdcache, this.requestId);
110
75
  if (this.log) {
111
76
  if (this.tdcache) {
112
77
  let currentStep =
113
78
  await TiledeskChatbot.currentStep(this.tdcache, this.requestId);
114
- if (this.log) {console.log("after reset currentStep:", currentStep)}
79
+ winston.verbose("(TiledeskChatbot) After reset currentStep:" + currentStep);
115
80
  }
116
81
  }
117
82
  }
118
83
  } catch(error) {
119
- console.error("Error resetting locked intent:", error);
84
+ winston.error("(TiledeskChatbot) Error resetting locked intent: ", error);
120
85
  }
121
- // Emergency stop :)
122
- // if (message.text === "/anomaly") {
123
- // console.log(".................stop on /anomaly!");
124
- // resolve(null);
125
- // }
126
86
 
127
87
  // Checking locked intent (for non-internal intents)
128
88
  // internal intents always "skip" the locked intent
129
- // if (message.text.startsWith("/") && message.sender != "_tdinternal") {
130
89
  const locked_intent = await this.currentLockedIntent(this.requestId);
131
- if (this.log) {console.log("got locked intent: -" + locked_intent + "-")}
90
+ winston.verbose("(TiledeskChatbot) Got locked intent: -" + locked_intent + "-");
132
91
  if (locked_intent) {
133
92
  // const tdclient = new TiledeskClient({
134
93
  // projectId: this.projectId,
@@ -140,12 +99,10 @@ class TiledeskChatbot {
140
99
  // it only gets the locked_intent
141
100
  // const faq = await this.botsDataSource.getByIntentDisplayName(this.botId, locked_intent);
142
101
  const faq = await this.botsDataSource.getByIntentDisplayNameCache(this.botId, locked_intent, this.tdcache);
143
- if (this.log) {console.log("locked intent. got faqs", JSON.stringify(faq))}
102
+ winston.debug("(TiledeskChatbot) Locked intent. Got faqs: ", faq);
144
103
  let reply;
145
104
  if (faq) {
146
105
  reply = await this.execIntent(faq, message, lead);//, bot);
147
- // resolve(reply);
148
- // return;
149
106
  }
150
107
  else {
151
108
  reply = {
@@ -163,75 +120,45 @@ class TiledeskChatbot {
163
120
  resolve(reply);
164
121
  return;
165
122
  }
166
- // }
167
- // else if (message.text.startsWith("/")) {
168
- // if (this.log) {
169
- // console.log("Internal intent". message.text, "skips locked intent check");
170
- // }
171
- // }
123
+
172
124
 
173
125
  let explicit_intent_name = null;
174
126
  // Explicit intent invocation
175
127
  if (message.text && message.text.startsWith("/")) {
176
- if (this.log) {console.log("Intent was explicitly invoked:", message.text);}
128
+ winston.verbose("(TiledeskChatbot) Intent was explicitly invoked: " + message.text);
177
129
  let intent_name = message.text.substring(message.text.indexOf("/") + 1);
178
- if (this.log) {console.log("Invoked Intent:", intent_name);}
130
+ winston.verbose("(TiledeskChatbot) Invoked Intent: " + intent_name)
179
131
  explicit_intent_name = intent_name;
180
- // if (!message.attributes) {
181
- // message.attributes = {}
182
- // }
183
- // message.attributes.action = intent_name;
184
- // if (this.log) {console.log("Message action:", message.attributes.action)}
185
132
  }
186
133
 
187
134
  // Intent invocation with action
188
135
  if (message.attributes && message.attributes.action) {
189
- if (this.log) {console.log("Message has action:", message.attributes.action)}
136
+ winston.debug("(TiledeskChatbot) Message has action: ", message.attributes.action)
190
137
  explicit_intent_name = message.attributes.action;
191
- /*let action_parameters_index = action.indexOf("?");
192
- if (action_parameters_index > -1) {
193
- intent_name = intent_name.substring(0, action_parameters_index);
194
- }*/
195
- if (this.log) {console.log("Intent was explicitly invoked with an action:", explicit_intent_name);}
138
+ winston.verbose("(TiledeskChatbot) Intent was explicitly invoked with an action:", explicit_intent_name)
196
139
  }
197
140
 
198
141
  if (explicit_intent_name) {
199
- if (this.log) {console.log("Processing explicit intent:", explicit_intent_name)}
142
+ winston.verbose("(TiledeskChatbot) Processing explicit intent:", explicit_intent_name)
200
143
  // look for parameters
201
144
  const intent = TiledeskChatbotUtil.parseIntent(explicit_intent_name);
202
- if (this.log) {console.log("parsed intent:", intent);}
145
+ winston.debug("(TiledeskChatbot) parsed intent:", intent);
203
146
  let reply;
204
147
  if (!intent || (intent && !intent.name)) {
205
- if (this.log) {console.log("Invalid intent:", explicit_intent_name);}
148
+ winston.verbose("(TiledeskChatbot) Invalid intent:", explicit_intent_name)
149
+ reply = { "text": "Invalid intent: *" + explicit_intent_name + "*" }
206
150
  resolve();
207
151
  }
208
152
  else {
209
- if (this.log) {console.log("processing intent:", explicit_intent_name);}
210
- // let faq = await this.botsDataSource.getByIntentDisplayName(this.botId, intent.name);
211
- if (this.log) {
212
- console.log("intent this.botId:", this.botId);
213
- console.log("intent intent.name:", intent.name);
214
- if (this.tdcache) {
215
- console.log("intent this.tdcache ok");
216
- }
217
- else {
218
- console.log("no intent this.tdcache");
219
- }
220
- }
153
+ winston.verbose("(TiledeskChatbot) Processing intent:", explicit_intent_name)
221
154
  let faq = await this.botsDataSource.getByIntentDisplayNameCache(this.botId, intent.name, this.tdcache);
222
155
  if (faq) {
223
- if (this.log) {
224
- console.log("Got a reply (faq) by Intent name:", JSON.stringify(faq));}
156
+ winston.verbose("(TiledeskChatbot) Got a reply (faq) by Intent name:", faq)
225
157
  try {
226
158
  if (intent.parameters) {
227
- if (this.log) {
228
- for (const [key, value] of Object.entries(intent.parameters)) {
229
- console.log(`* Attribute from intent: '${key}' => ${value}`);
230
- }
231
- }
232
159
  for (const [key, value] of Object.entries(intent.parameters)) {
233
- if (this.log) {console.log(`Adding attribute from intent invocation /intentName{} => ${key}: ${value}`);}
234
- this.addParameter(key, value);
160
+ winston.verbose("(TiledeskChatbot) Adding attribute from intent invocation /intentName{}: " + key + " " + value);
161
+ this.addParameter(key, value);
235
162
  }
236
163
  }
237
164
  reply = await this.execIntent(faq, message, lead);
@@ -239,12 +166,13 @@ class TiledeskChatbot {
239
166
  return;
240
167
  }
241
168
  catch(error) {
242
- console.error("error");
169
+ winston.error("(TiledeskChatbot) Error adding parameter: ", error);
243
170
  reject(error);
244
171
  }
245
172
  }
246
173
  else {
247
- if (this.log) {console.log("Intent not found:", explicit_intent_name);}
174
+ winston.verbose("(TiledeskChatbot) Intent not found: " + explicit_intent_name);
175
+ reply = { "text": "Intent not found: " + explicit_intent_name }
248
176
  resolve()
249
177
  }
250
178
  }
@@ -254,26 +182,20 @@ class TiledeskChatbot {
254
182
  let faqs;
255
183
  try {
256
184
  faqs = await this.botsDataSource.getByExactMatch(this.botId, message.text);
257
- if (this.log) {console.log("got faq by EXACT MATCH", faqs);}
185
+ winston.verbose("(TiledeskChatbot) Got faq by exact match: " + faqs);
258
186
  }
259
187
  catch (error) {
260
- console.error("(TiledeskChatbot) An error occurred during exact match:", JSON.stringify(error));
188
+ winston.error("(TiledeskChatbot) An error occurred during exact match: ", error);
261
189
  }
262
190
  if (faqs && faqs.length > 0 && faqs[0].answer) {
263
- if (this.log) {console.log("EXACT MATCH OR ACTION FAQ:", faqs[0]);}
191
+ winston.debug("(TiledeskChatbot) exact match or action faq: ", faqs[0]);
264
192
  let reply;
265
193
  const faq = faqs[0];
266
194
  try {
267
195
  reply = await this.execIntent(faq, message, lead);//, bot);
268
- // if (!reply.attributes) {
269
- // reply.attributes = {}
270
- // }
271
- // // used by the Clients to get some info about the intent that generated this reply
272
- // reply.attributes.intent_display_name = faq.intent_display_name;
273
- // reply.attributes.intent_id = faq.intent_id;
274
196
  }
275
197
  catch(error) {
276
- console.error("error during exact match execIntent():", error);
198
+ winston.error("(TiledeskChatbot) An error occured during exact match execIntent(): ", error);
277
199
  reject(error);
278
200
  return;
279
201
  }
@@ -281,38 +203,30 @@ class TiledeskChatbot {
281
203
  return;
282
204
  }
283
205
  else { // NLP
284
- if (this.log) {console.log("Chatbot NLP decoding intent...");}
206
+ winston.verbose("(TiledeskChatbot) Chatbot NLP decoding intent...");
285
207
  let intents;
286
208
  try {
287
209
  intents = await this.intentsFinder.decode(this.botId, message.text);
288
- if (this.log) {console.log("Tiledesk AI intents found:", intents);}
210
+ winston.verbose("(TiledeskChatbot) Tiledesk AI intents found:", intents);
289
211
  }
290
212
  catch(error) {
291
- console.error("An error occurred on IntentsFinder.decode() (/model/parse error):", error.message);
213
+ winston.error("(TiledeskChatbot) An error occurred on IntentsFinder.decode() (/model/parse error):" + error.message);
292
214
  // recover on fulltext
293
215
  if (this.backupIntentsFinder) {
294
- if (this.log) {console.log("using backup Finder:", this.backupIntentsFinder);}
216
+ winston.debug("(TiledeskChatbot) Using backup Finder:", this.backupIntentsFinder);
295
217
  intents = await this.backupIntentsFinder.decode(this.botId, message.text);
296
- if (this.log) {console.log("Got intents from backup finder:", intents);}
218
+ winston.debug("(TiledeskChatbot) Got intents from backup finder: ", intents);
297
219
  }
298
220
  }
299
- if (this.log) {console.log("NLP intents found:", intents);}
221
+ winston.debug("(TiledeskChatbot) NLP intents found: ", intents);
300
222
  if (intents && intents.length > 0) {
301
- // console.log("Matching intents found.");
302
- // let faq = await this.botsDataSource.getByIntentDisplayName(this.botId, intents[0].intent_display_name);
303
223
  let faq = await this.botsDataSource.getByIntentDisplayNameCache(this.botId, intents[0].intent_display_name, this.tdcache);
304
224
  let reply;
305
225
  try {
306
226
  reply = await this.execIntent(faq, message, lead);//, bot);
307
- // if (!reply.attributes) {
308
- // reply.attributes = {}
309
- // }
310
- // // used by the Clients to get some info about the intent that generated this reply
311
- // reply.attributes.intent_display_name = faq.intent_display_name;
312
- // reply.attributes.intent_id = faq.intent_id;
313
227
  }
314
228
  catch(error) {
315
- console.error("error during NLP decoding:", error);
229
+ winston.error("(TiledeskChatbot) An error occurred during NLP decoding: ", error);
316
230
  reject(error);
317
231
  return;
318
232
  }
@@ -320,11 +234,8 @@ class TiledeskChatbot {
320
234
  return;
321
235
  }
322
236
  else {
323
- // fallback
324
- // let fallbackIntent = await this.botsDataSource.getByIntentDisplayName(this.botId, "defaultFallback");
325
237
  let fallbackIntent = await this.botsDataSource.getByIntentDisplayNameCache(this.botId, "defaultFallback", this.tdcache);
326
238
  if (!fallbackIntent) {
327
- // console.log("No defaultFallback found!");
328
239
  resolve(null);
329
240
  return;
330
241
  }
@@ -332,15 +243,9 @@ class TiledeskChatbot {
332
243
  let reply;
333
244
  try {
334
245
  reply = await this.execIntent(fallbackIntent, message, lead);//, bot);
335
- // if (!reply.attributes) {
336
- // reply.attributes = {}
337
- // }
338
- // // used by the Clients to get some info about the intent that generated this reply
339
- // reply.attributes.intent_display_name = fallbackIntent.intent_display_name;
340
- // reply.attributes.intent_id = fallbackIntent.intent_id;
341
246
  }
342
247
  catch(error) {
343
- console.error("error during defaultFallback:", error);
248
+ winston.error("(TiledeskChatbot) An error occurred during defaultFallback: ", error);
344
249
  reject(error);
345
250
  return;
346
251
  }
@@ -355,71 +260,28 @@ class TiledeskChatbot {
355
260
  async execIntent(faq, message, lead) {//, bot) {
356
261
  let answerObj = faq; // faqs[0];
357
262
  const botId = this.botId;
358
- // let sender = 'bot_' + botId;
359
- //var answerObj;
360
- //answerObj.score = 100; // exact search has max score
361
- if (this.log) {
362
- console.log("requestId:", this.requestId)
363
- console.log("token:", this.token)
364
- console.log("projectId:", this.projectId)
365
- }
263
+
264
+ winston.debug("(TiledeskChatbot) execIntent requestId: " + this.requestId)
265
+ winston.debug("(TiledeskChatbot) execIntent token: " + this.token)
266
+ winston.debug("(TiledeskChatbot) execIntent projectId: " + this.projectId)
267
+
366
268
  if (this.tdcache) {
367
269
  const requestKey = "tilebot:" + this.requestId
368
270
  await this.tdcache.setJSON(requestKey, this.request);
369
271
  }
370
- // /ext/:projectId/requests/:requestId/messages ENDPOINT COINCIDES
371
- // with API_ENDPOINT (APIRURL) ONLY WHEN THE TYBOT ROUTE IS HOSTED
372
- // ON THE MAIN SERVER. OTHERWISE WE USE TYBOT_ROUTE TO SPECIFY
373
- // THE ALTERNATIVE ROUTE.
374
- // let extEndpoint = `${this.APIURL}/modules/tilebot/`;
375
- // if (process.env.TILEBOT_ENDPOINT) {
376
- // extEndpoint = `${process.env.TILEBOT_ENDPOINT}`;
377
- // }
378
- // const apiext = new ExtApi({
379
- // ENDPOINT: extEndpoint,
380
- // log: this.log
381
- // });
382
- // console.log("the form...")
383
272
 
384
273
  let intent_name = answerObj.intent_display_name
385
- // THE FORM
386
- // if (intent_name === "test_form_intent") {
387
- // answerObj.form = {
388
- // "cancelCommands": ['reset', 'cancel'],
389
- // "cancelReply": "Ok canceled!",
390
- // "fields": [
391
- // {
392
- // "name": "userFullname",
393
- // "type": "text",
394
- // "label": "What is your name?\n* Andrea\n* Marco\n* Mirco\n* Luca Leo"
395
- // },{
396
- // "name": "companyName",
397
- // "type": "text",
398
- // "label": "Thank you ${userFullname}! What is your Company name?\n* Tiledesk\n* Frontiere21"
399
- // },
400
- // {
401
- // "name": "userEmail",
402
- // "type": "text",
403
- // "regex": "/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/",
404
- // "label": "Hi ${userFullname} from ${companyName}\n\nJust one last question\n\nYour email 🙂\n* andrea@libero.it\n* andrea@tiledesk.com",
405
- // "errorLabel": "${userFullname} this email address is invalid\n\nCan you insert a correct email address?"
406
- // }
407
- // ]
408
- // };
409
- // }
410
274
  let intent_form = answerObj.form;
411
- if (this.log) {
412
- console.log("IntentForm.isValidForm(intent_form)", IntentForm.isValidForm(intent_form));
413
- }
275
+
276
+ winston.debug("(TiledeskChatbot) IntentForm.isValidForm(intent_form)" + IntentForm.isValidForm(intent_form));
277
+
414
278
  let clientUpdateUserFullname = null;
415
279
  if (IntentForm.isValidForm(intent_form)) {
416
280
  await this.lockIntent(this.requestId, intent_name);
417
281
  const user_reply = message.text;
418
282
  let form_reply = await this.execIntentForm(user_reply, intent_form);
419
- // console.log("got form reply", form_reply)
420
283
  if (!form_reply.canceled && form_reply.message) {
421
- // console.log("Form replying for next field...");
422
- if (this.log) {console.log("Sending form reply...", form_reply.message)}
284
+ winston.debug("(TiledeskChatbot) Sending form reply...", form_reply.message)
423
285
  // reply with this message (ex. please enter your fullname)
424
286
  if (!form_reply.message.attributes) {
425
287
  form_reply.message.attributes = {}
@@ -430,29 +292,28 @@ class TiledeskChatbot {
430
292
  return form_reply.message;
431
293
  }
432
294
  else if (form_reply.end) {
433
- if (this.log) {
434
- console.log("FORM end.", );
435
- console.log("unlocking intent for request:", this.requestId);
436
- console.log("populate data on lead:", JSON.stringify(lead));
437
- }
295
+
296
+ winston.debug("(TiledeskChatbot) FORM End");
297
+ winston.debug("(TiledeskChatbot) Unlocking intent for request: " + this.requestId);
298
+ winston.debug("(TiledeskChatbot) Populate data on lead:", lead);
299
+
438
300
  this.unlockIntent(this.requestId);
439
301
  if (lead) {
440
302
  this.populatePrechatFormAndLead(lead._id, this.requestId);
441
303
  }
442
304
  else {
443
- if (this.log) {console.log("No lead. Skipping populatePrechatFormAndLead()");}
305
+ winston.debug("(TiledeskChatbot) No lead. Skipping populatePrechatFormAndLead()");
444
306
  }
445
307
  const all_parameters = await this.allParameters();
446
- // if (this.log) {console.log("We have all_parameters:", all_parameters)};
447
308
  if (all_parameters && all_parameters["userFullname"]) {
448
309
  clientUpdateUserFullname = all_parameters["userFullname"];
449
310
  }
450
311
  }
451
312
  else if (form_reply.canceled) {
452
- console.log("Form canceled.");
453
- if (this.log) {console.log("unlocking intent due to canceling, for request", this.requestId);}
313
+ winston.verbose("(TiledeskChatbot) Form canceled");
314
+ winston.debug("(TiledeskChatbot) Unlocking intent due to canceling, for request", this.requestId);
454
315
  this.unlockIntent(this.requestId);
455
- if (this.log) {console.log("sending form 'cancel' reply...", form_reply.message)}
316
+ winston.debug("(TiledeskChatbot) Sending form 'cancel' reply...", form_reply.message)
456
317
  // reply with this message (ex. please enter your fullname)
457
318
  if (!form_reply.message.attributes) {
458
319
  form_reply.message.attributes = {}
@@ -460,9 +321,7 @@ class TiledeskChatbot {
460
321
  form_reply.message.attributes.fillParams = true;
461
322
  form_reply.message.attributes.splits = true;
462
323
  form_reply.message.attributes.directives = true;
463
- // // used by the Clients to get some info about the intent that generated this reply
464
- // form_reply.message.attributes.intent_display_name = faq.intent_display_name;
465
- // form_reply.message.attributes.intent_id = faq.intent_id;
324
+ // used by the Clients to get some info about the intent that generated this reply
466
325
  return form_reply.message
467
326
  }
468
327
  }
@@ -482,12 +341,6 @@ class TiledeskChatbot {
482
341
  if (answerObj.actions) {
483
342
  const actions_length = answerObj.actions.length;
484
343
  TiledeskChatbotUtil.addConnectAction(answerObj);
485
- if (this.log) {
486
- const new_actions_length = answerObj.actions.length;
487
- if (new_actions_length > actions_length) {
488
- console.log("Added connect to block action. All actions now:", JSON.stringify(answerObj.actions));
489
- }
490
- }
491
344
  }
492
345
 
493
346
  if (answerObj.actions && answerObj.actions.length > 0) {
@@ -506,7 +359,7 @@ class TiledeskChatbot {
506
359
  };
507
360
  }
508
361
  else {
509
- console.error("Intent with no actions or answer.", JSON.stringify(answerObj) );
362
+ winston.verbose("(TiledeskChatbot) Intent with no actions or answer.", answerObj);
510
363
  return null;
511
364
  }
512
365
 
@@ -533,21 +386,16 @@ class TiledeskChatbot {
533
386
  bot: this.bot
534
387
  }
535
388
  static_bot_answer.attributes.intent_info = intent_info;
536
- // console.log("static_bot_answer.attributes.intent_info",)
537
- // static_bot_answer.attributes.directives = true;
538
- // static_bot_answer.attributes.splits = true;
539
- // static_bot_answer.attributes.markbot = true;
540
- // static_bot_answer.attributes.fillParams = true;
541
389
  static_bot_answer.attributes.webhook = answerObj.webhook_enabled;
542
390
 
543
391
  if (clientUpdateUserFullname) {
544
- if (this.log) {console.log("We must clientUpdateUserFullname with:", clientUpdateUserFullname)};
392
+ winston.verbose("(TiledeskChatbot) We must clientUpdateUserFullname with:" + clientUpdateUserFullname)
545
393
  static_bot_answer.attributes.updateUserFullname = clientUpdateUserFullname;
546
394
  }
547
395
  // exec webhook
548
- if (this.log) {console.log("exec webhook on bot:", JSON.stringify(this.bot));}
396
+ winston.debug("(TiledeskChatbot) exec webhook on bot:", this.bot);
549
397
  const bot_answer = await this.execWebhook(static_bot_answer, message, this.bot, context, this.token);
550
- if (this.log) {console.log("bot_answer ready:", JSON.stringify(bot_answer));}
398
+ winston.debug("(TiledeskChatbot) bot_answer ready:", bot_answer);
551
399
  return bot_answer;
552
400
  }
553
401
 
@@ -574,7 +422,7 @@ class TiledeskChatbot {
574
422
  await this.tdcache.set("tilebot:requests:" + requestId + ":action:locked", action_id);
575
423
  }
576
424
  else {
577
- console.error("lockAction recoverable error, one of requestId:", requestId, "action_id:", action_id, "is null");
425
+ winston.error("(TiledeskChatbot) lockAction recoverable error, one of requestId: " + requestId + " action_id: " + action_id + " is null");
578
426
  }
579
427
  }
580
428
 
@@ -596,10 +444,6 @@ class TiledeskChatbot {
596
444
  }
597
445
 
598
446
  async getParameter(parameter_name) {
599
- // console.log("this.tdcache::", this.tdcache)
600
- // console.log("this.requestId::", this.requestId)
601
- // console.log("parameter_name::", parameter_name)
602
-
603
447
  return await TiledeskChatbot.getParameterStatic(this.tdcache, this.requestId, parameter_name);
604
448
  }
605
449
 
@@ -609,14 +453,11 @@ class TiledeskChatbot {
609
453
 
610
454
  static async addParameterStatic(_tdcache, requestId, parameter_name, parameter_value) {
611
455
  if (parameter_name === null || parameter_name === undefined) {
612
- // console.error("Error saving key:", parameter_name, "value:", parameter_value);
613
456
  return;
614
457
  }
615
458
  const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":parameters";
616
459
  const parameter_value_s = JSON.stringify(parameter_value);
617
- // console.log("saving key:", parameter_name, "value:", parameter_value);
618
460
  if (parameter_value_s?.length > 20000000) {
619
- // console.log("Error. Attribute size too big (> 20mb):", parameter_value_s);
620
461
  return;
621
462
  }
622
463
  await _tdcache.hset(parameter_key, parameter_name, parameter_value_s);
@@ -629,8 +470,6 @@ class TiledeskChatbot {
629
470
  static async allParametersStatic(_tdcache, requestId) {
630
471
  const parameters_key = TiledeskChatbot.requestCacheKey(requestId) + ":parameters";
631
472
  const attributes__as_string_map = await _tdcache.hgetall(parameters_key);
632
- // console.log("** getting parameters for requestId:", requestId);
633
- // console.log("** for key:", parameters_key, "parameters:", JSON.stringify(attributes__as_string_map));
634
473
  let attributes_native_values = {};
635
474
  if (attributes__as_string_map !== null) {
636
475
  for (const [key, value] of Object.entries(attributes__as_string_map)) {
@@ -638,31 +477,26 @@ class TiledeskChatbot {
638
477
  attributes_native_values[key] = JSON.parse(value);
639
478
  }
640
479
  catch(err) {
641
- console.error("An error occurred while JSON.parse(). Parsed value:" + value + " in allParametersStatic(). Error:", err);
480
+ winston.error("(TiledeskChatbot) An error occurred while JSON.parse(). Parsed value: " + value + " in allParametersStatic(). Error: " + JSON.stringify(err));
642
481
  }
643
482
  }
644
483
  }
645
- // else {
646
- // console.error("Warning: 'attributes__as_string_map' is null!");
647
- // }
648
484
  return attributes_native_values;
649
485
  }
650
486
 
651
487
  async allParametersInstance(_tdcache, requestId) {
652
- // const parameters_key = "tilebot:requests:" + requestId + ":parameters";
653
488
  return await _tdcache.hgetall(
654
489
  TiledeskChatbot.requestCacheKey(requestId) + ":parameters");
655
490
  }
656
491
 
657
492
  static async getParameterStatic(_tdcache, requestId, key) {
658
- // const parameters_key = "tilebot:requests:" + requestId + ":parameters";
659
493
  let value = await _tdcache.hget(
660
494
  TiledeskChatbot.requestCacheKey(requestId) + ":parameters", key);
661
495
  try {
662
496
  value = JSON.parse(value);
663
497
  }
664
498
  catch(error) {
665
- console.log("Error parsing to JSON an Attribute:", error);
499
+ winston.error("(TiledeskChatbot) Error parsing to JSON an Attribute:", error);
666
500
  }
667
501
  return value;
668
502
  }
@@ -673,18 +507,16 @@ class TiledeskChatbot {
673
507
  }
674
508
 
675
509
  static async checkStep(_tdcache, requestId, max_steps, max_execution_time, log) {
676
- if (log) {console.log("CHECKING ON MAX_STEPS:", max_steps);}
510
+ winston.verbose("(TiledeskChatbot) Checking on MAX_STEPS: " + max_steps);
677
511
  // let go_on = true; // continue
678
512
  const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":step";
679
- if (log) {console.log("__parameter_key:", parameter_key);}
513
+ winston.verbose("(TiledeskChatbot) __parameter_key:", parameter_key);
680
514
  await _tdcache.incr(parameter_key);
681
- // console.log("incr-ed");
682
515
  let _current_step = await _tdcache.get(parameter_key);
683
516
  let current_step = Number(_current_step);
684
517
  if (current_step > max_steps) {
685
- if (log) {console.log("max_steps limit just violated");}
686
- if (log) {console.log("CURRENT-STEP > MAX_STEPS!", current_step);}
687
- // go_on = false
518
+ winston.verbose("(TiledeskChatbot) max_steps limit just violated");
519
+ winston.verbose("(TiledeskChatbot) Current Step > Max Steps: " + current_step);
688
520
  return {
689
521
  error: "Anomaly detection. MAX ACTIONS (" + max_steps + ") exeeded."
690
522
  };
@@ -697,19 +529,15 @@ class TiledeskChatbot {
697
529
  // const TOTAL_ALLOWED_EXECUTION_TIME = 1000 * 60 // * 60 * 12 // 12 hours
698
530
  let start_time_key = TiledeskChatbot.requestCacheKey(requestId) + ":started";
699
531
  let start_time = await _tdcache.get(start_time_key);
700
- // console.log("cached start_time is:", start_time, typeof start_time);
701
532
  const now = Date.now();
702
533
  if (start_time === null || Number(start_time) === 0) {
703
- // console.log("start_time is null");
704
534
  await _tdcache.set(start_time_key, now);
705
535
  return {};
706
536
  }
707
537
  else {
708
- // console.log("start_time:", start_time);
709
538
  const execution_time = now - Number(start_time);
710
- // console.log("execution_time:", execution_time);
711
539
  if (execution_time > max_execution_time) {
712
- if (log) {console.log("execution_time > TOTAL_ALLOWED_EXECUTION_TIME. Stopping flow");}
540
+ winston.verbose("(TiledeskChatbot) execution_time > TOTAL_ALLOWED_EXECUTION_TIME. Stopping flow");
713
541
  return {
714
542
  error: "Anomaly detection. MAX EXECUTION TIME (" + max_execution_time + " ms) exeeded."
715
543
  };
@@ -720,7 +548,6 @@ class TiledeskChatbot {
720
548
 
721
549
  static async resetStep(_tdcache, requestId) {
722
550
  const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":step";
723
- // console.log("resetStep() parameter_key:", parameter_key);
724
551
  if (_tdcache) {
725
552
  await _tdcache.set(parameter_key, 0);
726
553
  }
@@ -728,7 +555,6 @@ class TiledeskChatbot {
728
555
 
729
556
  static async resetStarted(_tdcache, requestId) {
730
557
  const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":started";
731
- // console.log("resetStarted() parameter_key:", parameter_key);
732
558
  if (_tdcache) {
733
559
  await _tdcache.set(parameter_key, 0);
734
560
  }
@@ -736,7 +562,6 @@ class TiledeskChatbot {
736
562
 
737
563
  static async currentStep(_tdcache, requestId) {
738
564
  const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":step";
739
- // console.log("currentStep() parameter_key:", parameter_key);
740
565
  return await _tdcache.get(parameter_key);
741
566
  }
742
567
 
@@ -746,24 +571,22 @@ class TiledeskChatbot {
746
571
  }
747
572
 
748
573
  async execWebhook(static_bot_answer, userMessage, bot, context) {
749
- if (this.log) {console.log("static_bot_answer.attributes.webhook:", static_bot_answer.attributes.webhook);}
574
+ winston.verbose("(TiledeskChatbot) static_bot_answer.attributes.webhook:" + static_bot_answer.attributes.webhook);
750
575
  if (static_bot_answer.attributes && static_bot_answer.attributes.webhook && static_bot_answer.attributes.webhook === true) {
751
576
  const variables = await this.allParameters();
752
577
  context.variables = variables;
753
- if (this.log) {console.log("adding variables to webhook context:", JSON.stringify(context.variables));}
578
+ winston.debug("(TiledeskChatbot) adding variables to webhook context:", context.variables);
754
579
  }
755
580
  const messagePipeline = new MessagePipeline(static_bot_answer, context);
756
581
  const webhookurl = bot.webhook_url;
757
582
  messagePipeline.addPlug(new WebhookChatbotPlug(userMessage.request, webhookurl, this.token, this.log));
758
583
  const bot_answer = await messagePipeline.exec();
759
- //if (log) {console.log("End pipeline, bot_answer:", JSON.stringify(bot_answer));}
760
584
  return bot_answer;
761
585
  }
762
586
 
763
587
  async execIntentForm(userInputReply, form) {
764
- if (this.log) {console.log("executing intent form...")}
588
+ winston.verbose("(TiledeskChatbot) Executing intent form...")
765
589
  let all_parameters = await this.allParameters();
766
- // if (this.log) {console.log("allParameters for IntentForm:", all_parameters)}
767
590
  let intentForm = new IntentForm(
768
591
  {
769
592
  form: form,
@@ -777,10 +600,10 @@ class TiledeskChatbot {
777
600
  }
778
601
 
779
602
  async populatePrechatFormAndLead(leadId, requestId) {
780
- if (this.log) {console.log("(populatePrechatFormAndLead) leadId:", leadId);}
781
- if (this.log) {console.log("(populatePrechatFormAndLead) requestId:", requestId);}
603
+ winston.verbose("(TiledeskChatbot) (populatePrechatFormAndLead) leadId:" + leadId);
604
+ winston.verbose("(TiledeskChatbot) (populatePrechatFormAndLead) requestId:" + requestId);
782
605
  if (!leadId && !requestId) {
783
- if (this.log) {console.log("(populatePrechatFormAndLead) !leadId && !requestId");}
606
+ winston.verbose("(TiledeskChatbot) (populatePrechatFormAndLead) !leadId && !requestId");
784
607
  return;
785
608
  }
786
609
  const tdclient = new TiledeskClient({
@@ -792,18 +615,18 @@ class TiledeskChatbot {
792
615
  });
793
616
  // const parameters_key = "tilebot:requests:" + requestId + ":parameters";
794
617
  const all_parameters = await this.allParameters();//this.tdcache.hgetall(parameters_key);
795
- if (this.log) {console.log("(populatePrechatFormAndLead) parameters_key:", JSON.stringify(all_parameters));}
618
+ winston.debug("(TiledeskChatbot) (populatePrechatFormAndLead) parameters_key:" + JSON.stringify(all_parameters));
796
619
  if (all_parameters) {
797
- if (this.log) {console.log("(populatePrechatFormAndLead) userEmail:", all_parameters['userEmail']);}
798
- if (this.log) {console.log("(populatePrechatFormAndLead) userFullname:", all_parameters['userFullname']);}
799
- if (this.log) {console.log("(populatePrechatFormAndLead) userPhone:", all_parameters['userPhone']);}
620
+ winston.debug("(TiledeskChatbot) (populatePrechatFormAndLead) userEmail:" + all_parameters['userEmail']);
621
+ winston.debug("(TiledeskChatbot) (populatePrechatFormAndLead) userFullname:" + all_parameters['userFullname']);
622
+ winston.debug("(TiledeskChatbot) (populatePrechatFormAndLead) userPhone:" + all_parameters['userPhone']);
800
623
  let nativeAttributes = {
801
624
  email: all_parameters['userEmail'],
802
625
  fullname: all_parameters['userFullname'],
803
626
  phone: all_parameters['userPhone']
804
627
  }
805
628
  tdclient.updateLead(leadId, nativeAttributes, null, null, () => {
806
- if (this.log) {console.log("Lead updated.")}
629
+ winston.verbose("(TiledeskChatbot) Lead updated.")
807
630
  });
808
631
  };
809
632
  }