@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
@@ -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
8
  const { TiledeskChatbotUtil } = require('./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,44 @@ 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)
206
149
  resolve();
207
150
  }
208
151
  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
- }
152
+ winston.verbose("(TiledeskChatbot) Processing intent:", explicit_intent_name)
221
153
  let faq = await this.botsDataSource.getByIntentDisplayNameCache(this.botId, intent.name, this.tdcache);
222
154
  if (faq) {
223
- if (this.log) {
224
- console.log("Got a reply (faq) by Intent name:", JSON.stringify(faq));}
155
+ winston.verbose("(TiledeskChatbot) Got a reply (faq) by Intent name:", faq)
225
156
  try {
226
157
  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
158
  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);
159
+ winston.verbose("(TiledeskChatbot) Adding attribute from intent invocation /intentName{}: " + key + " " + value);
160
+ this.addParameter(key, value);
235
161
  }
236
162
  }
237
163
  reply = await this.execIntent(faq, message, lead);
@@ -239,12 +165,12 @@ class TiledeskChatbot {
239
165
  return;
240
166
  }
241
167
  catch(error) {
242
- console.error("error");
168
+ winston.error("(TiledeskChatbot) Error adding parameter: ", error);
243
169
  reject(error);
244
170
  }
245
171
  }
246
172
  else {
247
- if (this.log) {console.log("Intent not found:", explicit_intent_name);}
173
+ winston.verbose("(TiledeskChatbot) Intent not found: " + explicit_intent_name);
248
174
  resolve()
249
175
  }
250
176
  }
