@tiledesk/tiledesk-tybot-connector 0.1.47 → 0.1.49

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 (30) hide show
  1. package/.env +0 -6
  2. package/CHANGELOG.md +9 -0
  3. package/TdCache.js +15 -0
  4. package/TiledeskExpression.js +23 -5
  5. package/index.js +96 -72
  6. package/models/MockTdCache.js +27 -3
  7. package/models/MongodbIntentsMachine.js +2 -2
  8. package/models/TiledeskChatbot.js +78 -1
  9. package/models/TiledeskChatbotUtil.js +16 -0
  10. package/package.json +4 -3
  11. package/test/anomaly-detection-test.js +173 -0
  12. package/test/check_steps_test.js +23 -0
  13. package/test/conversation-actions_bot.js +20 -7
  14. package/test/conversation-locked-intent-test.js +242 -0
  15. package/tiledeskChatbotPlugs/DirectivesChatbotPlug.js +275 -331
  16. package/tiledeskChatbotPlugs/FillParamsChatbotPlug.js +1 -1
  17. package/tiledeskChatbotPlugs/Filler.js +5 -1
  18. package/tiledeskChatbotPlugs/directives/DirAssign.js +11 -5
  19. package/tiledeskChatbotPlugs/directives/DirCondition.js +16 -7
  20. package/tiledeskChatbotPlugs/directives/DirDeleteVariable.js +1 -3
  21. package/tiledeskChatbotPlugs/directives/DirDepartment.js +1 -3
  22. package/tiledeskChatbotPlugs/directives/DirIfOnlineAgents.js +2 -4
  23. package/tiledeskChatbotPlugs/directives/DirIntent.js +1 -3
  24. package/tiledeskChatbotPlugs/directives/DirMessage.js +14 -13
  25. package/tiledeskChatbotPlugs/directives/DirMoveToAgent.js +8 -9
  26. package/tiledeskChatbotPlugs/directives/DirReplaceBot.js +14 -6
  27. package/tiledeskChatbotPlugs/directives/DirReply.js +100 -0
  28. package/tiledeskChatbotPlugs/directives/DirSendEmail.js +4 -6
  29. package/tiledeskChatbotPlugs/directives/DirWait.js +6 -6
  30. package/tiledeskChatbotPlugs/directives/Directives.js +7 -3
package/.env CHANGED
@@ -7,9 +7,3 @@ _TYBOT_ENDPOINT=http://localhost:3000
7
7
  CHATBOT_TOKEN=JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3ZWJob29rX2VuYWJsZWQiOmZhbHNlLCJ0eXBlIjoiZXh0ZXJuYWwiLCJsYW5ndWFnZSI6ImVuIiwicHVibGljIjpmYWxzZSwiX2lkIjoiNjM4Yzc5MDQxZGI0NDkwMDM1MTEwMjYwIiwibmFtZSI6IlRoZSBGb3JtIHYyIC0gZXh0IiwidXJsIjoiaHR0cHM6Ly90aWxlYm90LWRldi5oZXJva3VhcHAuY29tL2V4dC82MzhjNzhkNzFkYjQ0OTAwMzUxMTAxYzIiLCJpZF9wcm9qZWN0IjoiNjM4Yzc4YTYxZGI0NDkwMDM1MTBmZjkxIiwidHJhc2hlZCI6ZmFsc2UsImNyZWF0ZWRCeSI6IjVlMDlkMTZkNGQzNjExMDAxNzUwNmQ3ZiIsImNyZWF0ZWRBdCI6IjIwMjItMTItMDRUMTA6NDA6MDQuMjA3WiIsInVwZGF0ZWRBdCI6IjIwMjItMTItMDVUMDc6MjE6MDIuOTIxWiIsIl9fdiI6MCwiZGVzY3JpcHRpb24iOiJPbiBIZXJva3UiLCJpYXQiOjE2NzA2NzE4ODksImF1ZCI6Imh0dHBzOi8vdGlsZWRlc2suY29tL2JvdHMvNjM4Yzc5MDQxZGI0NDkwMDM1MTEwMjYwIiwiaXNzIjoiaHR0cHM6Ly90aWxlZGVzay5jb20iLCJzdWIiOiJib3QiLCJqdGkiOiJmNDVlZGIwYS0zNzVhLTQ0NjMtYjFhZi1jM2ZiZDg4YmE3ZGQifQ.FbW3csHl1sQgSyRz5Jg0qaTvvpXWXgWHlJ1JWoVbv3s
