@tiledesk/tiledesk-tybot-connector 2.5.0 → 2.6.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 (50) hide show
  1. package/CHANGELOG.md +1 -52
  2. package/ExtUtil.js +1 -0
  3. package/TdCache copy.js +242 -0
  4. package/TiledeskExpression.js +1 -6
  5. package/TiledeskWhenExpression.js +1 -18
  6. package/engine/MongodbBotsDataSource.js +1 -3
  7. package/engine/MongodbIntentsMachine.js +2 -3
  8. package/engine/TiledeskChatbot.js +4 -76
  9. package/engine/TiledeskChatbotConst.js +1 -7
  10. package/engine/mock/MockBotsDataSource.js +6 -11
  11. package/index.js +36 -132
  12. package/models/faq_kb.js +0 -11
  13. package/package.json +1 -1
  14. package/services/AIController.js +1 -31
  15. package/services/AIService.js +33 -62
  16. package/services/IntegrationService.js +1 -4
  17. package/services/{LLMService.js → KbService.js} +3 -3
  18. package/services/RequestService.js +2 -23
  19. package/services/TilebotService.js +3 -19
  20. package/tiledeskChatbotPlugs/DirectivesChatbotPlug.js +17 -34
  21. package/tiledeskChatbotPlugs/directives/DirAiCondition.js +51 -18
  22. package/tiledeskChatbotPlugs/directives/DirAiPrompt.js +52 -103
  23. package/tiledeskChatbotPlugs/directives/DirAskGPTV2.js +5 -108
  24. package/tiledeskChatbotPlugs/directives/DirCallSubagent.js +8 -34
  25. package/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js +11 -36
  26. package/tiledeskChatbotPlugs/directives/DirGptTask.js +4 -16
  27. package/tiledeskChatbotPlugs/directives/DirIntent.js +6 -12
  28. package/tiledeskChatbotPlugs/directives/DirIteration.js +10 -63
  29. package/tiledeskChatbotPlugs/directives/DirMoveToAgent.js +16 -69
  30. package/tiledeskChatbotPlugs/directives/DirRemoveCurrentBot.js +2 -40
  31. package/tiledeskChatbotPlugs/directives/DirReply.js +6 -81
  32. package/tiledeskChatbotPlugs/directives/DirReplyV2.js +4 -58
  33. package/tiledeskChatbotPlugs/directives/DirWebRequest.js +0 -8
  34. package/tiledeskChatbotPlugs/directives/DirWebRequestV2.js +1 -11
  35. package/tiledeskChatbotPlugs/directives/DirWebRequestV2_old.js +418 -0
  36. package/tiledeskChatbotPlugs/directives/DirWebResponse.js +2 -5
  37. package/tiledeskChatbotPlugs/directives/Directives.js +0 -6
  38. package/utils/HttpUtils.js +17 -99
  39. package/utils/TiledeskChatbotUtil.js +5 -73
  40. package/utils/winston.js +2 -80
  41. package/services/InternalSubAgentService.js +0 -330
  42. package/tiledeskChatbotPlugs/directives/DirInviteHuman.js +0 -259
  43. package/tiledeskChatbotPlugs/directives/DirInvokeSubAgent.js +0 -345
  44. package/tiledeskChatbotPlugs/directives/DirJSONConditionMulti.js +0 -171
  45. package/tiledeskChatbotPlugs/directives/DirRemoveHuman.js +0 -129
  46. package/tiledeskChatbotPlugs/directives/DirReturn.js +0 -98
  47. package/utils/ConnectorsV3.js +0 -292
  48. package/utils/LlmStream.js +0 -215
  49. package/utils/SentenceChunker.js +0 -94
  50. package/utils/StreamSender.js +0 -109
@@ -11,7 +11,7 @@ const { AnalyticsClient } = require('../../AnalyticsClient');
11
11
  const requestService = require('../../services/RequestService');
12
12
  const { pushCallerSnapshot } = require('../pushCallerSnapshot');
13
13
 