@@ -254,26 +180,20 @@ class TiledeskChatbot {
254
180
  let faqs;
255
181
  try {
256
182
  faqs = await this.botsDataSource.getByExactMatch(this.botId, message.text);
257
- if (this.log) {console.log("got faq by EXACT MATCH", faqs);}
183
+ winston.verbose("(TiledeskChatbot) Got faq by exact match: " + faqs);
258
184
  }
259
185
  catch (error) {
260
- console.error("(TiledeskChatbot) An error occurred during exact match:", JSON.stringify(error));
186
+ winston.error("(TiledeskChatbot) An error occurred during exact match: ", error);
261
187
  }
262
188
  if (faqs && faqs.length > 0 && faqs[0].answer) {
263
- if (this.log) {console.log("EXACT MATCH OR ACTION FAQ:", faqs[0]);}
189
+ winston.debug("(TiledeskChatbot) exact match or action faq: ", faqs[0]);
264
190
  let reply;
265
191
  const faq = faqs[0];
266
192
  try {
267
193
  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
194
  }
275
195
  catch(error) {
276
- console.error("error during exact match execIntent():", error);
196
+ winston.error("(TiledeskChatbot) An error occured during exact match execIntent(): ", error);
277
197
  reject(error);
278
198
  return;
279
199
  }
@@ -281,38 +201,30 @@ class TiledeskChatbot {
281
201
  return;
282
202
  }
283
203
  else { // NLP
284
- if (this.log) {console.log("Chatbot NLP decoding intent...");}
204
+ winston.verbose("(TiledeskChatbot) Chatbot NLP decoding intent...");
285
205
  let intents;
286
206
  try {
287
207
  intents = await this.intentsFinder.decode(this.botId, message.text);
288
- if (this.log) {console.log("Tiledesk AI intents found:", intents);}
208
+ winston.verbose("(TiledeskChatbot) Tiledesk AI intents found:", intents);
289
209
  }
290
210
  catch(error) {
291
- console.error("An error occurred on IntentsFinder.decode() (/model/parse error):", error.message);
211
+ winston.error("(TiledeskChatbot) An error occurred on IntentsFinder.decode() (/model/parse error):" + error.message);
292
212
  // recover on fulltext
293
213
  if (this.backupIntentsFinder) {
294
- if (this.log) {console.log("using backup Finder:", this.backupIntentsFinder);}
214
+ winston.debug("(TiledeskChatbot) Using backup Finder:", this.backupIntentsFinder);
295
215
  intents = await this.backupIntentsFinder.decode(this.botId, message.text);
296
- if (this.log) {console.log("Got intents from backup finder:", intents);}
216
+ winston.debug("(TiledeskChatbot) Got intents from backup finder: ", intents);
297
217
  }
298
218
  }
299
- if (this.log) {console.log("NLP intents found:", intents);}
219
+ winston.debug("(TiledeskChatbot) NLP intents found: ", intents);
300
220
  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
221
  let faq = await this.botsDataSource.getByIntentDisplayNameCache(this.botId, intents[0].intent_display_name, this.tdcache);
304
222
  let reply;
305
223
  try {
306
224
  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
225
  }
314
226
  catch(error) {
315
- console.error("error during NLP decoding:", error);
227
+ winston.error("(TiledeskChatbot) An error occurred during NLP decoding: ", error);
316
228
  reject(error);
317
229
  return;
318
230
  }
@@ -320,11 +232,8 @@ class TiledeskChatbot {
320
232
  return;
321
233
  }
322
234
  else {
323
- // fallback
324
- // let fallbackIntent = await this.botsDataSource.getByIntentDisplayName(this.botId, "defaultFallback");
325
235
  let fallbackIntent = await this.botsDataSource.getByIntentDisplayNameCache(this.botId, "defaultFallback", this.tdcache);
326
236
  if (!fallbackIntent) {
327
- // console.log("No defaultFallback found!");
328
237
  resolve(null);
329
238
  return;
330
239
  }
@@ -332,15 +241,9 @@ class TiledeskChatbot {
332
241
  let reply;
333
242
  try {
334
243
  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
244
  }
342
245
  catch(error) {
343
- console.error("error during defaultFallback:", error);
246
+ winston.error("(TiledeskChatbot) An error occurred during defaultFallback: ", error);
344
247
  reject(error);
345
248
  return;
346
249
  }
@@ -355,71 +258,28 @@ class TiledeskChatbot {
355
258
  async execIntent(faq, message, lead) {//, bot) {
356
259
  let answerObj = faq; // faqs[0];
357
260
  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
- }
261
+
262
+ winston.debug("(TiledeskChatbot) execIntent requestId: " + this.requestId)
263
+ winston.debug("(TiledeskChatbot) execIntent token: " + this.token)
264
+ winston.debug("(TiledeskChatbot) execIntent projectId: " + this.projectId)
265
+
366
266
  if (this.tdcache) {
367
267
  const requestKey = "tilebot:" + this.requestId
368
268
  await this.tdcache.setJSON(requestKey, this.request);
369
269
  }
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
270
 
384
271
  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
272
  let intent_form = answerObj.form;
411
- if (this.log) {
412
- console.log("IntentForm.isValidForm(intent_form)", IntentForm.isValidForm(intent_form));
413
- }
273
+
274
+ winston.debug("(TiledeskChatbot) IntentForm.isValidForm(intent_form)" + IntentForm.isValidForm(intent_form));
275
+
414
276
  let clientUpdateUserFullname = null;
415
277
  if (IntentForm.isValidForm(intent_form)) {
416
278
  await this.lockIntent(this.requestId, intent_name);
417
279
  const user_reply = message.text;
418
280
  let form_reply = await this.execIntentForm(user_reply, intent_form);
419
- // console.log("got form reply", form_reply)
420
281
  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)}
282
+ winston.debug("(TiledeskChatbot) Sending form reply...", form_reply.message)
423
283
  // reply with this message (ex. please enter your fullname)
424
284
  if (!form_reply.message.attributes) {
425
285
  form_reply.message.attributes = {}
@@ -430,29 +290,28 @@ class TiledeskChatbot {
430
290
  return form_reply.message;
431
291
  }
432
292
  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
- }
293
+
294
+ winston.debug("(TiledeskChatbot) FORM End");
295
+ winston.debug("(TiledeskChatbot) Unlocking intent for request: " + this.requestId);
296
+ winston.debug("(TiledeskChatbot) Populate data on lead:", lead);
297
+
438
298
  this.unlockIntent(this.requestId);
439
299
  if (lead) {
440
300
  this.populatePrechatFormAndLead(lead._id, this.requestId);
441
301
  }
442
302
  else {
443
- if (this.log) {console.log("No lead. Skipping populatePrechatFormAndLead()");}
303
+ winston.debug("(TiledeskChatbot) No lead. Skipping populatePrechatFormAndLead()");
444
304
  }
445
305
  const all_parameters = await this.allParameters();
446
- // if (this.log) {console.log("We have all_parameters:", all_parameters)};
447
306
  if (all_parameters && all_parameters["userFullname"]) {
448
307
  clientUpdateUserFullname = all_parameters["userFullname"];
449
308
  }
450
309
  }
451
310
  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);}
311
+ winston.verbose("(TiledeskChatbot) Form canceled");
312
+ winston.debug("(TiledeskChatbot) Unlocking intent due to canceling, for request", this.requestId);
454
313
  this.unlockIntent(this.requestId);
455
- if (this.log) {console.log("sending form 'cancel' reply...", form_reply.message)}
314
+ winston.debug("(TiledeskChatbot) Sending form 'cancel' reply...", form_reply.message)
456
315
  // reply with this message (ex. please enter your fullname)
457
316
  if (!form_reply.message.attributes) {
458
317
  form_reply.message.attributes = {}
@@ -460,9 +319,7 @@ class TiledeskChatbot {
460
319
  form_reply.message.attributes.fillParams = true;
461
320
  form_reply.message.attributes.splits = true;
462
321
  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;
322
+ // used by the Clients to get some info about the intent that generated this reply
466
323
  return form_reply.message
467
324
  }
468
325
  }
@@ -482,12 +339,6 @@ class TiledeskChatbot {
482
339
  if (answerObj.actions) {
483
340
  const actions_length = answerObj.actions.length;
484
341
  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
342
  }
492
343
 
493
344
  if (answerObj.actions && answerObj.actions.length > 0) {
@@ -506,7 +357,7 @@ class TiledeskChatbot {
506
357
  };
507
358
  }
508
359
  else {
509
- console.error("Intent with no actions or answer.", JSON.stringify(answerObj) );
360
+ winston.verbose("(TiledeskChatbot) Intent with no actions or answer.", answerObj);
510
361
  return null;
511
362
  }
512
363
 
@@ -533,21 +384,16 @@ class TiledeskChatbot {
533
384
  bot: this.bot
534
385
  }
535
386
  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
387
  static_bot_answer.attributes.webhook = answerObj.webhook_enabled;
542
388
 
543
389
  if (clientUpdateUserFullname) {
544
- if (this.log) {console.log("We must clientUpdateUserFullname with:", clientUpdateUserFullname)};
390
+ winston.verbose("(TiledeskChatbot) We must clientUpdateUserFullname with:" + clientUpdateUserFullname)
545
391
  static_bot_answer.attributes.updateUserFullname = clientUpdateUserFullname;
546
392
  }
547
393
  // exec webhook
548
- if (this.log) {console.log("exec webhook on bot:", JSON.stringify(this.bot));}
394
+ winston.debug("(TiledeskChatbot) exec webhook on bot:", this.bot);
549
395
  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));}