8
8
  _CHATBOT_ENDPOINT=http://localhost:10001
9
9
  _API_LOG=1
10
- TEST_PROJECT_ID=638c78a61db449003510ff91
11
- TEST_BOT_ID=638c78d71db44900351101c2
12
-
13
- TEST_ACTIONS_PROJECT_ID=63b2ab8fd0029e0035252df5
14
- TEST_ACTIONS_BOT_ID=63b2aba4d0029e0035252ebb
15
- ACTIONS_CHATBOT_TOKEN=JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3ZWJob29rX2VuYWJsZWQiOmZhbHNlLCJ0eXBlIjoiZXh0ZXJuYWwiLCJsYW5ndWFnZSI6ImVuIiwicHVibGljIjpmYWxzZSwiY2VydGlmaWVkIjpmYWxzZSwiaW50ZW50c0VuZ2luZSI6Im5vbmUiLCJfaWQiOiI2M2IyYWJkY2QwMDI5ZTAwMzUyNTMyNGIiLCJuYW1lIjoiQWN0aW9ucyBCb3QgLSBleHQiLCJ1cmwiOiJodHRwczovL3RpbGVib3QtZGV2Lmhlcm9rdWFwcC5jb20vZXh0LzYzYjJhYmE0ZDAwMjllMDAzNTI1MmViYiIsImlkX3Byb2plY3QiOiI2M2IyYWI4ZmQwMDI5ZTAwMzUyNTJkZjUiLCJ0cmFzaGVkIjpmYWxzZSwiY3JlYXRlZEJ5IjoiNWUwOWQxNmQ0ZDM2MTEwMDE3NTA2ZDdmIiwiY3JlYXRlZEF0IjoiMjAyMy0wMS0wMlQxMDowMzowOC43NTVaIiwidXBkYXRlZEF0IjoiMjAyMy0wMS0wMlQxMDowMzo1MS4yOTZaIiwiX192IjowLCJpYXQiOjE2NzMzNzA5NzksImF1ZCI6Imh0dHBzOi8vdGlsZWRlc2suY29tL2JvdHMvNjNiMmFiZGNkMDAyOWUwMDM1MjUzMjRiIiwiaXNzIjoiaHR0cHM6Ly90aWxlZGVzay5jb20iLCJzdWIiOiJib3QiLCJqdGkiOiJjMTI2ZTk1Yi1lMGY2LTRmNDQtOTQ3NS0xN2IxNDMzYmY0MjEifQ.TWfVy7frEA98o596xCa-8hNnBAzBVhpYTz9p_zmNA4M
package/CHANGELOG.md CHANGED
@@ -5,6 +5,15 @@
5
5
  available on:
6
6
  ▶️ https://www.npmjs.com/package/@tiledesk/tiledesk-tybot-connector
7
7
 
8
+ ### 0.1.49
9
+ - anomaly detection
10
+ - bug fix
11
+
12
+ ### 0.1.48
13
+ - fixed ReplaceBot "log" bug
14
+ - ReplaceBot fill-variables botName
15
+ - fixing
16
+
8
17
  ### 0.1.47
9
18
  - Introduced _tdIfOnlineAgents --trueIntent -- falseIntent
10
19
  - Refactored _tdIfOpenHours --trueIntent -- falseIntent
package/TdCache.js CHANGED
@@ -72,6 +72,21 @@ class TdCache {
72
72
  });
73
73
  }
74
74
 