14
- class DirCallSubagent {
14
+ class DirCallSubAgent {
15
15
 
16
16
  constructor(context) {
17
17
  if (!context) {
@@ -33,7 +33,7 @@ class DirCallSubagent {
33
33
  }
34
34
  else {
35
35
  this.logger.error("Incorrect action for ", directive.name, directive)
36
- winston.warn("DirCallSubagent Incorrect directive: ", directive);
36
+ winston.warn("DirCallSubAgent Incorrect directive: ", directive);
37
37
  callback();
38
38
  return;
39
39
  }
@@ -44,7 +44,7 @@ class DirCallSubagent {
44
44
  }
45
45
 
46
46
  async go(action, callback) {
47
- winston.debug("(DirCallSubagent) Action: ", action);
47
+ winston.debug("(DirCallSubAgent) Action: ", action);
48
48
  let botId = action.botId;
49
49
  let botSlug = action.botSlug;
50
50
  let useSlug = action.useSlug;
@@ -72,7 +72,6 @@ class DirCallSubagent {
72
72
  blockName: blockName
73
73
  });
74
74
 
75
- console.log("Context token before replaceBot: ", this.context.token);
76
75
  try {
77
76
  const resbody = await requestService.replaceBot(this.context.projectId, this.requestId, data, this.context.token);
78
77
  if (this.context.chatbot?.bot.root_id) {
@@ -85,7 +84,7 @@ class DirCallSubagent {
85
84
  }
86
85
  } catch (error) {
87
86
  await subagentStack.pop(this.requestId);
88
- winston.error("(DirCallSubagent) error: ", error);
87
+ winston.error("(DirCallSubAgent) error: ", error);
89
88
  this.logger.error("(ReplaceBot) Invoke subagent error: ", error);
90
89
  if (callback) {
91
90
  callback(true);
@@ -94,6 +93,7 @@ class DirCallSubagent {
94
93
  }
95
94
 
96
95
  if (blockName) {
96
+ winston.debug("(DirCallSubAgent) Sending hidden /start message to bot in dept");
97
97
  const message = {
98
98
  type: "text",
99
99
  text: "/" + blockName,
@@ -101,46 +101,20 @@ class DirCallSubagent {
101
101
  subtype: "info"
102
102
  }
103
103
  }
104
- winston.info("(DirCallSubagent) sendSupportMessage request " + JSON.stringify({
105
- requestId: this.requestId,
106
- apiEndpoint: this.API_ENDPOINT,
107
- targetBotId: botId,
108
- text: message.text,
109
- subtype: message.attributes.subtype
110
- }));
111
- const started = Date.now();
112
104
  this.tdClient.sendSupportMessage(
113
105
  this.requestId,
114
- message, (err, result) => {
106
+ message, (err) => {
115
107
  if (err) {
116
- winston.error("(DirCallSubagent) sendSupportMessage failed " + JSON.stringify({
117
- requestId: this.requestId,
118
- text: message.text,
119
- duration_ms: Date.now() - started,
120
- message: err.message,
121
- status: err.response && err.response.status
122
- }));
123
- }
124
- else {
125
- winston.info("(DirCallSubagent) sendSupportMessage response " + JSON.stringify({
126
- requestId: this.requestId,
127
- text: message.text,
128
- duration_ms: Date.now() - started,
129
- messageId: result && (result._id || result.id)
130
- }));
108
+ winston.debug("(DirCallSubAgent) Error sending hidden message: " + err.message);
131
109
  }
132
110
  callback(true);
133
111
  });
134
112
  }
135
113
  else {
136
- winston.info("(DirCallSubagent) no blockName, skip hidden message " + JSON.stringify({
137
- requestId: this.requestId,
138
- targetBotId: botId
139
- }));
140
114
  callback();
141
115
  }
142
116
  }
143
117
 
144
118
  }
145
119
 
146
- module.exports = { DirCallSubagent };
120
+ module.exports = { DirCallSubAgent };
@@ -33,47 +33,22 @@ class DirCaptureUserReply {
33
33
  callback();
34
34
  return;
35
35
  }
36
- this.go(action, (stop) => {
37
- callback(stop);
36
+ this.go(action, () => {
37
+ callback();
38
38
  });
39
39
  }
40
40
 
41
- #resolveIntentLockKey() {
42
- const intent_info = this.reply?.attributes?.intent_info;
43
- if (intent_info?.intent_id) {
44
- return "#" + intent_info.intent_id;
45
- }
46
- if (intent_info?.intent_name) {
47
- return intent_info.intent_name;
48
- }
49
- if (this.reply?.intent_id) {
50
- return "#" + this.reply.intent_id;
51
- }
52
- if (this.reply?.intent_display_name) {
53
- return this.reply.intent_display_name;
54
- }
55
- return null;
56
- }
57
-
58
41
  async go(action, callback) {
59
42
  winston.debug("(DirCaptureUserReply) Action: ", action);
60
43
  const goToIntent = action.goToIntent;
61
- const lockedAction = await this.chatbot.currentLockedAction(this.requestId);
62
- // a lock only counts as "waiting for the reply" when this very action set it
63
- const own = lockedAction && lockedAction === action["_tdActionId"];
64
- if (!own) {
65
- const intent_name = this.#resolveIntentLockKey();
66
- const actionId = action["_tdActionId"];
67
- if (!intent_name) {
68
- this.logger.error("[Capture User Reply] Cannot lock intent: missing intent info");
69
- winston.error("(DirCaptureUserReply) Cannot lock intent: missing intent info");
70
- callback(true);
71
- return;
72
- }
44
+ let lockedAction = await this.chatbot.currentLockedAction(this.requestId);
45
+ if (!lockedAction) {
46
+ const intent_name = this.reply.attributes.intent_info.intent_name
47
+ const actionId = action["_tdActionId"];;
73
48
  await this.chatbot.lockIntent(this.requestId, intent_name);
74
49
  await this.chatbot.lockAction(this.requestId, actionId);
75
50
  this.logger.native("[Capture User Reply] Waiting for user reply...");
76
- callback(true);
51
+ callback();
77
52
  return;
78
53
  } else {
79
54
  try {
@@ -97,9 +72,9 @@ class DirCaptureUserReply {
97
72
 
98
73
  if (callback) {
99
74
  if (goToIntent) {
100
- this.#executeGoTo(goToIntent, (stop) => {
75
+ this.#executeGoTo(goToIntent, () => {
101
76
  this.logger.native("[Capture User Reply] Executed");
102
- callback(stop); // a jump ends this block
77
+ callback(); // continue the flow
103
78
  });
104
79
  }
105
80
  else {
@@ -120,8 +95,8 @@ class DirCaptureUserReply {
120
95
  if (intent) {
121
96
  goToIntentDirective = DirIntent.intentDirectiveFor(intent);
122
97
  }
123
- this.intentDir.execute(goToIntentDirective, (stop) => {
124
- callback(stop);
98
+ this.intentDir.execute(goToIntentDirective, () => {
99
+ callback();
125
100
  });
126
101
  }
127
102
 
@@ -203,26 +203,14 @@ class DirGptTask {
203
203
  HTTPREQUEST, async (err, resbody) => {
204
204
  if (err) {
205
205
  winston.debug("(DirGptTask) openai err: ", err);
206
- console.log("(DirGptTask) openai err.data: ", JSON.stringify(err.data));
207
206
  winston.debug("(DirGptTask) openai err: " + err.response?.data?.error?.message);
208
207
  this.logger.error("[ChatGPT Task] Completions error: ", err.response?.data?.error?.message);
209
208
  await this.#assignAttributes(action, answer);
210
- console.log("attributes assigned with answer: ", answer)
211
209
  if (falseIntent) {
212
- console.log("false intent");
213
- try {
214
- await this.chatbot.addParameter("flowError", "GPT Error: " + err.response?.data?.error?.message);
215
- console.log("addParamter ok")
216
- await this.#executeCondition(false, trueIntent, trueIntentAttributes, falseIntent, falseIntentAttributes);
217
- console.log("executeCondition ok")
218
- console.log("callback")
219
- callback(true);
220
- return;
221
- } catch (e) {
222
- console.error("error on false intent: ", e);
223
- callback(true);
224
- return;
225
- }
210
+ await this.chatbot.addParameter("flowError", "GPT Error: " + err.response?.data?.error?.message);
211
+ await this.#executeCondition(false, trueIntent, trueIntentAttributes, falseIntent, falseIntentAttributes);
212
+ callback(true);
213
+ return;
226
214
  }
227
215
  callback();
228
216
  return;
@@ -15,7 +15,6 @@ class DirIntent {
15
15
  this.TILEBOT_ENDPOINT = context.TILEBOT_ENDPOINT;
16
16
  this.supportRequest = context.supportRequest;
17
17
  this.token = context.token;
18
- this.message = context.message;
19
18
  }
20
19
 
21
20
  execute(directive, callback) {
@@ -66,25 +65,20 @@ class DirIntent {
66
65
  "request_id": requestId,
67
66
  "id_project": projectId,
68
67
  "draft": draft
69
- },
70
- "message": this.message
68
+ }
71
69
  },
72
70
  "token": this.token
73
71
  }
74
- if (this.context.turnId) {
75
- // keep the voice turn across the jump, so the next block can still be superseded
76
- intent_command_request.payload.voice_turn_id = this.context.turnId;
77
- }
78
72
  winston.debug("DirIntent move to intent message: ", intent_command_request);
79
73
 
80
- tilebotService.executeBlock(intent_command_request, botId, () => {
81
- callback(true);
82
- });
83
-
84
- // tilebotService.sendMessageToBot(intent_command_request, botId, () => {
74
+ // tilebotService.executeBlock(intent_command_request, botId, () => {
85
75
  // callback(true);
86
76
  // });
87
77
 
78
+ tilebotService.sendMessageToBot(intent_command_request, botId, () => {
79
+ callback(true);
80
+ });
81
+
88
82
  }
89
83
 
90
84
  static intentDirectiveFor(intent, json_params) {
@@ -2,7 +2,6 @@ const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
2
2
  const { DirIntent } = require('./DirIntent');
3
3
  const winston = require('../../utils/winston');
4
4
  const { Logger } = require('../../Logger');
5
- const { ConnectorsV3 } = require('../../utils/ConnectorsV3');
6
5
 
7
6
  class DirIteration {
8
7
  constructor(context) {
@@ -61,15 +60,6 @@ class DirIteration {
61
60
  }
62
61
  }
63
62
 
64
- // A state left behind by a loop that never finished (a branch that did not
65
- // lead back here) must not be resumed by a later, unrelated run of this
66
- // block: if the list is not the one the saved state was iterating, start over.
67
- if (iterationState && await this.#isStale(iterationState, action)) {
68
- this.logger.warn("[Iteration] Saved iteration state belongs to another list. Starting over.");
69
- await this.#clearIterationState(foundActionId);
70
- iterationState = null;
71
- }
72
-
73
63
  if (!iterationState) {
74
64
  // First call: initialize iteration state
75
65
  if (!actionId) {
@@ -95,7 +85,6 @@ class DirIteration {
95
85
 
96
86
  const iterable = action.iterable;
97
87
  const goToIntent = action.goToIntent;
98
- const fallbackIntent = action.fallbackIntent; // "when the list is done": il blocco da eseguire dopo l'ultimo elemento (o con una lista vuota)
99
88
  const output = action.assignOutputTo;
100
89
  const delay = 1000;
101
90
  //const delay = (action.delay || 30) * 1000; // s to ms
@@ -103,12 +92,10 @@ class DirIteration {
103
92
  // Get iterable value
104
93
  const iterableValue = await TiledeskChatbot.getParameterStatic(this.tdcache, this.requestId, iterable);
105
94
 
106
- // Nothing to iterate is a list that is already done: the flow goes on
107
- // from the block's exit instead of stopping the conversation in silence.
108
95
  if (!iterableValue) {
109
96
  winston.verbose("[Iteration] Iterable object is undefined");
110
- this.logger.warn("[Iteration] Iterable object is undefined. Nothing to iterate, going on.");
111
- callback(false);
97
+ this.logger.warn("[Iteration] Iterable object is undefined");
98
+ callback(true);
112
99
  return;
113
100
  }
114
101
 
@@ -117,15 +104,15 @@ class DirIteration {
117
104
 
118
105
  if (!iterableArray) {
119
106
  winston.verbose("[Iteration] Could not convert iterable to array");
120
- this.logger.error(`[Iteration] Could not convert iterable '${iterable}' to array | type: ${typeof iterableValue}. Going on.`);
121
- callback(false);
107
+ this.logger.error(`[Iteration] Could not convert iterable '${iterable}' to array | type: ${typeof iterableValue}`);
108
+ callback(true);
122
109
  return;
123
110
  }
124
111
 
125
112
  if (iterableArray.length === 0) {
126
113
  winston.verbose("[Iteration] Iterable array is empty. Exit...")
127
- this.logger.warn("[Iteration] Iterable array is empty. Going on.")
128
- this.#whenDone(fallbackIntent, false, callback);
114
+ this.logger.warn("[Iteration] Iterable array is empty. Exit...")
115
+ callback(true);
129
116
  return;
130
117
  }
131
118
 
@@ -134,7 +121,6 @@ class DirIteration {
134
121
  currentIndex: 0,
135
122
  iterableArray: iterableArray,
136
123
  goToIntent: goToIntent,
137
- fallbackIntent: fallbackIntent,
138
124
  output: output,
139
125
  delay: delay,
140
126
  totalItems: iterableArray.length
@@ -157,7 +143,7 @@ class DirIteration {
157
143
  if (iterationState.currentIndex >= iterationState.totalItems) {
158
144
  this.logger.native("[Iteration] Iteration completed");
159
145
  await this.#clearIterationState(actionId);
160
- this.#whenDone(iterationState.fallbackIntent, false, callback);
146
+ callback(false);
161
147
  return;
162
148
  }
163
149
 
@@ -168,24 +154,6 @@ class DirIteration {
168
154
  await this.#processCurrentItem(iterationState, actionId, iterationState.goToIntent, iterationState.output, callback);
169
155
  }
170
156
 
171
- /**
172
- * La lista e' finita (ultimo elemento gia' passato, o lista vuota). Per un agente V3 con un
173
- * blocco "when the list is done" (`fallbackIntent`, dal 14/10/2026) lo esegue e ferma il flusso,
174
- * come fa `goToIntent` per ogni elemento. Per gli agenti precedenti il campo resta ignorato come
175
- * e' sempre stato (nessun cambiamento di comportamento): il flusso fa quello che ha sempre fatto
176
- * (`stopWithoutFallback`).
177
- */
178
- #whenDone(fallbackIntent, stopWithoutFallback, callback) {
179
- if (!fallbackIntent || !ConnectorsV3.isV3Bot(this.chatbot && this.chatbot.bot)) {
180
- callback(stopWithoutFallback);
181
- return;
182
- }
183
- this.logger.native("[Iteration] List done: executing fallbackIntent");
184
- this.#executeIntent(fallbackIntent, () => {
185
- callback(true);
186
- });
187
- }
188
-
189
157
  async #processCurrentItem(iterationState, actionId, goToIntent, output, callback) {
190
158
  try {
191
159
  const currentItem = iterationState.iterableArray[iterationState.currentIndex];
@@ -218,10 +186,9 @@ class DirIteration {
218
186
  } catch (error) {
219
187
  this.logger.error("[Iteration] Error processing current item: ", error);
220
188
  winston.error("[Iteration] Error processing current item: ", error);
221
- // Clear state on error to prevent stuck iterations, and leave the loop
222
- // through the block's exit rather than stopping the conversation.
189
+ // Clear state on error to prevent stuck iterations
223
190
  await this.#clearIterationState(actionId);
224
- callback(false);
191
+ callback(true);
225
192
  }
226
193
  }
227
194
 
@@ -242,27 +209,7 @@ class DirIteration {
242
209
  // Clear state and complete
243
210
  await this.#clearIterationState(actionId);
244
211
  this.logger.native("[Iteration] Iteration completed (no intent mode)");
245
- callback(false);
246
- }
247
-
248
- /**
249
- * True when the saved state was iterating a different list from the one the
250
- * action's iterable holds now. While a loop runs, its branch leads back here
251
- * with the same list; a different list means the block was reached again by
252
- * a new run (a new message, a new email) after a loop that never finished.
253
- */
254
- async #isStale(iterationState, action) {
255
- if (!action || !action.iterable) {
256
- return false;
257
- }
258
- try {
259
- const currentValue = await TiledeskChatbot.getParameterStatic(this.tdcache, this.requestId, action.iterable);
260
- const currentArray = currentValue ? this.#normalizeToArray(currentValue, action.iterable) : [];
261
- return JSON.stringify(currentArray || []) !== JSON.stringify(iterationState.iterableArray || []);
262
- } catch (error) {
263
- winston.error("[Iteration] Error checking iteration state: ", error);
264
- return false;
265
- }
212
+ callback(true);
266
213
  }
267
214
 
268
215
  async #getIterationState(actionId) {
@@ -23,8 +23,8 @@ class DirMoveToAgent {
23
23
 
24
24
  execute(directive, callback) {
25
25
  winston.verbose("Execute MoveToAgent directive");
26
- const action = directive.action || {};
27
- this.go(action, () => {
26
+ directive.action = {};
27
+ this.go(directive.action, () => {
28
28
  this.logger.native("[Transfer to a Human] Executed");
29
29
  callback();
30
30
  });
@@ -33,77 +33,24 @@ class DirMoveToAgent {
33
33
  async go(action, callback) {
34
34
  this.tdClient.moveToAgent(this.requestId, (err) => {
35
35
  if (err) {
36
- winston.error("(DirMoveToAgent) Error moving to agent: ", err);
37
- callback();
38
- return;
39
- }
40
-
41
- const depName = action.depName;
42
- if (depName) {
43
- this.moveToDepartment(this.requestId, depName, (err, deps) => {
44
- if (err) {
45
- winston.error("(DirMoveToAgent) Error moving to department: ", err);
46
- }
47
- else {
48
- this.logger.native("[Move to Department] Moved to department: ", depName);
49
- winston.debug("(DirMoveToAgent) Moved to department: ", deps);
50
- }
51
- callback();
52
- });
36
+ winston.error("DirMoveToAgent) Error moving to agent: ", err);
53
37
  }
54
38
  else {
55
- callback();
56
- }
57
-
58
- // Successfully moved to agent. Only track published (production) runs
59
- // (root/draft copy has no root_id).
60
- if (this.context.chatbot?.bot.root_id) {
61
- AnalyticsClient.track('handover_to_human', this.context.projectId, {
62
- id_request: this.requestId,
63
- human_id: null,
64
- reason: 'bot_directive',
65
- department_id: this.context.departmentId || null,
66
- waiting_time_seconds: null,
67
- agent_id: this.context.chatbot?.bot.root_id,
68
- trigger_intent: this.context.reply?.attributes?.intent_info?.intent_name || null
69
- });
70
- }
71
-
72
- });
73
- }
74
-
75
- async moveToDepartment(requestId, depName, callback) {
76
- this.tdClient.getAllDepartments((err, deps) => {
77
- winston.debug("(DirMoveToAgent) deps: ", deps);
78
- if (err) {
79
- winston.error("(DirMoveToAgent) getAllDepartments() error: ", err);
80
- callback(err);
81
- return;
82
- }
83
- let dep = null;
84
- let i;
85
- for (i = 0; i < deps.length; i++) {
86
- let d = deps[i];
87
- if (d.name.toLowerCase() === depName.toLowerCase()) {
88
- dep = d;
89
- break;
39
+ // Successfully moved to agent. Only track published (production) runs
40
+ // (root/draft copy has no root_id).
41
+ if (this.context.chatbot?.bot.root_id) {
42
+ AnalyticsClient.track('handover_to_human', this.context.projectId, {
43
+ id_request: this.requestId,
44
+ human_id: null,
45
+ reason: 'bot_directive',
46
+ department_id: this.context.departmentId || null,
47
+ waiting_time_seconds: null,
48
+ agent_id: this.context.chatbot?.bot.root_id,
49
+ trigger_intent: this.context.reply?.attributes?.intent_info?.intent_name || null
50
+ });
90
51
  }
91
52
  }
92
- if (dep) {
93
- this.tdClient.updateRequestDepartment(requestId, dep._id, null, (err, res) => {
94
- if (err) {
95
- winston.error("(DirMoveToAgent) updatedRequestDepartment error: ", err);
96
- callback(err);
97
- }
98
- else {
99
- winston.debug("(DirMoveToAgent) response: ", res);
100
- callback(null, deps);
101
- }
102
- });
103
- }
104
- else {
105
- callback(null, null);
106
- }
53
+ callback();
107
54
  });
108
55
  }
109
56
 
@@ -1,6 +1,5 @@
1
1
  const { TiledeskClient } = require("@tiledesk/tiledesk-client");
2
2
  const winston = require('../../utils/winston');
3
- const HttpUtils = require('../../utils/HttpUtils').constructor;
4
3
 
5
4
  class DirRemoveCurrentBot {
6
5
 
@@ -28,7 +27,6 @@ class DirRemoveCurrentBot {
28
27
  else {
29
28
  winston.warn("DirRemoveCurrentBot Incorrect directive: ", directive);
30
29
  callback();
31
- return;
32
30
  }
33
31
  this.go(action, () => {
34
32
  callback();
@@ -37,46 +35,10 @@ class DirRemoveCurrentBot {
37
35
 
38
36
  go(action, callback) {
39
37
  winston.debug("(RemoveCurrentBot) Action: ", action);
40
- let done = false;
41
- const finish = () => {
42
- if (done) return;
43
- done = true;
38
+ this.tdClient.removeCurrentBot(this.requestId, (err) => {
44
39
  callback();
45
- };
46
- const fail = (step, err) => {
47
- winston.error("(RemoveCurrentBot) " + step + " error: ", HttpUtils.errorSummary(err));
48
- finish();
49
- };
50
- const requestId = this.requestId;
51
- this.tdClient.getRequestById(requestId, (err, request) => {
52
- if (err) {
53
- return fail("getRequestById", err);
54
- }
55
- const bots = request && request.participantsBots;
56
- if (!bots || bots.length === 0) {
57
- return finish();
58
- }
59
- const botParticipant = this.tdClient.normalizeBotId(bots[0]);
60
- const participants = Array.isArray(request.participants) ? request.participants : [];
61
- // Any participant besides the removed bot (human or another bot) keeps the
62
- // conversation ASSIGNED (the server already handles the status): don't touch it.
63
- const botOnly = !participants.some((p) => p !== botParticipant);
64
- this.tdClient.deleteRequestParticipant(requestId, botParticipant, (err) => {
65
- if (err) {
66
- return fail("deleteRequestParticipant", err);
67
- }
68
- if (!botOnly) {
69
- return finish();
70
- }
71
- this.tdClient.updateRequestProperties(requestId, { status: 50 }, (err) => {
72
- if (err) {
73
- return fail("updateRequestProperties", err);
74
- }
75
- finish();
76
- });
77
- });
78
40
  });
79
41
  }
80
42
  }
81
43
 
82
- module.exports = { DirRemoveCurrentBot };
44
+ module.exports = { DirRemoveCurrentBot };