@tiledesk/tiledesk-tybot-connector 3.0.0 → 3.0.2
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.
- package/TiledeskExpression.js +3 -1
- package/engine/TiledeskChatbot.js +23 -1
- package/index.js +5 -2
- package/logs/app1.log +6267 -0
- package/package.json +22 -21
- package/tiledeskChatbotPlugs/DirectivesChatbotPlug.js +8 -2
- package/tiledeskChatbotPlugs/directives/DirAiCondition.js +14 -10
- package/tiledeskChatbotPlugs/directives/DirAiPrompt.js +5 -5
- package/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js +36 -11
- package/tiledeskChatbotPlugs/directives/DirDocparseExtract.js +166 -48
- package/tiledeskChatbotPlugs/directives/DirInviteHuman.js +259 -0
- package/tiledeskChatbotPlugs/directives/DirIteration.js +3 -3
- package/tiledeskChatbotPlugs/directives/DirJSONConditionMulti.js +171 -0
- package/tiledeskChatbotPlugs/directives/DirRemoveCurrentBot.js +40 -2
- package/tiledeskChatbotPlugs/directives/DirRemoveHuman.js +129 -0
- package/tiledeskChatbotPlugs/directives/DirReplyV2.js +18 -3
- package/tiledeskChatbotPlugs/directives/Directives.js +3 -0
- package/utils/ConnectorsV3.js +3 -0
- package/utils/HttpUtils.js +15 -11
- package/utils/TiledeskChatbotUtil.js +4 -1
- package/utils/winston.js +80 -2
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
const { DirIntent } = require('./DirIntent');
|
|
2
|
+
const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
|
|
3
|
+
const { Filler } = require('../Filler');
|
|
4
|
+
const httpUtils = require('../../utils/HttpUtils');
|
|
5
|
+
const winston = require('../../utils/winston');
|
|
6
|
+
const { Logger } = require('../../Logger');
|
|
7
|
+
|
|
8
|
+
const SEPARATORS = /[,;\n]/;
|
|
9
|
+
const SINGLE_PLACEHOLDER = /^\{\{\s*([\w.]+)\s*\}\}$/;
|
|
10
|
+
const AUTOMATION_PREFIX = 'automation-request-';
|
|
11
|
+
|
|
12
|
+
class DirInviteHuman {
|
|
13
|
+
|
|
14
|
+
static INVITE_TIMEOUT_MS = 30000;
|
|
15
|
+
static AUTOMATION_PREFIX = AUTOMATION_PREFIX;
|
|
16
|
+
|
|
17
|
+
constructor(context) {
|
|
18
|
+
if (!context) {
|
|
19
|
+
throw new Error('context object is mandatory.');
|
|
20
|
+
}
|
|
21
|
+
this.context = context;
|
|
22
|
+
this.chatbot = context.chatbot;
|
|
23
|
+
this.requestId = context.requestId;
|
|
24
|
+
this.projectId = context.projectId;
|
|
25
|
+
this.token = context.token;
|
|
26
|
+
this.tdcache = context.tdcache;
|
|
27
|
+
this.API_ENDPOINT = context.API_ENDPOINT;
|
|
28
|
+
this.intentDir = new DirIntent(context);
|
|
29
|
+
this.logger = new Logger({ request_id: this.requestId, dev: this.context.supportRequest?.draft, intent_id: this.context.reply?.intent_id || this.context.reply?.attributes?.intent_info?.intent_id });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
execute(directive, callback) {
|
|
33
|
+
winston.verbose("Execute InviteHuman directive");
|
|
34
|
+
let called = false;
|
|
35
|
+
const safeCallback = (stop) => {
|
|
36
|
+
if (called) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
called = true;
|
|
40
|
+
callback(stop);
|
|
41
|
+
};
|
|
42
|
+
if (!directive || !directive.action) {
|
|
43
|
+
this.logger.error("[Invite Human] Incorrect action for ", directive?.name, directive);
|
|
44
|
+
winston.warn("(DirInviteHuman) Incorrect directive: ", directive);
|
|
45
|
+
safeCallback();
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
this.go(directive.action, (stop) => {
|
|
49
|
+
safeCallback(stop);
|
|
50
|
+
}).catch((err) => {
|
|
51
|
+
winston.error("(DirInviteHuman) unexpected error: " + JSON.stringify(DirInviteHuman.errorSummary(err)));
|
|
52
|
+
safeCallback();
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async go(action, callback) {
|
|
57
|
+
const trueIntent = action.trueIntent;
|
|
58
|
+
const falseIntent = action.falseIntent;
|
|
59
|
+
|
|
60
|
+
if (!trueIntent && !falseIntent) {
|
|
61
|
+
this.logger.error("[Invite Human] missing both action.trueIntent & action.falseIntent");
|
|
62
|
+
winston.error("(DirInviteHuman) missing both action.trueIntent & action.falseIntent");
|
|
63
|
+
callback();
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (this.requestId && this.requestId.startsWith(AUTOMATION_PREFIX)) {
|
|
68
|
+
this.logger.error("[Invite Human] requires a conversation");
|
|
69
|
+
await this.setParameter("flowError", "(Invite human) requires a conversation");
|
|
70
|
+
this.jump(falseIntent, action.falseIntentAttributes, callback);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
let members;
|
|
75
|
+
try {
|
|
76
|
+
const variables = this.tdcache ? await TiledeskChatbot.allParametersStatic(this.tdcache, this.requestId) : {};
|
|
77
|
+
members = DirInviteHuman.resolveMembers(action.members, variables, new Filler());
|
|
78
|
+
} catch (err) {
|
|
79
|
+
const summary = DirInviteHuman.errorSummary(err);
|
|
80
|
+
this.logger.error("[Invite Human] Error resolving members: " + summary.message);
|
|
81
|
+
winston.error("(DirInviteHuman) error resolving members: " + JSON.stringify(summary));
|
|
82
|
+
await this.setParameter("flowError", "(Invite human) An error occurred: " + summary.message);
|
|
83
|
+
this.jump(falseIntent, action.falseIntentAttributes, callback);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
let result;
|
|
88
|
+
try {
|
|
89
|
+
const inviteBody = { department_id: action.departmentId || undefined, members: members };
|
|
90
|
+
if (falseIntent && typeof falseIntent === 'string' && falseIntent.length > 0) {
|
|
91
|
+
inviteBody.fallback_intent = falseIntent;
|
|
92
|
+
}
|
|
93
|
+
result = await this.invite(inviteBody);
|
|
94
|
+
} catch (err) {
|
|
95
|
+
const summary = DirInviteHuman.errorSummary(err);
|
|
96
|
+
this.logger.error("[Invite Human] Error: " + summary.message);
|
|
97
|
+
winston.error("(DirInviteHuman) invite error: " + JSON.stringify(summary));
|
|
98
|
+
await this.setParameter("flowError", "(Invite human) An error occurred: " + summary.message);
|
|
99
|
+
this.jump(falseIntent, action.falseIntentAttributes, callback);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const invited = (result && Array.isArray(result.invited)) ? result.invited : [];
|
|
104
|
+
await this.setParameter("invited_humans", invited);
|
|
105
|
+
await this.setParameter("invited_humans_count", invited.length);
|
|
106
|
+
|
|
107
|
+
if (invited.length > 0) {
|
|
108
|
+
this.logger.native("[Invite Human] Invited: " + invited.map((i) => i.fullname || i.id_user).join(', '));
|
|
109
|
+
this.jump(trueIntent, action.trueIntentAttributes, callback);
|
|
110
|
+
} else {
|
|
111
|
+
this.logger.native("[Invite Human] No human available");
|
|
112
|
+
this.jump(falseIntent, action.falseIntentAttributes, callback);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
jump(intent, attributes, callback) {
|
|
117
|
+
if (!intent) {
|
|
118
|
+
callback();
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const intentDirective = DirIntent.intentDirectiveFor(intent, attributes);
|
|
122
|
+
this.intentDir.execute(intentDirective, () => {
|
|
123
|
+
callback(true);
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async setParameter(name, value) {
|
|
128
|
+
try {
|
|
129
|
+
if (this.chatbot) {
|
|
130
|
+
await this.chatbot.addParameter(name, value);
|
|
131
|
+
} else if (this.tdcache) {
|
|
132
|
+
await TiledeskChatbot.addParameterStatic(this.tdcache, this.requestId, name, value);
|
|
133
|
+
}
|
|
134
|
+
} catch (err) {
|
|
135
|
+
winston.error("(DirInviteHuman) error setting parameter " + name + ": " + JSON.stringify(DirInviteHuman.errorSummary(err)));
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
invite(body) {
|
|
140
|
+
return new Promise((resolve, reject) => {
|
|
141
|
+
const HTTPREQUEST = {
|
|
142
|
+
url: `${this.API_ENDPOINT}/${this.projectId}/requests/${this.requestId}/participants/invite`,
|
|
143
|
+
headers: {
|
|
144
|
+
'Content-Type': 'application/json',
|
|
145
|
+
'Authorization': DirInviteHuman.fixToken(this.token)
|
|
146
|
+
},
|
|
147
|
+
json: body,
|
|
148
|
+
method: 'POST',
|
|
149
|
+
timeout: DirInviteHuman.INVITE_TIMEOUT_MS
|
|
150
|
+
};
|
|
151
|
+
httpUtils.request(HTTPREQUEST, (err, resbody) => {
|
|
152
|
+
if (err) {
|
|
153
|
+
reject(err);
|
|
154
|
+
} else {
|
|
155
|
+
resolve(resbody);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Resolves the "members" field of the action into a list of ids/emails.
|
|
163
|
+
* A token that is exactly one {{variable}} is replaced by the raw variable value
|
|
164
|
+
* (arrays are expanded); other tokens containing {{...}} are rendered with the Filler.
|
|
165
|
+
*/
|
|
166
|
+
static resolveMembers(rawMembers, variables, filler) {
|
|
167
|
+
const vars = variables || {};
|
|
168
|
+
const result = [];
|
|
169
|
+
|
|
170
|
+
const push = (value) => {
|
|
171
|
+
if (value === undefined || value === null) {
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (Array.isArray(value)) {
|
|
175
|
+
value.forEach(push);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (typeof value === 'string') {
|
|
179
|
+
const trimmed = value.trim();
|
|
180
|
+
if (trimmed.startsWith('[')) {
|
|
181
|
+
try {
|
|
182
|
+
const parsed = JSON.parse(trimmed);
|
|
183
|
+
if (Array.isArray(parsed)) {
|
|
184
|
+
parsed.forEach(push);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
} catch (err) {
|
|
188
|
+
// not a JSON array: treat as plain text
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
trimmed.split(SEPARATORS).map((s) => s.trim()).filter((s) => s.length > 0).forEach((s) => {
|
|
192
|
+
if (!result.includes(s)) {
|
|
193
|
+
result.push(s);
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
push(String(value));
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
if (rawMembers === undefined || rawMembers === null) {
|
|
202
|
+
return result;
|
|
203
|
+
}
|
|
204
|
+
const tokens = Array.isArray(rawMembers) ? rawMembers : String(rawMembers).split(SEPARATORS);
|
|
205
|
+
for (const token of tokens) {
|
|
206
|
+
if (typeof token !== 'string') {
|
|
207
|
+
push(token);
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const trimmed = token.trim();
|
|
211
|
+
if (!trimmed) {
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
const placeholder = trimmed.match(SINGLE_PLACEHOLDER);
|
|
215
|
+
if (placeholder) {
|
|
216
|
+
push(DirInviteHuman.lookup(vars, placeholder[1]));
|
|
217
|
+
} else if (trimmed.includes('{{') && filler) {
|
|
218
|
+
push(filler.fill(trimmed, Object.assign({}, vars)));
|
|
219
|
+
} else {
|
|
220
|
+
push(trimmed);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return result;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
static lookup(variables, path) {
|
|
227
|
+
return path.split('.').reduce((obj, key) => (obj !== undefined && obj !== null ? obj[key] : undefined), variables);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
static fixToken(token) {
|
|
231
|
+
if (!token) {
|
|
232
|
+
return token;
|
|
233
|
+
}
|
|
234
|
+
return token.startsWith('JWT ') ? token : 'JWT ' + token;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Reduces an axios-like error to a plain, log-safe summary.
|
|
239
|
+
* Never reads err.config, err.request or headers (they may carry the bot JWT).
|
|
240
|
+
*/
|
|
241
|
+
static errorSummary(err) {
|
|
242
|
+
const responseData = (err && err.response) ? err.response.data : undefined;
|
|
243
|
+
let message;
|
|
244
|
+
if (responseData && typeof responseData.error === 'string' && responseData.error.length > 0) {
|
|
245
|
+
message = responseData.error;
|
|
246
|
+
} else if (err && err.message) {
|
|
247
|
+
message = err.message;
|
|
248
|
+
} else {
|
|
249
|
+
message = String(err);
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
message: message,
|
|
253
|
+
status: (err && err.response) ? err.response.status : undefined,
|
|
254
|
+
data: responseData
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
module.exports = { DirInviteHuman };
|
|
@@ -123,9 +123,9 @@ class DirIteration {
|
|
|
123
123
|
}
|
|
124
124
|
|
|
125
125
|
if (iterableArray.length === 0) {
|
|
126
|
-
winston.verbose("[Iteration] Iterable array is empty.
|
|
127
|
-
this.logger.warn("[Iteration] Iterable array is empty.
|
|
128
|
-
this.#whenDone(fallbackIntent,
|
|
126
|
+
winston.verbose("[Iteration] Iterable array is empty. Nothing to iterate, going on.")
|
|
127
|
+
this.logger.warn("[Iteration] Iterable array is empty. Nothing to iterate, going on.")
|
|
128
|
+
this.#whenDone(fallbackIntent, false, callback);
|
|
129
129
|
return;
|
|
130
130
|
}
|
|
131
131
|
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
const { DirIntent } = require('./DirIntent');
|
|
2
|
+
const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
|
|
3
|
+
const { TiledeskWhenExpression } = require('../../TiledeskWhenExpression');
|
|
4
|
+
const winston = require('../../utils/winston');
|
|
5
|
+
const { Logger } = require('../../Logger');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* DirJSONConditionMulti
|
|
9
|
+
*
|
|
10
|
+
* Multi-branch condition: N cases evaluated IN ORDER, each with its own exit.
|
|
11
|
+
* The first case whose `when` is true routes the flow to its own block and the
|
|
12
|
+
* action stops there; the remaining cases are never evaluated. When no case
|
|
13
|
+
* matches, the flow leaves through `elseIntent`.
|
|
14
|
+
*
|
|
15
|
+
* It replaces the chain of single conditions (each one's false branch feeding
|
|
16
|
+
* the next) with one block that has one exit per case.
|
|
17
|
+
*
|
|
18
|
+
* Rules (see design-studio docs/V3/multi-conditions-piano.md):
|
|
19
|
+
* 1. cases are evaluated in order; the first true one wins and stops the chain;
|
|
20
|
+
* 2. a case with no `when` (or an empty one) is SKIPPED, never taken as true —
|
|
21
|
+
* an empty case at the top would otherwise swallow all the traffic;
|
|
22
|
+
* 3. an evaluation error on a case counts as "no match": `flowError` is set and
|
|
23
|
+
* the next case is tried, so one broken case does not shadow the sound ones
|
|
24
|
+
* that follow it;
|
|
25
|
+
* 4. a case that matches but has no target block advances to the next action,
|
|
26
|
+
* exactly as DirJSONConditionV2 does with an unset trueIntent;
|
|
27
|
+
* 5. no case matched -> `elseIntent`; unset, the next action runs;
|
|
28
|
+
* 6. nothing usable at all -> a warning, and the chain advances.
|
|
29
|
+
*
|
|
30
|
+
* There is no legacy delegation here (unlike DirJSONConditionV2): this action
|
|
31
|
+
* type is new, so no bot can carry an older shape of it.
|
|
32
|
+
*
|
|
33
|
+
* The callback contract matches the dispatcher (DirectivesChatbotPlug): the
|
|
34
|
+
* callback is invoked with `stop` (truthy halts the directive chain) and is
|
|
35
|
+
* guaranteed to be called EXACTLY ONCE on every path, including errors.
|
|
36
|
+
*/
|
|
37
|
+
class DirJSONConditionMulti {
|
|
38
|
+
|
|
39
|
+
constructor(context) {
|
|
40
|
+
if (!context) {
|
|
41
|
+
throw new Error('context object is mandatory.');
|
|
42
|
+
}
|
|
43
|
+
this.context = context;
|
|
44
|
+
this.chatbot = context.chatbot;
|
|
45
|
+
this.requestId = this.context.requestId;
|
|
46
|
+
|
|
47
|
+
this.intentDir = new DirIntent(context);
|
|
48
|
+
this.logger = new Logger({ request_id: this.requestId, dev: this.context.supportRequest?.draft, intent_id: this.context.reply?.intent_id || this.context.reply?.attributes?.intent_info?.intent_id });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
execute(directive, callback) {
|
|
52
|
+
winston.verbose("Execute JSONConditionMulti directive");
|
|
53
|
+
let action;
|
|
54
|
+
if (directive.action) {
|
|
55
|
+
action = directive.action;
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
this.logger.error("Incorrect action for ", directive.name, directive);
|
|
59
|
+
winston.warn("DirJSONConditionMulti Incorrect directive: ", directive);
|
|
60
|
+
callback();
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
this.go(action, (stop) => {
|
|
65
|
+
this.logger.native("[ConditionMulti] Executed");
|
|
66
|
+
callback(stop);
|
|
67
|
+
}).catch((err) => {
|
|
68
|
+
// Last-resort net: never leave the directive chain hanging.
|
|
69
|
+
winston.error("(DirJSONConditionMulti) Unhandled error in go(): " + (err && err.message));
|
|
70
|
+
callback();
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async go(action, callback) {
|
|
75
|
+
// Guarantee the callback fires exactly once, regardless of which branch/throw occurs.
|
|
76
|
+
let finished = false;
|
|
77
|
+
const done = (stop) => {
|
|
78
|
+
if (finished) return;
|
|
79
|
+
finished = true;
|
|
80
|
+
callback(stop);
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
try {
|
|
84
|
+
const cases = Array.isArray(action.cases) ? action.cases : [];
|
|
85
|
+
const elseIntent = this.#cleanIntent(action.elseIntent);
|
|
86
|
+
const elseIntentAttributes = action.elseIntentAttributes;
|
|
87
|
+
// Same decision as V2: a matched case always stops the chain.
|
|
88
|
+
const stopOnConditionMet = true;
|
|
89
|
+
|
|
90
|
+
const evaluable = cases.filter((c) => c && typeof c.when === 'string' && c.when.trim() !== "");
|
|
91
|
+
if (evaluable.length === 0 && !elseIntent) {
|
|
92
|
+
this.logger.warn("[ConditionMulti] Invalid action: no evaluable case and no elseIntent");
|
|
93
|
+
winston.warn("(DirJSONConditionMulti) No evaluable case and no elseIntent");
|
|
94
|
+
done();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (evaluable.length !== cases.length) {
|
|
98
|
+
// Rule 2. Worth saying out loud: an unfinished case in the editor is a branch
|
|
99
|
+
// of the flow that silently never fires.
|
|
100
|
+
winston.verbose("(DirJSONConditionMulti) " + (cases.length - evaluable.length) + " case(s) without a condition were skipped");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Load conversation variables (native-typed) from cache, once for every case.
|
|
104
|
+
let variables = {};
|
|
105
|
+
if (this.context.tdcache) {
|
|
106
|
+
variables = await TiledeskChatbot.allParametersStatic(this.context.tdcache, this.context.requestId) || {};
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
winston.error("(DirJSONConditionMulti) No this.context.tdcache — evaluating with empty variables");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const expression = new TiledeskWhenExpression();
|
|
113
|
+
for (let i = 0; i < evaluable.length; i++) {
|
|
114
|
+
const branch = evaluable[i];
|
|
115
|
+
const label = branch.label || branch._tdCaseId || ('#' + (i + 1));
|
|
116
|
+
let result;
|
|
117
|
+
try {
|
|
118
|
+
const value = expression.evaluate(branch.when, variables);
|
|
119
|
+
result = (value === null || value === undefined) ? false : Boolean(value);
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
// Rule 3: a broken case is not a match, and it does not shadow the ones below it.
|
|
123
|
+
winston.error("(DirJSONConditionMulti) Error evaluating case '" + label + "': " + (err && err.message));
|
|
124
|
+
this.logger.error("[ConditionMulti] An error occurred evaluating case '" + label + "'");
|
|
125
|
+
if (this.context.tdcache) {
|
|
126
|
+
await TiledeskChatbot.addParameterStatic(this.context.tdcache, this.context.requestId, "flowError", "An error occurred evaluating condition '" + label + "' (when)");
|
|
127
|
+
}
|
|
128
|
+
result = false;
|
|
129
|
+
}
|
|
130
|
+
winston.debug("(DirJSONConditionMulti) case '" + label + "' -> " + result);
|
|
131
|
+
if (!result) continue;
|
|
132
|
+
|
|
133
|
+
this.logger.native("[ConditionMulti] Case '" + label + "' matched");
|
|
134
|
+
const intent = this.#cleanIntent(branch.intent);
|
|
135
|
+
if (!intent) {
|
|
136
|
+
// Rule 4: the switch is decided, but there is nowhere to go.
|
|
137
|
+
this.logger.native("[ConditionMulti] Case '" + label + "' has no target block");
|
|
138
|
+
winston.warn("(DirJSONConditionMulti) Matched case '" + label + "' has no intent");
|
|
139
|
+
done();
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
this.intentDir.execute(DirIntent.intentDirectiveFor(intent, branch.intentAttributes), () => done(stopOnConditionMet));
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Rule 5: nothing matched.
|
|
147
|
+
this.logger.native("[ConditionMulti] No case matched");
|
|
148
|
+
if (elseIntent) {
|
|
149
|
+
this.intentDir.execute(DirIntent.intentDirectiveFor(elseIntent, elseIntentAttributes), () => done(stopOnConditionMet));
|
|
150
|
+
}
|
|
151
|
+
else {
|
|
152
|
+
this.logger.native("[ConditionMulti] No elseIntent specified");
|
|
153
|
+
done();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
winston.error("(DirJSONConditionMulti) Unexpected error in go(): " + (err && err.message));
|
|
158
|
+
done(); // advance the chain rather than hang
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** An intent that is missing, or blank, is an unconnected exit — not a target. */
|
|
163
|
+
#cleanIntent(intent) {
|
|
164
|
+
if (typeof intent !== 'string') return null;
|
|
165
|
+
const trimmed = intent.trim();
|
|
166
|
+
return trimmed === "" ? null : trimmed;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
module.exports = { DirJSONConditionMulti };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const { TiledeskClient } = require("@tiledesk/tiledesk-client");
|
|
2
2
|
const winston = require('../../utils/winston');
|
|
3
|
+
const HttpUtils = require('../../utils/HttpUtils').constructor;
|
|
3
4
|
|
|
4
5
|
class DirRemoveCurrentBot {
|
|
5
6
|
|
|
@@ -27,6 +28,7 @@ class DirRemoveCurrentBot {
|
|
|
27
28
|
else {
|
|
28
29
|
winston.warn("DirRemoveCurrentBot Incorrect directive: ", directive);
|
|
29
30
|
callback();
|
|
31
|
+
return;
|
|
30
32
|
}
|
|
31
33
|
this.go(action, () => {
|
|
32
34
|
callback();
|
|
@@ -35,10 +37,46 @@ class DirRemoveCurrentBot {
|
|
|
35
37
|
|
|
36
38
|
go(action, callback) {
|
|
37
39
|
winston.debug("(RemoveCurrentBot) Action: ", action);
|
|
38
|
-
|
|
40
|
+
let done = false;
|
|
41
|
+
const finish = () => {
|
|
42
|
+
if (done) return;
|
|
43
|
+
done = true;
|
|
39
44
|
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
|
+
});
|
|
40
78
|
});
|
|
41
79
|
}
|
|
42
80
|
}
|
|
43
81
|
|
|
44
|
-
module.exports = { DirRemoveCurrentBot };
|
|
82
|
+
module.exports = { DirRemoveCurrentBot };
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
const { DirIntent } = require('./DirIntent');
|
|
2
|
+
const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
|
|
3
|
+
const { DirInviteHuman } = require('./DirInviteHuman');
|
|
4
|
+
const httpUtils = require('../../utils/HttpUtils');
|
|
5
|
+
const winston = require('../../utils/winston');
|
|
6
|
+
const { Logger } = require('../../Logger');
|
|
7
|
+
|
|
8
|
+
class DirRemoveHuman {
|
|
9
|
+
|
|
10
|
+
constructor(context) {
|
|
11
|
+
if (!context) {
|
|
12
|
+
throw new Error('context object is mandatory.');
|
|
13
|
+
}
|
|
14
|
+
this.context = context;
|
|
15
|
+
this.chatbot = context.chatbot;
|
|
16
|
+
this.requestId = context.requestId;
|
|
17
|
+
this.projectId = context.projectId;
|
|
18
|
+
this.token = context.token;
|
|
19
|
+
this.tdcache = context.tdcache;
|
|
20
|
+
this.API_ENDPOINT = context.API_ENDPOINT;
|
|
21
|
+
this.intentDir = new DirIntent(context);
|
|
22
|
+
this.logger = new Logger({ request_id: this.requestId, dev: this.context.supportRequest?.draft, intent_id: this.context.reply?.intent_id || this.context.reply?.attributes?.intent_info?.intent_id });
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
execute(directive, callback) {
|
|
26
|
+
winston.verbose("Execute RemoveHuman directive");
|
|
27
|
+
let called = false;
|
|
28
|
+
const safeCallback = (stop) => {
|
|
29
|
+
if (called) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
called = true;
|
|
33
|
+
callback(stop);
|
|
34
|
+
};
|
|
35
|
+
if (!directive || !directive.action) {
|
|
36
|
+
this.logger.error("[Remove Human] Incorrect action for ", directive?.name, directive);
|
|
37
|
+
winston.warn("(DirRemoveHuman) Incorrect directive: ", directive);
|
|
38
|
+
safeCallback();
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
this.go(directive.action, (stop) => {
|
|
42
|
+
safeCallback(stop);
|
|
43
|
+
}).catch((err) => {
|
|
44
|
+
winston.error("(DirRemoveHuman) unexpected error: " + JSON.stringify(DirInviteHuman.errorSummary(err)));
|
|
45
|
+
safeCallback();
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async go(action, callback) {
|
|
50
|
+
const trueIntent = action.trueIntent;
|
|
51
|
+
const falseIntent = action.falseIntent;
|
|
52
|
+
|
|
53
|
+
if (this.requestId && this.requestId.startsWith(DirInviteHuman.AUTOMATION_PREFIX)) {
|
|
54
|
+
this.logger.error("[Remove Human] requires a conversation");
|
|
55
|
+
await this.setParameter("flowError", "(Remove human) requires a conversation");
|
|
56
|
+
this.jump(falseIntent, action.falseIntentAttributes, callback);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
let result;
|
|
61
|
+
try {
|
|
62
|
+
result = await this.remove({ scope: DirRemoveHuman.normalizeScope(action.scope) });
|
|
63
|
+
} catch (err) {
|
|
64
|
+
const summary = DirInviteHuman.errorSummary(err);
|
|
65
|
+
this.logger.error("[Remove Human] Error: " + summary.message);
|
|
66
|
+
winston.error("(DirRemoveHuman) remove error: " + JSON.stringify(summary));
|
|
67
|
+
await this.setParameter("flowError", "(Remove human) An error occurred: " + summary.message);
|
|
68
|
+
this.jump(falseIntent, action.falseIntentAttributes, callback);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const removed = (result && Array.isArray(result.removed)) ? result.removed : [];
|
|
73
|
+
await this.setParameter("removed_humans", removed);
|
|
74
|
+
await this.setParameter("removed_humans_count", removed.length);
|
|
75
|
+
this.logger.native("[Remove Human] Removed: " + (removed.length > 0 ? removed.map((r) => r.fullname || r.id_user).join(', ') : 'nobody'));
|
|
76
|
+
this.jump(trueIntent, action.trueIntentAttributes, callback);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
jump(intent, attributes, callback) {
|
|
80
|
+
if (!intent) {
|
|
81
|
+
callback();
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
const intentDirective = DirIntent.intentDirectiveFor(intent, attributes);
|
|
85
|
+
this.intentDir.execute(intentDirective, () => {
|
|
86
|
+
callback(true);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async setParameter(name, value) {
|
|
91
|
+
try {
|
|
92
|
+
if (this.chatbot) {
|
|
93
|
+
await this.chatbot.addParameter(name, value);
|
|
94
|
+
} else if (this.tdcache) {
|
|
95
|
+
await TiledeskChatbot.addParameterStatic(this.tdcache, this.requestId, name, value);
|
|
96
|
+
}
|
|
97
|
+
} catch (err) {
|
|
98
|
+
winston.error("(DirRemoveHuman) error setting parameter " + name + ": " + JSON.stringify(DirInviteHuman.errorSummary(err)));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
remove(body) {
|
|
103
|
+
return new Promise((resolve, reject) => {
|
|
104
|
+
const HTTPREQUEST = {
|
|
105
|
+
url: `${this.API_ENDPOINT}/${this.projectId}/requests/${this.requestId}/participants/remove`,
|
|
106
|
+
headers: {
|
|
107
|
+
'Content-Type': 'application/json',
|
|
108
|
+
'Authorization': DirInviteHuman.fixToken(this.token)
|
|
109
|
+
},
|
|
110
|
+
json: body,
|
|
111
|
+
method: 'POST',
|
|
112
|
+
timeout: DirInviteHuman.INVITE_TIMEOUT_MS
|
|
113
|
+
};
|
|
114
|
+
httpUtils.request(HTTPREQUEST, (err, resbody) => {
|
|
115
|
+
if (err) {
|
|
116
|
+
reject(err);
|
|
117
|
+
} else {
|
|
118
|
+
resolve(resbody);
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
static normalizeScope(scope) {
|
|
125
|
+
return scope === 'all_humans' ? 'all_humans' : 'invited';
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
module.exports = { DirRemoveHuman };
|
|
@@ -83,6 +83,10 @@ class DirReplyV2 {
|
|
|
83
83
|
const buttons = TiledeskChatbotUtil.allReplyButtons(message);
|
|
84
84
|
if (buttons && buttons.length > 0) {
|
|
85
85
|
const locked = await this.lockUnlock(action); // first execution returns locked, then unlocked
|
|
86
|
+
if (locked === null) { // could not lock: stop, do not ask
|
|
87
|
+
callback(true);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
86
90
|
if (locked) { // fist execution returns (just) locked
|
|
87
91
|
must_stop = true; // you must stop after next callbacks (in this flow) if there are buttons
|
|
88
92
|
if (action.noInputIntent) {
|
|
@@ -94,6 +98,11 @@ class DirReplyV2 {
|
|
|
94
98
|
setTimeout(async () => {
|
|
95
99
|
winston.debug("(DirReplyV2) noinput timeout triggered!");
|
|
96
100
|
const userInput = await this.chatbot.getParameter(TiledeskChatbotConst.USER_INPUT);
|
|
101
|
+
const lockedAction = await this.chatbot.currentLockedAction(this.requestId);
|
|
102
|
+
if (lockedAction !== action["_tdActionId"]) {
|
|
103
|
+
winston.debug("(DirReplyV2) lock owned by another action, skipping noinput");
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
97
106
|
if (userInput && userInput === timeout_id) {
|
|
98
107
|
await this.chatbot.unlockIntent(this.requestId);
|
|
99
108
|
await this.chatbot.unlockAction(this.requestId);
|
|
@@ -272,10 +281,16 @@ class DirReplyV2 {
|
|
|
272
281
|
|
|
273
282
|
|
|
274
283
|
async lockUnlock(action, callback) {
|
|
275
|
-
|
|
284
|
+
const lockedAction = await this.chatbot.currentLockedAction(this.requestId);
|
|
285
|
+
// a lock only counts as "waiting for the reply" when this very action set it
|
|
286
|
+
const own = lockedAction && lockedAction === action["_tdActionId"];
|
|
276
287
|
|
|
277
|
-
if (!
|
|
278
|
-
const intent_name = this.reply
|
|
288
|
+
if (!own) {
|
|
289
|
+
const intent_name = this.reply?.attributes?.intent_info?.intent_name;
|
|
290
|
+
if (!intent_name) {
|
|
291
|
+
winston.error("(DirReplyV2) Cannot lock: missing attributes.intent_info.intent_name");
|
|
292
|
+
return null; // caller stops the block without locking
|
|
293
|
+
}
|
|
279
294
|
const actionId = action["_tdActionId"];
|
|
280
295
|
await this.chatbot.lockIntent(this.requestId, intent_name);
|
|
281
296
|
await this.chatbot.lockAction(this.requestId, actionId);
|