396
+ winston.debug("(TiledeskChatbot) bot_answer ready:", bot_answer);
551
397
  return bot_answer;
552
398
  }
553
399
 
@@ -574,7 +420,7 @@ class TiledeskChatbot {
574
420
  await this.tdcache.set("tilebot:requests:" + requestId + ":action:locked", action_id);
575
421
  }
576
422
  else {
577
- console.error("lockAction recoverable error, one of requestId:", requestId, "action_id:", action_id, "is null");
423
+ winston.error("(TiledeskChatbot) lockAction recoverable error, one of requestId: " + requestId + " action_id: " + action_id + " is null");
578
424
  }
579
425
  }
580
426
 
@@ -596,10 +442,6 @@ class TiledeskChatbot {
596
442
  }
597
443
 
598
444
  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
445
  return await TiledeskChatbot.getParameterStatic(this.tdcache, this.requestId, parameter_name);
604
446
  }
605
447
 
@@ -609,14 +451,11 @@ class TiledeskChatbot {
609
451
 
610
452
  static async addParameterStatic(_tdcache, requestId, parameter_name, parameter_value) {
611
453
  if (parameter_name === null || parameter_name === undefined) {
612
- // console.error("Error saving key:", parameter_name, "value:", parameter_value);
613
454
  return;
614
455
  }
615
456
  const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":parameters";
616
457
  const parameter_value_s = JSON.stringify(parameter_value);
617
- // console.log("saving key:", parameter_name, "value:", parameter_value);
618
458
  if (parameter_value_s?.length > 20000000) {
619
- // console.log("Error. Attribute size too big (> 20mb):", parameter_value_s);
620
459
  return;
621
460
  }
622
461
  await _tdcache.hset(parameter_key, parameter_name, parameter_value_s);
@@ -629,8 +468,6 @@ class TiledeskChatbot {
629
468
  static async allParametersStatic(_tdcache, requestId) {
630
469
  const parameters_key = TiledeskChatbot.requestCacheKey(requestId) + ":parameters";
631
470
  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
471
  let attributes_native_values = {};
635
472
  if (attributes__as_string_map !== null) {
636
473
  for (const [key, value] of Object.entries(attributes__as_string_map)) {
@@ -638,31 +475,26 @@ class TiledeskChatbot {
638
475
  attributes_native_values[key] = JSON.parse(value);
639
476
  }
640
477
  catch(err) {
641
- console.error("An error occurred while JSON.parse(). Parsed value:" + value + " in allParametersStatic(). Error:", err);
478
+ winston.error("(TiledeskChatbot) An error occurred while JSON.parse(). Parsed value: " + value + " in allParametersStatic(). Error: " + JSON.stringify(err));
642
479
  }
643
480
  }
644
481
  }
645
- // else {
646
- // console.error("Warning: 'attributes__as_string_map' is null!");
647
- // }
648
482
  return attributes_native_values;
649
483
  }
650
484
 
651
485
  async allParametersInstance(_tdcache, requestId) {
652
- // const parameters_key = "tilebot:requests:" + requestId + ":parameters";
653
486
  return await _tdcache.hgetall(
654
487
  TiledeskChatbot.requestCacheKey(requestId) + ":parameters");
655
488
  }
656
489
 
657
490
  static async getParameterStatic(_tdcache, requestId, key) {
658
- // const parameters_key = "tilebot:requests:" + requestId + ":parameters";
659
491
  let value = await _tdcache.hget(
660
492
  TiledeskChatbot.requestCacheKey(requestId) + ":parameters", key);
661
493
  try {
662
494
  value = JSON.parse(value);
663
495
  }
664
496
  catch(error) {
665
- console.log("Error parsing to JSON an Attribute:", error);
497
+ winston.error("(TiledeskChatbot) Error parsing to JSON an Attribute:", error);
666
498
  }
667
499
  return value;
668
500
  }
@@ -673,18 +505,16 @@ class TiledeskChatbot {
673
505
  }
674
506
 
675
507
  static async checkStep(_tdcache, requestId, max_steps, max_execution_time, log) {
676
- if (log) {console.log("CHECKING ON MAX_STEPS:", max_steps);}
508
+ winston.verbose("(TiledeskChatbot) Checking on MAX_STEPS: " + max_steps);
677
509
  // let go_on = true; // continue
678
510
  const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":step";
679
- if (log) {console.log("__parameter_key:", parameter_key);}
511
+ winston.verbose("(TiledeskChatbot) __parameter_key:", parameter_key);
680
512
  await _tdcache.incr(parameter_key);
681
- // console.log("incr-ed");
682
513
  let _current_step = await _tdcache.get(parameter_key);
683
514
  let current_step = Number(_current_step);
684
515
  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
516
+ winston.verbose("(TiledeskChatbot) max_steps limit just violated");
517
+ winston.verbose("(TiledeskChatbot) Current Step > Max Steps: " + current_step);
688
518
  return {
689
519
  error: "Anomaly detection. MAX ACTIONS (" + max_steps + ") exeeded."
690
520
  };
@@ -697,19 +527,15 @@ class TiledeskChatbot {
697
527
  // const TOTAL_ALLOWED_EXECUTION_TIME = 1000 * 60 // * 60 * 12 // 12 hours
698
528
  let start_time_key = TiledeskChatbot.requestCacheKey(requestId) + ":started";
699
529
  let start_time = await _tdcache.get(start_time_key);
700
- // console.log("cached start_time is:", start_time, typeof start_time);
701
530
  const now = Date.now();
702
531
  if (start_time === null || Number(start_time) === 0) {
703
- // console.log("start_time is null");
704
532
  await _tdcache.set(start_time_key, now);
705
533
  return {};
706
534
  }
707
535
  else {
708
- // console.log("start_time:", start_time);
709
536
  const execution_time = now - Number(start_time);
710
- // console.log("execution_time:", execution_time);
711
537
  if (execution_time > max_execution_time) {
712
- if (log) {console.log("execution_time > TOTAL_ALLOWED_EXECUTION_TIME. Stopping flow");}
538
+ winston.verbose("(TiledeskChatbot) execution_time > TOTAL_ALLOWED_EXECUTION_TIME. Stopping flow");
713
539
  return {
714
540
  error: "Anomaly detection. MAX EXECUTION TIME (" + max_execution_time + " ms) exeeded."
715
541
  };
@@ -720,7 +546,6 @@ class TiledeskChatbot {
720
546
 
721
547
  static async resetStep(_tdcache, requestId) {
722
548
  const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":step";
723
- // console.log("resetStep() parameter_key:", parameter_key);
724
549
  if (_tdcache) {
725
550
  await _tdcache.set(parameter_key, 0);
726
551
  }
@@ -728,7 +553,6 @@ class TiledeskChatbot {
728
553
 
729
554
  static async resetStarted(_tdcache, requestId) {
730
555
  const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":started";
731
- // console.log("resetStarted() parameter_key:", parameter_key);
732
556
  if (_tdcache) {
733
557
  await _tdcache.set(parameter_key, 0);
734
558
  }
@@ -736,7 +560,6 @@ class TiledeskChatbot {
736
560
 
737
561
  static async currentStep(_tdcache, requestId) {
738
562
  const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":step";
739
- // console.log("currentStep() parameter_key:", parameter_key);
740
563
  return await _tdcache.get(parameter_key);
741
564
  }
742
565
 
@@ -746,24 +569,22 @@ class TiledeskChatbot {
746
569
  }
747
570
 
748
571
  async execWebhook(static_bot_answer, userMessage, bot, context) {
749
- if (this.log) {console.log("static_bot_answer.attributes.webhook:", static_bot_answer.attributes.webhook);}
572
+ winston.verbose("(TiledeskChatbot) static_bot_answer.attributes.webhook:" + static_bot_answer.attributes.webhook);
750
573
  if (static_bot_answer.attributes && static_bot_answer.attributes.webhook && static_bot_answer.attributes.webhook === true) {
751
574
  const variables = await this.allParameters();
752
575
  context.variables = variables;
753
- if (this.log) {console.log("adding variables to webhook context:", JSON.stringify(context.variables));}
576
+ winston.debug("(TiledeskChatbot) adding variables to webhook context:", context.variables);
754
577
  }
755
578
  const messagePipeline = new MessagePipeline(static_bot_answer, context);
756
579
  const webhookurl = bot.webhook_url;
757
580
  messagePipeline.addPlug(new WebhookChatbotPlug(userMessage.request, webhookurl, this.token, this.log));
758
581
  const bot_answer = await messagePipeline.exec();
759
- //if (log) {console.log("End pipeline, bot_answer:", JSON.stringify(bot_answer));}
760
582
  return bot_answer;
761
583
  }
762
584
 
763
585
  async execIntentForm(userInputReply, form) {
764
- if (this.log) {console.log("executing intent form...")}
586
+ winston.verbose("(TiledeskChatbot) Executing intent form...")
765
587
  let all_parameters = await this.allParameters();
766
- // if (this.log) {console.log("allParameters for IntentForm:", all_parameters)}
767
588
  let intentForm = new IntentForm(
768
589
  {
769
590
  form: form,
@@ -777,10 +598,10 @@ class TiledeskChatbot {
777
598
  }
778
599
 
779
600
  async populatePrechatFormAndLead(leadId, requestId) {
780
- if (this.log) {console.log("(populatePrechatFormAndLead) leadId:", leadId);}
781
- if (this.log) {console.log("(populatePrechatFormAndLead) requestId:", requestId);}
601
+ winston.verbose("(TiledeskChatbot) (populatePrechatFormAndLead) leadId:" + leadId);
602
+ winston.verbose("(TiledeskChatbot) (populatePrechatFormAndLead) requestId:" + requestId);
782
603
  if (!leadId && !requestId) {
783
- if (this.log) {console.log("(populatePrechatFormAndLead) !leadId && !requestId");}
604
+ winston.verbose("(TiledeskChatbot) (populatePrechatFormAndLead) !leadId && !requestId");
784
605
  return;
785
606
  }
786
607
  const tdclient = new TiledeskClient({
@@ -792,18 +613,18 @@ class TiledeskChatbot {
792
613
  });
793
614
  // const parameters_key = "tilebot:requests:" + requestId + ":parameters";
794
615
  const all_parameters = await this.allParameters();//this.tdcache.hgetall(parameters_key);
795
- if (this.log) {console.log("(populatePrechatFormAndLead) parameters_key:", JSON.stringify(all_parameters));}
616
+ winston.debug("(TiledeskChatbot) (populatePrechatFormAndLead) parameters_key:" + JSON.stringify(all_parameters));
796
617
  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']);}
618
+ winston.debug("(TiledeskChatbot) (populatePrechatFormAndLead) userEmail:" + all_parameters['userEmail']);
619
+ winston.debug("(TiledeskChatbot) (populatePrechatFormAndLead) userFullname:" + all_parameters['userFullname']);
620
+ winston.debug("(TiledeskChatbot) (populatePrechatFormAndLead) userPhone:" + all_parameters['userPhone']);
800
621
  let nativeAttributes = {
801
622
  email: all_parameters['userEmail'],
802
623
  fullname: all_parameters['userFullname'],
803
624
  phone: all_parameters['userPhone']
804
625
  }
805
626
  tdclient.updateLead(leadId, nativeAttributes, null, null, () => {
806
- if (this.log) {console.log("Lead updated.")}
627
+ winston.verbose("(TiledeskChatbot) Lead updated.")
807
628
  });
808
629
  };
809
630
  }