75
+ async incr(key) {
76
+ // console.log("incr key:", key)
77
+ return new Promise( async (resolve, reject) => {
78
+ try {
79
+ // console.log("incr here...key", key)
80
+ await this.client.incr(key);
81
+ }
82
+ catch(error) {
83
+ console.error("Error on incr:", error);
84
+ reject(error)
85
+ }
86
+ return resolve();
87
+ });
88
+ }
89
+
75
90
  async hset(dict_key, key, value, options) {
76
91
  //console.log("hsetting dict_key key value", dict_key, key, value)
77
92
  return new Promise( async (resolve, reject) => {
@@ -1,3 +1,5 @@
1
+ const {VM} = require('vm2');
2
+
1
3
  class TiledeskExpression {
2
4
  // rules:
3
5
  // check valid operators (only those in operators are allowed)
@@ -45,17 +47,33 @@ class TiledeskExpression {
45
47
  }
46
48
 
47
49
  // private
50
+ // evaluate(expression, context) {
51
+ // let fn;
52
+ // let res
53
+ // try {
54
+ // fn = Function(`let $data = this;return (${expression})`);
55
+ // res = fn.bind(context)()
56
+ // }
57
+ // catch (err) {
58
+ // console.error("TiledeskExpression.evaluate() error:", err.message, "evaluating expression: '" + expression + "'");
59
+ // }
60
+ // // let fn = Function(`let $data = this;console.log('data', $data);return (${conditionExpression})`);
61
+ // return res;
62
+ // }
63
+
48
64
  evaluate(expression, context) {
49
- let fn;
50
- let res
65
+ let res;
51
66
  try {
52
- fn = Function(`let $data = this;return (${expression})`);
53
- res = fn.bind(context)()
67
+ const vm = new VM({
68
+ timeout: 200,
69
+ allowAsync: false,
70
+ sandbox: context
71
+ });
72
+ res = vm.run(`let $data = this;${expression}`);
54
73
  }
55
74
  catch (err) {
56
75
  console.error("TiledeskExpression.evaluate() error:", err.message, "evaluating expression: '" + expression + "'");
57
76
  }
58
- // let fn = Function(`let $data = this;console.log('data', $data);return (${conditionExpression})`);
59
77
  return res;
60
78
  }
61
79
 
package/index.js CHANGED
@@ -27,30 +27,31 @@ let log = false;
27
27
  let tdcache = null;
28
28
 
29
29
  // DEV
30
- const { MessagePipeline } = require('./tiledeskChatbotPlugs/MessagePipeline');
30
+ // const { MessagePipeline } = require('./tiledeskChatbotPlugs/MessagePipeline');
31
31
  const { DirectivesChatbotPlug } = require('./tiledeskChatbotPlugs/DirectivesChatbotPlug');
32
- /*const { SplitsChatbotPlug } = require('./tiledeskChatbotPlugs/SplitsChatbotPlug');
33
- const { MarkbotChatbotPlug } = require('./tiledeskChatbotPlugs/MarkbotChatbotPlug');*/
34
- const { WebhookChatbotPlug } = require('./tiledeskChatbotPlugs/WebhookChatbotPlug');
32
+ // const { SplitsChatbotPlug } = require('./tiledeskChatbotPlugs/SplitsChatbotPlug');
33
+ // const { MarkbotChatbotPlug } = require('./tiledeskChatbotPlugs/MarkbotChatbotPlug');
34
+ // const { WebhookChatbotPlug } = require('./tiledeskChatbotPlugs/WebhookChatbotPlug');
35
35
 
36
36
  // PROD
37
- /*const { MessagePipeline } = require('@tiledesk/tiledesk-chatbot-plugs/MessagePipeline');
38
- const { DirectivesChatbotPlug } = require('@tiledesk/tiledesk-chatbot-plugs/DirectivesChatbotPlug');
39
- const { SplitsChatbotPlug } = require('@tiledesk/tiledesk-chatbot-plugs/SplitsChatbotPlug');
40
- const { MarkbotChatbotPlug } = require('@tiledesk/tiledesk-chatbot-plugs/MarkbotChatbotPlug');
41
- const { WebhookChatbotPlug } = require('@tiledesk/tiledesk-chatbot-plugs/WebhookChatbotPlug');*/
37
+ // const { MessagePipeline } = require('@tiledesk/tiledesk-chatbot-plugs/MessagePipeline');
38
+ // const { DirectivesChatbotPlug } = require('@tiledesk/tiledesk-chatbot-plugs/DirectivesChatbotPlug');
39
+ // const { SplitsChatbotPlug } = require('@tiledesk/tiledesk-chatbot-plugs/SplitsChatbotPlug');
40
+ // const { MarkbotChatbotPlug } = require('@tiledesk/tiledesk-chatbot-plugs/MarkbotChatbotPlug');
41
+ // const { WebhookChatbotPlug } = require('@tiledesk/tiledesk-chatbot-plugs/WebhookChatbotPlug');
42
42
 
43
43
  // THE IMPORT
44
44
  let mongoose = require('mongoose');
45
- const { DirSendEmail } = require('./tiledeskChatbotPlugs/directives/DirSendEmail.js');
45
+ // const { DirSendEmail } = require('./tiledeskChatbotPlugs/directives/DirSendEmail.js');
46
46
  const { Directives } = require('./tiledeskChatbotPlugs/directives/Directives.js');
47
- //let Faq = require('./models/faq');
48
- //let Faq_kb = require('./models/faq_kb');
49
- // let connection;
50
47
  let APIURL = null;
51
48
  let staticBots;
52
49
 
53
50
  router.post('/ext/:botid', async (req, res) => {
51
+ if (req && req.body && req.body.payload && req.body.payload.request && req.body.payload.request.snapshot) {
52
+ delete req.body.payload.request.snapshot;
53
+ console.log("Removed req.body.payload.request.snapshot field");
54
+ }
54
55
  if (log) {console.log("REQUEST BODY:", JSON.stringify(req.body));}
55
56
  res.status(200).send({"success":true});
56
57
 
@@ -68,16 +69,6 @@ router.post('/ext/:botid', async (req, res) => {
68
69
  if (message.request.id_project === null || message.request.id_project === undefined) {
69
70
  message.request.id_project = projectId;
70
71
  }
71
-
72
- let requestSourcePage = null;
73
- let requestLanguage = null;
74
- let requestUserAgent = null;
75
-
76
- if (message.payload) {
77
- requestSourcePage = message.payload.sourcePage;
78
- requestLanguage = message.payload.language;
79
- requestUserAgent = message.payload.userAgent;
80
- }
81
72
 
82
73
  // NEXTTTTTTT
83
74
  // const message_context = {
@@ -117,8 +108,10 @@ router.post('/ext/:botid', async (req, res) => {
117
108
 
118
109
  let intentsMachine;
119
110
  if (!staticBots) {
120
- intentsMachine = new MongodbIntentsMachine({projectId: projectId, language: bot.language});
111
+ if (log) {console.log("intentsMachine to MongoDB");}
112
+ intentsMachine = new MongodbIntentsMachine({projectId: projectId, language: bot.language, log});
121
113
  if (bot.intentsEngine === "tiledesk-ai") {
114
+ if (log) {console.log("intentsMachine to tiledesk-ai");}
122
115
  intentsMachine = new TiledeskIntentsMachine(
123
116
  {
124
117
  //projectId: projectId,
@@ -146,60 +139,14 @@ router.post('/ext/:botid', async (req, res) => {
146
139
  log: log
147
140
  });
148
141
 
149
- // initial request context
150
- await chatbot.addParameter("_tdLastMessageId", messageId);
151
- await chatbot.addParameter("_tdProjectId", projectId);
152
- await chatbot.addParameter("_tdRequestId", requestId);
153
- if (message.request && message.request.location && message.request.location.country) {
154
- await chatbot.addParameter("_tdCountry", message.request.location.country);
155
- }
156
- if (message.request && message.request.location && message.request.location.city) {
157
- await chatbot.addParameter("_tdCity", message.request.location.city);
158
- }
159
- if (message.text) {
160
- await chatbot.addParameter("_tdUserText", message.text);
161
- }
162
- if (requestSourcePage) {
163
- await chatbot.addParameter("_tdRequestSourcePage", sourcePage);
164
- }
165
- if (requestLanguage) {
166
- await chatbot.addParameter("_tdRequestLanguage", language);
167
- }
168
- if (requestUserAgent) {
169
- await chatbot.addParameter("_tdRequestUserAgent", userAgent);
170
- }
142
+ await updateRequestVariables(chatbot, message, projectId, requestId);
143
+
171
144
  let reply = await chatbot.replyToMessage(message);
172
145
  if (!reply) {
173
146
  reply = {
174
147
  "text": "No messages found. Is 'defaultFallback' intent missing?"
175
148
  }
176
149
  }
177
- // console.log("reply back:", JSON.stringify(reply));
178
-
179
- // TEMP
180
- // if (reply.attributes && reply.attributes.intent_info) {
181
- // switch (reply.attributes.intent_info.intent_name) {
182
- // case "MessageActions":
183
- // reply.actions = MockActions.MessageActions()
184
- // break;
185
- // case "Message_plus_Agent":
186
- // reply.actions = MockActions.Message_plus_Agent();
187
- // break;
188
- // case "Message_plus_AgentWhenOnline":
189
- // reply.actions = MockActions.Message_plus_AgentWhenOnline();
190
- // break;
191
- // case "Message_plus_Close":
192
- // reply.actions = MockActions.Message_plus_Close();
193
- // break;
194
- // case "ChangeDepartment":
195
- // reply.actions = MockActions.ChangeDepartment();
196
- // break;
197
- // case "Intent":
198
- // reply.actions = MockActions.Intent();
199
- // break;
200
- // }
201
- // }
202
-
203
150
 
204
151
  // console.log("reply.actions:", reply.actions);
205
152
  if (reply.actions && reply.actions.length > 0) { // structured actions (coming from chatbot designer)
@@ -250,6 +197,83 @@ router.post('/ext/:botid', async (req, res) => {
250
197
 
251
198
  });
252
199
 
200
+ async function updateRequestVariables(chatbot, message, projectId, requestId) {
201
+ // update request context
202
+ const messageId = message._id;
203
+ await chatbot.addParameter("_tdProjectId", projectId);
204
+ await chatbot.addParameter("_tdRequestId", requestId);
205
+ if (message.text) {
206
+ await chatbot.addParameter("_tdLastUserText", message.text);
207
+ }
208
+ await chatbot.addParameter("_tdLastMessageId", messageId);
209
+ if (message.request && message.request.location && message.request.location.country) {
210
+ await chatbot.addParameter("_tdCountry", message.request.location.country);
211
+ }
212
+ if (message.request && message.request.location && message.request.location.city) {
213
+ await chatbot.addParameter("_tdCity", message.request.location.city);
214
+ }
215
+ // console.log("message.request.language", message.request["language"])
216
+ if (message.request) {
217
+ await chatbot.addParameter("_tdUserSourcePage", message.request.sourcePage);
218
+ await chatbot.addParameter("_tdUserLanguage", message.request["language"]);
219
+ await chatbot.addParameter("_tdUserAgent", message.request.userAgent);
220
+ }
221
+ if (message.attributes) {
222
+ await chatbot.addParameter("_tdRequestDepartmentId", message.attributes.departmentId);
223
+ await chatbot.addParameter("_tdRequestDepartmentName", message.attributes.departmentName);
224
+ await chatbot.addParameter("_tdRequestRequesterId", message.attributes.requester_id);
225
+ await chatbot.addParameter("_tdRequestIpAddress", message.attributes.ipAddress);
226
+ if (message.attributes.payload) {
227
+ try {
228
+ for (const [key, value] of Object.entries(message.attributes.payload)) {
229
+ // const value = all_parameters[key];
230
+ const value_type = typeof value;
231
+ if (chatbot.log) {console.log("importing payload parameter:", key, "value:", value, "type:", value_type)}
232
+ await chatbot.addParameter(key, String(value));
233
+ }
234
+ }
235
+ catch(err) {
236
+ console.error("Error importing message payload in request variables:", err);
237
+ }
238
+ }
239
+ }
240
+ if (chatbot.log) {
241
+ const all_parameters = await TiledeskChatbot.allParametersStatic(chatbot.tdcache, requestId);
242
+ for (const [key, value] of Object.entries(all_parameters)) {
243
+ // const value = all_parameters[key];
244
+ const value_type = typeof value;
245
+ if (chatbot.log) {console.log("request parameter:", key, "value:", value, "type:", value_type)}
246
+ }
247
+ }
248
+ // message["attributes"]: {
249
+ // "departmentId": "63c980054f857c00350535bc",
250
+ // "departmentName": "Default Department",
251
+ // "client": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
252
+ // "sourcePage": "https://tiledesk-html-site.tiledesk.repl.co/custom-attributes.html",
253
+ // "projectId": "63c980054f857c00350535b8",
254
+ // "payload": {
255
+ // "user_country": "Italy",
256
+ // "user_code": "E001"
257
+ // },
258
+ // "userFullname": "guest#7216 ",
259
+ // "requester_id": "7216926a-84c3-4bd5-aa79-8bd763094dc0",
260
+ // "ipAddress": "79.8.190.172",
261
+ // "sourceTitle": "Custom attributes",
262
+ // "widgetVer": "v.5.0.53-rc.4",
263
+ // "subtype": "info",
264
+ // "decoded_jwt": {
265
+ // "_id": "7216926a-84c3-4bd5-aa79-8bd763094dc0",
266
+ // "firstname": "guest#7216",
267
+ // "id": "7216926a-84c3-4bd5-aa79-8bd763094dc0",
268
+ // "fullName": "guest#7216 ",
269
+ // "iat": 1674201892,
270
+ // "aud": "https://tiledesk.com",
271
+ // "iss": "https://tiledesk.com",
272
+ // "sub": "guest",
273
+ // "jti": "f053af3d-14ca-411b-9903-78bd74e24218"
274
+ // }
275
+ }
276
+
253
277
  function actionsToDirectives(actions) {
254
278
  let directives = [];
255
279
  if (actions && actions.length > 0) {
@@ -7,14 +7,38 @@ class MockTdCache {
7
7
  this.db = new Map();
8
8
  }
9
9
 
10
- set(k, v) {
10
+ async set(k, v) {
11
11
  return new Promise( (resolve, reject) => {
12
- this.db.set(k, "" + v) // saves as string, to simulate Redis
12
+ this.db.set(k, "" + v) // saves as string
13
13
  resolve();
14
14
  });
15
15
  }
16
16
 
17
- get(k) {
17
+ async incr(k) {
18
+ // console.log("incr...", k)
19
+ // return new Promise( (resolve, reject) => {
20
+ // console.log("Promise incr...", k)
21
+ let value = await this.get(k);
22
+ // console.log("value.............", value)
23
+ if (value == undefined || value == null) {
24
+ value = 0;
25
+ }
26
+ try {
27
+ value = Number(value);
28
+ }
29
+ catch(error) {
30
+ // console.error("Error on value = Number(value);", error);
31
+ value = 0
32
+ }
33
+ // console.log("got", k, value)
34
+ let v_incr = Number(value) + 1;
35
+ this.db.set(k, "" + v_incr) // saves as string
36
+ // resolve();
37
+
38
+ // });
39
+ }
40
+
41
+ async get(k) {
18
42
  return new Promise( (resolve, reject) => {
19
43
  const v = this.db.get(k);
20
44
  resolve(v);
@@ -19,7 +19,7 @@ class MongodbIntentsMachine {
19
19
  */
20
20
  async decode(botId, text) {
21
21
  return new Promise( (resolve, reject) => {
22
- if (this.log) {console.log("NLP decode intent...");}
22
+ if (this.log) {console.log("Mongodb NLP decode intent...");}
23
23
  let query = { "id_project": this.projectId, "id_faq_kb": botId };
24
24
  var mongoproject = undefined;
25
25
  var sort = undefined;
@@ -37,7 +37,7 @@ class MongodbIntentsMachine {
37
37
  if (err) {
38
38
  console.error("Error:", err);
39
39
  }
40
- if (faqs && faqs.length > 0 && faqs[0].answer) {
40
+ if (faqs && faqs.length > 0) {
41
41
  resolve(faqs);
42
42
  }
43
43
  else {
@@ -12,6 +12,8 @@ const { DirUnlockIntent } = require('../tiledeskChatbotPlugs/directives/DirUnloc
12
12
 
13
13
  class TiledeskChatbot {
14
14
 
15
+ static MAX_STEPS = 20;
16
+
15
17
  constructor(config) {
16
18
  if (!config.botsDataSource) {
17
19
  throw new Error("config.botsDataSource is mandatory");
@@ -61,6 +63,26 @@ class TiledeskChatbot {
61
63
  console.log("replyToMessage() > lead found:", JSON.stringify(lead));
62
64
  }
63
65
 
66
+ // any external invocation restarts the steps counter
67
+ if (message.sender != "_tdinternal") {
68
+ if (this.log) {
69
+ console.log("Resetting current step by request message:", message.text);
70
+ }
71
+ await TiledeskChatbot.resetStep(this.tdcache, this.requestId);
72
+ if (this.log) {
73
+ if (this.tdcache) {
74
+ let currentStep =
75
+ await TiledeskChatbot.currentStep(this.tdcache, this.requestId);
76
+ if (this.log) {console.log("after reset currentStep:", currentStep)}
77
+ }
78
+ }
79
+ }
80
+ // Emergency stop :)
81
+ // if (message.text === "/anomaly") {
82
+ // console.log(".................stop on /anomaly!");
83
+ // resolve(null);
84
+ // }
85
+
64
86
  // Checking locked intent (for non-internal intents)
65
87
  // internal intents always "skip" the locked intent
66
88
  // if (message.text.startsWith("/") && message.sender != "_tdinternal") {
@@ -125,6 +147,7 @@ class TiledeskChatbot {
125
147
  if (this.log) {console.log("Processing explicit intent:", explicit_intent_name)}
126
148
  // look for parameters
127
149
  const intent = TiledeskChatbotUtil.parseIntent(explicit_intent_name);
150
+ if (this.log) {console.log("parsed intent:", intent);}
128
151
  let reply;
129
152
  if (!intent || (intent && !intent.name)) {
130
153
  if (this.log) {console.log("Invalid intent:", explicit_intent_name);}
@@ -184,7 +207,7 @@ class TiledeskChatbot {
184
207
  return;
185
208
  }
186
209
  else { // NLP
187
- if (this.log) {console.log("NLP decode intent...");}
210
+ if (this.log) {console.log("Chatbot NLP decode intent...");}
188
211
  let intents;
189
212
  try {
190
213
  intents = await this.intentsFinder.decode(this.botId, message.text);
@@ -211,6 +234,7 @@ class TiledeskChatbot {
211
234
  // fallback
212
235
  let fallbackIntent = await this.botsDataSource.getByIntentDisplayName(this.botId, "defaultFallback");
213
236
  if (!fallbackIntent) {
237
+ console.log("No defaultFallback found!");
214
238
  resolve(null);
215
239
  return;
216
240
  }
@@ -449,6 +473,59 @@ class TiledeskChatbot {
449
473
  await _tdcache.hset(parameter_key, parameter_name, parameter_value);
450
474
  }
451
475
 
476
+ static async checkStep(_tdcache, requestId, max_steps) {
477
+ // console.log("CHECKING ON MAX_STEPS:", max_steps);
478
+ let go_on = true; // continue
479
+ const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":step";
480
+ // console.log("__parameter_key:", parameter_key);
481
+ await _tdcache.incr(parameter_key);
482
+ // console.log("incr-ed");
483
+ let _current_step = await _tdcache.get(parameter_key);
484
+ // if (!_current_step) { // this shouldn't be happening
485
+ // _current_step = 0;
486
+ // }
487
+ let current_step = Number(_current_step);
488
+ // current_step += 1;
489
+ // await _tdcache.set(parameter_key, current_step); // increment step
490
+ // console.log("CURRENT-STEP:", current_step);
491
+ if (current_step > max_steps) { // max_steps limit just violated
492
+ // console.log("CURRENT-STEP > MAX_STEPS!", current_step);
493
+ // await TiledeskChatbot.resetStep(_tdcache, requestId);
494
+ // go_on = 1; // stop execution, send error message
495
+ go_on = false
496
+ }
497
+ // else if (current_step > max_steps + 1) { // max_steps limit already violated
498
+ // console.log("CURRENT-STEP > MAX_STEPS!", current_step);
499
+ // // await TiledeskChatbot.resetStep(_tdcache, requestId);
500
+ // go_on = 2; // stop execution, don't send error message (already sent with go_on = 1)
501
+ // }
502
+ else {
503
+ // go_on = 0;
504
+ go_on = true;
505
+ }
506
+ // else {
507
+ // console.log("CURRENT-STEP UNDER MAX_STEPS THRESHOLD:)", current_step);
508
+ // current_step += 1;
509
+ // await _tdcache.set(parameter_key, current_step); // increment step
510
+ // console.log("current_step from cache:", await _tdcache.get(parameter_key));
511
+ // }
512
+ return go_on;
513
+ }
514
+
515
+ static async resetStep(_tdcache, requestId) {
516
+ const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":step";
517
+ // console.log("resetStep() parameter_key:", parameter_key);
518
+ if (_tdcache) {
519
+ await _tdcache.set(parameter_key, 0);
520
+ }
521
+ }
522
+
523
+ static async currentStep(_tdcache, requestId) {
524
+ const parameter_key = TiledeskChatbot.requestCacheKey(requestId) + ":step";
525
+ // console.log("currentStep() parameter_key:", parameter_key);
526
+ return await _tdcache.get(parameter_key);
527
+ }
528
+
452
529
  async allParameters() {
453
530
  return await TiledeskChatbot.allParametersStatic(this.tdcache, this.requestId);
454
531
  }
@@ -28,6 +28,22 @@ class TiledeskChatbotUtil {
28
28
  return intent;
29
29
 
30
30
  }
31
+
32
+ // static errorMessage(message) {
33
+ // return {
34
+ // name: "message",
35
+ // action: {
36
+ // "_tdThenStop": true,
37
+ // text: message,
38
+ // attributes: {
39
+ // runtimeError: {
40
+ // message: message
41
+ // }
42
+ // }
43
+ // }
44
+ // }
45
+ // }
46
+
31
47
  }
32
48
 
33
49
  module.exports = { TiledeskChatbotUtil };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiledesk/tiledesk-tybot-connector",
3
- "version": "0.1.47",
3
+ "version": "0.1.49",
4
4
  "description": "Tiledesk Tybot connector",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -14,7 +14,7 @@
14
14
  "@tiledesk/helpcenter-query-client": "^0.1.8",
15
15
  "@tiledesk/tiledesk-chatbot-client": "^0.5.30",
16
16
  "@tiledesk/tiledesk-chatbot-util": "^0.8.39",
17
- "@tiledesk/tiledesk-client": "^0.9.5",
17
+ "@tiledesk/tiledesk-client": "^0.9.6",
18
18
  "axios": "^0.27.2",
19
19
  "body-parser": "^1.19.0",
20
20
  "cors": "^2.8.5",
@@ -26,6 +26,7 @@
26
26
  "mongoose": "^6.3.5",
27
27
  "nanoid": "^3.1.25",
28
28
  "redis": "^3.1.2",
29
- "uuid": "^3.3.3"
29
+ "uuid": "^3.3.3",
30
+ "vm2": "^3.9.13"
30
31
  }
31
32
  }