n8n-nodes-chat-data 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,980 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChatData = void 0;
4
+ const n8n_workflow_1 = require("n8n-workflow");
5
+ const ActionDescription_1 = require("./ActionDescription");
6
+ const ChatbotDescription_1 = require("./ChatbotDescription");
7
+ const TriggerDescription_1 = require("./TriggerDescription");
8
+ class ChatData {
9
+ constructor() {
10
+ this.description = {
11
+ displayName: 'Chat Data',
12
+ name: 'chatData',
13
+ group: ['transform'],
14
+ version: 1,
15
+ description: 'Basic Chat Data Node',
16
+ defaults: {
17
+ name: 'Chat Data',
18
+ },
19
+ inputs: ['main'],
20
+ outputs: ['main'],
21
+ icon: 'file:ChatData.svg',
22
+ subtitle: '={{$parameter["resource"] + ": " + $parameter["operation"]}}',
23
+ credentials: [
24
+ {
25
+ name: 'chatDataApi',
26
+ required: true,
27
+ },
28
+ ],
29
+ requestDefaults: {
30
+ baseURL: '{{$credentials.baseUrl}}',
31
+ headers: {
32
+ Accept: 'application/json',
33
+ 'Content-Type': 'application/json',
34
+ },
35
+ },
36
+ webhooks: [
37
+ {
38
+ name: 'default',
39
+ httpMethod: 'POST',
40
+ responseMode: 'onReceived',
41
+ path: 'webhook',
42
+ isFullPath: false,
43
+ },
44
+ ],
45
+ properties: [
46
+ {
47
+ displayName: 'Resource',
48
+ name: 'resource',
49
+ type: 'options',
50
+ noDataExpression: true,
51
+ options: [
52
+ {
53
+ name: 'Action',
54
+ value: 'action',
55
+ },
56
+ {
57
+ name: 'Chatbot',
58
+ value: 'chatbot',
59
+ },
60
+ {
61
+ name: 'Trigger',
62
+ value: 'trigger',
63
+ },
64
+ ],
65
+ default: 'action',
66
+ description: 'Choose a resource - Trigger resource supports webhooks',
67
+ },
68
+ ...ActionDescription_1.actionOperations,
69
+ ...ActionDescription_1.actionFields,
70
+ ...ChatbotDescription_1.chatbotOperations,
71
+ ...ChatbotDescription_1.chatbotFields,
72
+ ...TriggerDescription_1.triggerOperations,
73
+ ...TriggerDescription_1.triggerFields,
74
+ ],
75
+ };
76
+ this.methods = {
77
+ loadOptions: {
78
+ async getChatbots() {
79
+ const credentials = await this.getCredentials('chatDataApi');
80
+ if (!credentials.baseUrl) {
81
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), new Error('Base URL is missing in credentials. Please check your credentials configuration.'), { itemIndex: 0 });
82
+ }
83
+ const baseUrl = credentials.baseUrl;
84
+ const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
85
+ const fullUrl = `${baseUrlFormatted}/api/v2/get-chatbots`;
86
+ try {
87
+ const response = await this.helpers.httpRequest({
88
+ url: fullUrl,
89
+ method: 'GET',
90
+ headers: {
91
+ Authorization: `Bearer ${credentials.apiKey}`,
92
+ 'Accept': 'application/json',
93
+ 'Content-Type': 'application/json',
94
+ },
95
+ json: true,
96
+ ignoreHttpStatusErrors: true,
97
+ });
98
+ if (response.status === 'error') {
99
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: 0 });
100
+ }
101
+ if (!response.chatbots || !Array.isArray(response.chatbots)) {
102
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), new Error('Invalid response format. Expected chatbots array.'), {
103
+ itemIndex: 0,
104
+ });
105
+ }
106
+ const options = response.chatbots.map((chatbot) => ({
107
+ name: chatbot.chatbotName,
108
+ value: chatbot.chatbotId,
109
+ }));
110
+ return options;
111
+ }
112
+ catch (error) {
113
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), new Error(`Failed to fetch chatbots: ${error.message}`), { itemIndex: 0 });
114
+ }
115
+ },
116
+ },
117
+ };
118
+ this.webhookMethods = {
119
+ default: {
120
+ async checkExists() {
121
+ const webhookData = this.getWorkflowStaticData('node');
122
+ const chatbotId = webhookData.chatbotId;
123
+ const webhookUrl = webhookData.webhookUrl;
124
+ if (chatbotId && webhookUrl) {
125
+ try {
126
+ return true;
127
+ }
128
+ catch (error) {
129
+ return false;
130
+ }
131
+ }
132
+ return false;
133
+ },
134
+ async create() {
135
+ try {
136
+ const webhookUrl = this.getNodeWebhookUrl('default');
137
+ const resource = this.getNodeParameter('resource');
138
+ const operation = this.getNodeParameter('operation');
139
+ if (resource === 'trigger') {
140
+ let eventType = '';
141
+ if (operation === 'onLeadSubmission') {
142
+ eventType = 'lead-submission';
143
+ }
144
+ else if (operation === 'onLiveChatEscalation') {
145
+ eventType = 'live-chat-escalation';
146
+ }
147
+ else if (operation === 'onNewMessage') {
148
+ eventType = 'chat';
149
+ }
150
+ else {
151
+ return false;
152
+ }
153
+ const chatbotId = this.getNodeParameter('chatbot_id');
154
+ const credentials = await this.getCredentials('chatDataApi');
155
+ const baseUrl = credentials.baseUrl;
156
+ const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
157
+ const fullUrl = `${baseUrlFormatted}/api/v2/add-webhook`;
158
+ const response = await this.helpers.httpRequest({
159
+ url: fullUrl,
160
+ method: 'POST',
161
+ body: {
162
+ url: webhookUrl,
163
+ event: eventType,
164
+ chatbotId,
165
+ },
166
+ headers: {
167
+ Authorization: `Bearer ${credentials.apiKey}`,
168
+ 'Accept': 'application/json',
169
+ 'Content-Type': 'application/json',
170
+ },
171
+ json: true,
172
+ ignoreHttpStatusErrors: true,
173
+ });
174
+ if (response.status === 'error') {
175
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message || 'Failed to register webhook');
176
+ }
177
+ const webhookData = this.getWorkflowStaticData('node');
178
+ webhookData.chatbotId = chatbotId;
179
+ webhookData.eventType = eventType;
180
+ webhookData.webhookUrl = webhookUrl;
181
+ webhookData.isPersistent = true;
182
+ return true;
183
+ }
184
+ return false;
185
+ }
186
+ catch (error) {
187
+ throw error;
188
+ }
189
+ },
190
+ async delete() {
191
+ try {
192
+ const webhookData = this.getWorkflowStaticData('node');
193
+ const nodeSettings = this.getNode();
194
+ const workflowMode = this.getMode();
195
+ const isNodeRemoved = nodeSettings.disabled === true;
196
+ const isWorkflowDeleted = workflowMode === 'internal';
197
+ if (!isNodeRemoved && !isWorkflowDeleted) {
198
+ return true;
199
+ }
200
+ const chatbotId = webhookData.chatbotId;
201
+ const webhookUrl = webhookData.webhookUrl;
202
+ if (chatbotId && webhookUrl) {
203
+ const credentials = await this.getCredentials('chatDataApi');
204
+ const baseUrl = credentials.baseUrl;
205
+ const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
206
+ const fullUrl = `${baseUrlFormatted}/api/v2/delete-webhook`;
207
+ const response = await this.helpers.httpRequest({
208
+ url: fullUrl,
209
+ method: 'POST',
210
+ body: {
211
+ url: webhookUrl,
212
+ chatbotId,
213
+ },
214
+ headers: {
215
+ Authorization: `Bearer ${credentials.apiKey}`,
216
+ 'Accept': 'application/json',
217
+ 'Content-Type': 'application/json',
218
+ },
219
+ json: true,
220
+ ignoreHttpStatusErrors: true,
221
+ });
222
+ if (response.status === 'error') {
223
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: 0 });
224
+ }
225
+ delete webhookData.chatbotId;
226
+ delete webhookData.eventType;
227
+ delete webhookData.webhookUrl;
228
+ delete webhookData.isPersistent;
229
+ return true;
230
+ }
231
+ return false;
232
+ }
233
+ catch (error) {
234
+ throw error;
235
+ }
236
+ },
237
+ },
238
+ };
239
+ }
240
+ async webhook() {
241
+ const bodyData = this.getBodyData();
242
+ return {
243
+ workflowData: [
244
+ this.helpers.returnJsonArray(JSON.parse(JSON.stringify(bodyData)))
245
+ ],
246
+ };
247
+ }
248
+ async execute() {
249
+ const items = this.getInputData();
250
+ const returnData = [];
251
+ const resource = this.getNodeParameter('resource', 0);
252
+ const operation = this.getNodeParameter('operation', 0);
253
+ if (resource === 'action') {
254
+ if (operation === 'sendMessage') {
255
+ for (let i = 0; i < items.length; i++) {
256
+ try {
257
+ const chatbotId = this.getNodeParameter('chatbot_id', i);
258
+ const messagesData = this.getNodeParameter('messages.messageValues', i, []);
259
+ const additionalFields = this.getNodeParameter('additionalFields', i, {});
260
+ if (!messagesData.length) {
261
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'At least one message is required', { itemIndex: i });
262
+ }
263
+ const messages = messagesData.map((message) => ({
264
+ role: message.role,
265
+ content: message.content,
266
+ }));
267
+ const body = {
268
+ chatbotId,
269
+ messages,
270
+ };
271
+ if (additionalFields.conversationId) {
272
+ body.conversationId = additionalFields.conversationId;
273
+ }
274
+ if (additionalFields.baseModel) {
275
+ body.baseModel = additionalFields.baseModel;
276
+ }
277
+ if (additionalFields.basePrompt) {
278
+ body.basePrompt = additionalFields.basePrompt;
279
+ }
280
+ if (additionalFields.appendMessages !== undefined) {
281
+ body.appendMessages = additionalFields.appendMessages;
282
+ }
283
+ else {
284
+ body.appendMessages = true;
285
+ }
286
+ if (additionalFields.stream !== undefined) {
287
+ body.stream = additionalFields.stream;
288
+ }
289
+ else {
290
+ body.stream = false;
291
+ }
292
+ const credentials = await this.getCredentials('chatDataApi');
293
+ const baseUrl = credentials.baseUrl;
294
+ const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
295
+ const fullUrl = `${baseUrlFormatted}/api/v2/chat`;
296
+ const response = await this.helpers.httpRequest({
297
+ url: fullUrl,
298
+ method: 'POST',
299
+ body,
300
+ headers: {
301
+ Authorization: `Bearer ${credentials.apiKey}`,
302
+ 'Accept': 'application/json',
303
+ 'Content-Type': 'application/json',
304
+ },
305
+ json: true,
306
+ ignoreHttpStatusErrors: true,
307
+ });
308
+ if (response.status === 'error') {
309
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: i });
310
+ }
311
+ const newItem = {
312
+ json: {
313
+ output: response,
314
+ }
315
+ };
316
+ returnData.push(newItem);
317
+ }
318
+ catch (error) {
319
+ let errorMessage = error.message;
320
+ if (error.response && error.response.body) {
321
+ const responseBody = error.response.body;
322
+ if (typeof responseBody === 'object' && responseBody.message) {
323
+ errorMessage = responseBody.message;
324
+ }
325
+ else if (typeof responseBody === 'string') {
326
+ try {
327
+ const parsedBody = JSON.parse(responseBody);
328
+ if (parsedBody.message) {
329
+ errorMessage = parsedBody.message;
330
+ }
331
+ }
332
+ catch (e) {
333
+ }
334
+ }
335
+ }
336
+ if (this.continueOnFail()) {
337
+ returnData.push({
338
+ json: {
339
+ ...items[i].json,
340
+ error: errorMessage,
341
+ },
342
+ pairedItem: i,
343
+ });
344
+ continue;
345
+ }
346
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage, { itemIndex: i });
347
+ }
348
+ }
349
+ }
350
+ else if (operation === 'getLeads') {
351
+ try {
352
+ const chatbotId = this.getNodeParameter('chatbot_id', 0);
353
+ const limit = this.getNodeParameter('limit', 0);
354
+ const additionalFields = this.getNodeParameter('additionalFields', 0, {});
355
+ const returnData = [];
356
+ let responseData = [];
357
+ const qs = {
358
+ size: 100,
359
+ };
360
+ if (additionalFields.startDate) {
361
+ const startDate = new Date(additionalFields.startDate);
362
+ qs.startTimestamp = startDate.getTime().toString();
363
+ }
364
+ if (additionalFields.endDate) {
365
+ const endDate = new Date(additionalFields.endDate);
366
+ qs.endTimestamp = endDate.getTime().toString();
367
+ }
368
+ if (additionalFields.source) {
369
+ qs.source = additionalFields.source;
370
+ }
371
+ let hasNextPage = true;
372
+ let pageNumber = 0;
373
+ const credentials = await this.getCredentials('chatDataApi');
374
+ const baseUrl = credentials.baseUrl;
375
+ while (hasNextPage) {
376
+ if (pageNumber > 0) {
377
+ qs.start = (pageNumber * 100).toString();
378
+ }
379
+ const endpoint = `/get-customers/${chatbotId}`;
380
+ const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
381
+ const fullUrl = `${baseUrlFormatted}/api/v2${endpoint}`;
382
+ const response = await this.helpers.httpRequest({
383
+ url: fullUrl,
384
+ method: 'GET',
385
+ qs,
386
+ headers: {
387
+ Authorization: `Bearer ${credentials.apiKey}`,
388
+ 'Accept': 'application/json',
389
+ 'Content-Type': 'application/json',
390
+ },
391
+ json: true,
392
+ ignoreHttpStatusErrors: true,
393
+ });
394
+ if (response.status === 'error') {
395
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: 0 });
396
+ }
397
+ if (response && response.customers && Array.isArray(response.customers)) {
398
+ responseData = [...responseData, ...response.customers];
399
+ const totalResults = response.total;
400
+ hasNextPage = totalResults > (pageNumber + 1) * 100;
401
+ if (limit > 0 && responseData.length >= limit) {
402
+ responseData = responseData.slice(0, limit);
403
+ hasNextPage = false;
404
+ break;
405
+ }
406
+ pageNumber++;
407
+ }
408
+ else {
409
+ hasNextPage = false;
410
+ }
411
+ }
412
+ for (const item of responseData) {
413
+ returnData.push({
414
+ json: item,
415
+ });
416
+ }
417
+ return [returnData];
418
+ }
419
+ catch (error) {
420
+ let errorMessage = error.message;
421
+ if (error.response && error.response.body) {
422
+ const responseBody = error.response.body;
423
+ if (typeof responseBody === 'object' && responseBody.message) {
424
+ errorMessage = responseBody.message;
425
+ }
426
+ else if (typeof responseBody === 'string') {
427
+ try {
428
+ const parsedBody = JSON.parse(responseBody);
429
+ if (parsedBody.message) {
430
+ errorMessage = parsedBody.message;
431
+ }
432
+ }
433
+ catch (e) {
434
+ }
435
+ }
436
+ }
437
+ if (this.continueOnFail()) {
438
+ return [[{ json: { error: errorMessage } }]];
439
+ }
440
+ throw error;
441
+ }
442
+ }
443
+ else if (operation === 'getConversations') {
444
+ try {
445
+ const chatbotId = this.getNodeParameter('chatbot_id', 0);
446
+ const limit = this.getNodeParameter('limit', 0);
447
+ const additionalFields = this.getNodeParameter('additionalFields', 0, {});
448
+ const returnData = [];
449
+ let responseData = [];
450
+ const qs = {
451
+ size: 100,
452
+ };
453
+ if (additionalFields.startDate) {
454
+ const startDate = new Date(additionalFields.startDate);
455
+ qs.startTimestamp = startDate.getTime().toString();
456
+ }
457
+ if (additionalFields.endDate) {
458
+ const endDate = new Date(additionalFields.endDate);
459
+ qs.endTimestamp = endDate.getTime().toString();
460
+ }
461
+ if (additionalFields.source) {
462
+ qs.source = additionalFields.source;
463
+ }
464
+ if (additionalFields.leadId) {
465
+ qs.leadId = additionalFields.leadId;
466
+ }
467
+ let hasNextPage = true;
468
+ let pageNumber = 0;
469
+ while (hasNextPage) {
470
+ if (pageNumber > 0) {
471
+ qs.start = (pageNumber * 100).toString();
472
+ }
473
+ const endpoint = `/get-conversations/${chatbotId}`;
474
+ const credentials = await this.getCredentials('chatDataApi');
475
+ const baseUrl = credentials.baseUrl;
476
+ const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
477
+ const fullUrl = `${baseUrlFormatted}/api/v2${endpoint}`;
478
+ const response = await this.helpers.httpRequest({
479
+ url: fullUrl,
480
+ method: 'GET',
481
+ qs,
482
+ headers: {
483
+ Authorization: `Bearer ${credentials.apiKey}`,
484
+ 'Accept': 'application/json',
485
+ 'Content-Type': 'application/json',
486
+ },
487
+ json: true,
488
+ ignoreHttpStatusErrors: true,
489
+ });
490
+ if (response.status === 'error') {
491
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: 0 });
492
+ }
493
+ if (response && response.conversations && Array.isArray(response.conversations)) {
494
+ responseData = [...responseData, ...response.conversations];
495
+ const totalResults = response.total;
496
+ hasNextPage = totalResults > (pageNumber + 1) * 100;
497
+ if (limit > 0 && responseData.length >= limit) {
498
+ responseData = responseData.slice(0, limit);
499
+ hasNextPage = false;
500
+ break;
501
+ }
502
+ pageNumber++;
503
+ }
504
+ else {
505
+ hasNextPage = false;
506
+ }
507
+ }
508
+ for (const item of responseData) {
509
+ returnData.push({
510
+ json: item,
511
+ });
512
+ }
513
+ return [returnData];
514
+ }
515
+ catch (error) {
516
+ let errorMessage = error.message;
517
+ if (error.response && error.response.body) {
518
+ const responseBody = error.response.body;
519
+ if (typeof responseBody === 'object' && responseBody.message) {
520
+ errorMessage = responseBody.message;
521
+ }
522
+ else if (typeof responseBody === 'string') {
523
+ try {
524
+ const parsedBody = JSON.parse(responseBody);
525
+ if (parsedBody.message) {
526
+ errorMessage = parsedBody.message;
527
+ }
528
+ }
529
+ catch (e) {
530
+ }
531
+ }
532
+ }
533
+ if (this.continueOnFail()) {
534
+ return [[{ json: { error: errorMessage } }]];
535
+ }
536
+ throw error;
537
+ }
538
+ }
539
+ else if (operation === 'makeApiCall') {
540
+ try {
541
+ const url = this.getNodeParameter('url', 0);
542
+ const method = this.getNodeParameter('method', 0);
543
+ const responseFormat = this.getNodeParameter('responseFormat', 0);
544
+ let fullUrl = url;
545
+ if (url.startsWith('/api/v2/')) {
546
+ const credentials = await this.getCredentials('chatDataApi');
547
+ const baseUrl = credentials.baseUrl;
548
+ const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
549
+ fullUrl = `${baseUrlFormatted}${url}`;
550
+ }
551
+ else {
552
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'URL must start with "/api/v2/". Please use the format: /api/v2/your-endpoint', { itemIndex: 0 });
553
+ }
554
+ const credentials = await this.getCredentials('chatDataApi');
555
+ const headerParameters = this.getNodeParameter('headers.parameters', 0, []);
556
+ const headers = {};
557
+ for (const param of headerParameters) {
558
+ headers[param.name] = param.value;
559
+ }
560
+ headers['Authorization'] = `Bearer ${credentials.apiKey}`;
561
+ const queryParameters = this.getNodeParameter('qs.parameters', 0, []);
562
+ const qs = {};
563
+ for (const param of queryParameters) {
564
+ qs[param.name] = param.value;
565
+ }
566
+ let body;
567
+ if (['POST', 'PUT', 'PATCH'].includes(method)) {
568
+ const bodyParam = this.getNodeParameter('body', 0, '{}');
569
+ try {
570
+ body = JSON.parse(bodyParam);
571
+ }
572
+ catch (error) {
573
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Body must be a valid JSON object', { itemIndex: 0 });
574
+ }
575
+ }
576
+ const requestOptions = {
577
+ url: fullUrl,
578
+ method: method,
579
+ headers: headers,
580
+ };
581
+ if (Object.keys(qs).length > 0) {
582
+ requestOptions.qs = qs;
583
+ }
584
+ if (body !== undefined) {
585
+ requestOptions.body = body;
586
+ requestOptions.json = true;
587
+ }
588
+ requestOptions.ignoreHttpStatusErrors = true;
589
+ const response = await this.helpers.httpRequest(requestOptions);
590
+ if (response && response.status === 'error') {
591
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: 0 });
592
+ }
593
+ let responseData;
594
+ if (responseFormat === 'string' && typeof response === 'object') {
595
+ responseData = JSON.stringify(response);
596
+ }
597
+ else {
598
+ responseData = response;
599
+ }
600
+ const returnItem = {
601
+ json: responseData,
602
+ };
603
+ return [[returnItem]];
604
+ }
605
+ catch (error) {
606
+ let errorMessage = error.message;
607
+ if (error.response && error.response.body) {
608
+ const responseBody = error.response.body;
609
+ if (typeof responseBody === 'object' && responseBody.message) {
610
+ errorMessage = responseBody.message;
611
+ }
612
+ else if (typeof responseBody === 'string') {
613
+ try {
614
+ const parsedBody = JSON.parse(responseBody);
615
+ if (parsedBody.message) {
616
+ errorMessage = parsedBody.message;
617
+ }
618
+ }
619
+ catch (e) {
620
+ }
621
+ }
622
+ }
623
+ if (this.continueOnFail()) {
624
+ return [[{
625
+ json: {
626
+ error: errorMessage,
627
+ statusCode: error.statusCode || 500,
628
+ }
629
+ }]];
630
+ }
631
+ throw error;
632
+ }
633
+ }
634
+ }
635
+ else if (resource === 'chatbot') {
636
+ if (operation === 'updateBasePrompt') {
637
+ for (let i = 0; i < items.length; i++) {
638
+ try {
639
+ const chatbotId = this.getNodeParameter('chatbot_id', i);
640
+ const basePrompt = this.getNodeParameter('basePrompt', i);
641
+ const body = {
642
+ chatbotId,
643
+ basePrompt,
644
+ };
645
+ const credentials = await this.getCredentials('chatDataApi');
646
+ const baseUrl = credentials.baseUrl;
647
+ const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
648
+ const fullUrl = `${baseUrlFormatted}/api/v2/update-chatbot-settings`;
649
+ const response = await this.helpers.httpRequest({
650
+ url: fullUrl,
651
+ method: 'POST',
652
+ body,
653
+ headers: {
654
+ Authorization: `Bearer ${credentials.apiKey}`,
655
+ 'Accept': 'application/json',
656
+ 'Content-Type': 'application/json',
657
+ },
658
+ json: true,
659
+ ignoreHttpStatusErrors: true,
660
+ });
661
+ if (response.status === 'error') {
662
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: i });
663
+ }
664
+ const newItem = {
665
+ json: {
666
+ ...response,
667
+ success: true,
668
+ chatbotId,
669
+ },
670
+ };
671
+ returnData.push(newItem);
672
+ }
673
+ catch (error) {
674
+ let errorMessage = error.message;
675
+ if (error.response && error.response.body) {
676
+ const responseBody = error.response.body;
677
+ if (typeof responseBody === 'object' && responseBody.message) {
678
+ errorMessage = responseBody.message;
679
+ }
680
+ else if (typeof responseBody === 'string') {
681
+ try {
682
+ const parsedBody = JSON.parse(responseBody);
683
+ if (parsedBody.message) {
684
+ errorMessage = parsedBody.message;
685
+ }
686
+ }
687
+ catch (e) {
688
+ }
689
+ }
690
+ }
691
+ if (this.continueOnFail()) {
692
+ returnData.push({
693
+ json: {
694
+ ...items[i].json,
695
+ error: errorMessage,
696
+ },
697
+ pairedItem: i,
698
+ });
699
+ continue;
700
+ }
701
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage, { itemIndex: i });
702
+ }
703
+ }
704
+ }
705
+ else if (operation === 'retrainChatbot') {
706
+ for (let i = 0; i < items.length; i++) {
707
+ try {
708
+ const chatbotId = this.getNodeParameter('chatbot_id', i);
709
+ const sourceText = this.getNodeParameter('sourceText', i, '');
710
+ const qAndAsData = this.getNodeParameter('qAndAs.qAndAValues', i, []);
711
+ const urlsData = this.getNodeParameter('urlsToScrape.urlValues', i, []);
712
+ const scrapingOptions = this.getNodeParameter('options', i, {});
713
+ const qAndAs = qAndAsData.length ? qAndAsData.map((qa) => ({
714
+ question: qa.question,
715
+ answer: qa.answer,
716
+ })) : undefined;
717
+ const urlsToScrape = urlsData.length ? urlsData.map((urlObj) => urlObj.url) : undefined;
718
+ const body = {
719
+ chatbotId,
720
+ };
721
+ if (sourceText) {
722
+ body.sourceText = sourceText;
723
+ }
724
+ if (qAndAs && qAndAs.length) {
725
+ body.qAndAs = qAndAs;
726
+ }
727
+ if (Array.isArray(urlsToScrape) && urlsToScrape.length) {
728
+ body.urlsToScrape = urlsToScrape;
729
+ }
730
+ if (Object.keys(scrapingOptions).length) {
731
+ body.options = scrapingOptions;
732
+ }
733
+ const credentials = await this.getCredentials('chatDataApi');
734
+ const baseUrl = credentials.baseUrl;
735
+ const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
736
+ const fullUrl = `${baseUrlFormatted}/api/v2/retrain-chatbot`;
737
+ const response = await this.helpers.httpRequest({
738
+ url: fullUrl,
739
+ method: 'POST',
740
+ body,
741
+ headers: {
742
+ Authorization: `Bearer ${credentials.apiKey}`,
743
+ 'Accept': 'application/json',
744
+ 'Content-Type': 'application/json',
745
+ },
746
+ json: true,
747
+ ignoreHttpStatusErrors: true,
748
+ });
749
+ if (response.status === 'error') {
750
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: i });
751
+ }
752
+ const newItem = {
753
+ json: {
754
+ ...response,
755
+ success: true,
756
+ chatbotId,
757
+ },
758
+ };
759
+ returnData.push(newItem);
760
+ }
761
+ catch (error) {
762
+ let errorMessage = error.message;
763
+ if (error.response && error.response.body) {
764
+ const responseBody = error.response.body;
765
+ if (typeof responseBody === 'object' && responseBody.message) {
766
+ errorMessage = responseBody.message;
767
+ }
768
+ else if (typeof responseBody === 'string') {
769
+ try {
770
+ const parsedBody = JSON.parse(responseBody);
771
+ if (parsedBody.message) {
772
+ errorMessage = parsedBody.message;
773
+ }
774
+ }
775
+ catch (e) {
776
+ }
777
+ }
778
+ }
779
+ if (this.continueOnFail()) {
780
+ returnData.push({
781
+ json: {
782
+ ...items[i].json,
783
+ error: errorMessage,
784
+ },
785
+ pairedItem: i,
786
+ });
787
+ continue;
788
+ }
789
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage, { itemIndex: i });
790
+ }
791
+ }
792
+ }
793
+ else if (operation === 'getChatbotStatus') {
794
+ try {
795
+ const chatbotId = this.getNodeParameter('chatbot_id', 0);
796
+ const endpoint = `/chatbot/status/${chatbotId}`;
797
+ const credentials = await this.getCredentials('chatDataApi');
798
+ const baseUrl = credentials.baseUrl;
799
+ const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
800
+ const fullUrl = `${baseUrlFormatted}/api/v2${endpoint}`;
801
+ const response = await this.helpers.httpRequest({
802
+ url: fullUrl,
803
+ method: 'GET',
804
+ headers: {
805
+ Authorization: `Bearer ${credentials.apiKey}`,
806
+ 'Accept': 'application/json',
807
+ 'Content-Type': 'application/json',
808
+ },
809
+ json: true,
810
+ ignoreHttpStatusErrors: true,
811
+ });
812
+ if (response.status === 'error') {
813
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: 0 });
814
+ }
815
+ return [[{ json: response }]];
816
+ }
817
+ catch (error) {
818
+ let errorMessage = error.message;
819
+ if (error.response && error.response.body) {
820
+ const responseBody = error.response.body;
821
+ if (typeof responseBody === 'object' && responseBody.message) {
822
+ errorMessage = responseBody.message;
823
+ }
824
+ else if (typeof responseBody === 'string') {
825
+ try {
826
+ const parsedBody = JSON.parse(responseBody);
827
+ if (parsedBody.message) {
828
+ errorMessage = parsedBody.message;
829
+ }
830
+ }
831
+ catch (e) {
832
+ }
833
+ }
834
+ }
835
+ if (this.continueOnFail()) {
836
+ return [[{ json: { error: errorMessage } }]];
837
+ }
838
+ throw error;
839
+ }
840
+ }
841
+ else if (operation === 'createChatbot') {
842
+ try {
843
+ const chatbotName = this.getNodeParameter('chatbotName', 0);
844
+ const model = this.getNodeParameter('model', 0);
845
+ const sourceText = this.getNodeParameter('sourceText', 0, '');
846
+ const urlsData = this.getNodeParameter('urlsToScrape.urlValues', 0, []);
847
+ const urlsToScrape = urlsData.length ? urlsData.map((urlObj) => urlObj.url) : undefined;
848
+ const body = {
849
+ chatbotName,
850
+ model,
851
+ };
852
+ if (sourceText) {
853
+ body.sourceText = sourceText;
854
+ }
855
+ if (Array.isArray(urlsToScrape) && urlsToScrape.length) {
856
+ body.urlsToScrape = urlsToScrape;
857
+ }
858
+ if (model === 'custom-model') {
859
+ const customBackend = this.getNodeParameter('customBackend', 0, '');
860
+ const bearer = this.getNodeParameter('bearer', 0, '');
861
+ if (customBackend) {
862
+ body.customBackend = customBackend;
863
+ }
864
+ if (bearer) {
865
+ body.bearer = bearer;
866
+ }
867
+ }
868
+ const credentials = await this.getCredentials('chatDataApi');
869
+ const baseUrl = credentials.baseUrl;
870
+ const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
871
+ const fullUrl = `${baseUrlFormatted}/api/v2/create-chatbot`;
872
+ const response = await this.helpers.httpRequest({
873
+ url: fullUrl,
874
+ method: 'POST',
875
+ body,
876
+ headers: {
877
+ Authorization: `Bearer ${credentials.apiKey}`,
878
+ 'Accept': 'application/json',
879
+ 'Content-Type': 'application/json',
880
+ },
881
+ json: true,
882
+ ignoreHttpStatusErrors: true,
883
+ });
884
+ if (response.status === 'error') {
885
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: 0 });
886
+ }
887
+ return [[{ json: response }]];
888
+ }
889
+ catch (error) {
890
+ let errorMessage = error.message;
891
+ if (error.response && error.response.body) {
892
+ const responseBody = error.response.body;
893
+ if (typeof responseBody === 'object' && responseBody.message) {
894
+ errorMessage = responseBody.message;
895
+ }
896
+ else if (typeof responseBody === 'string') {
897
+ try {
898
+ const parsedBody = JSON.parse(responseBody);
899
+ if (parsedBody.message) {
900
+ errorMessage = parsedBody.message;
901
+ }
902
+ }
903
+ catch (e) {
904
+ }
905
+ }
906
+ }
907
+ if (this.continueOnFail()) {
908
+ return [[{ json: { error: errorMessage } }]];
909
+ }
910
+ throw error;
911
+ }
912
+ }
913
+ }
914
+ else if (resource === 'trigger') {
915
+ if (operation === 'onLeadSubmission' || operation === 'onLiveChatEscalation' || operation === 'onNewMessage') {
916
+ let incomingData;
917
+ if (typeof items[0].json === 'object' && items[0].json !== null) {
918
+ incomingData = items[0].json;
919
+ }
920
+ else {
921
+ incomingData = JSON.parse(String(items[0].json));
922
+ }
923
+ const newItem = {
924
+ json: incomingData,
925
+ };
926
+ returnData.push(newItem);
927
+ }
928
+ else {
929
+ for (let i = 0; i < items.length; i++) {
930
+ try {
931
+ const pollInterval = this.getNodeParameter('pollInterval', i);
932
+ const newItem = {
933
+ json: {
934
+ ...items[i].json,
935
+ success: true,
936
+ resource: 'trigger',
937
+ operation,
938
+ pollInterval,
939
+ },
940
+ };
941
+ returnData.push(newItem);
942
+ }
943
+ catch (error) {
944
+ let errorMessage = error.message;
945
+ if (error.response && error.response.body) {
946
+ const responseBody = error.response.body;
947
+ if (typeof responseBody === 'object' && responseBody.message) {
948
+ errorMessage = responseBody.message;
949
+ }
950
+ else if (typeof responseBody === 'string') {
951
+ try {
952
+ const parsedBody = JSON.parse(responseBody);
953
+ if (parsedBody.message) {
954
+ errorMessage = parsedBody.message;
955
+ }
956
+ }
957
+ catch (e) {
958
+ }
959
+ }
960
+ }
961
+ if (this.continueOnFail()) {
962
+ returnData.push({
963
+ json: {
964
+ ...items[i].json,
965
+ error: errorMessage,
966
+ },
967
+ pairedItem: i,
968
+ });
969
+ continue;
970
+ }
971
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage, { itemIndex: i });
972
+ }
973
+ }
974
+ }
975
+ }
976
+ return [returnData.length ? returnData : items];
977
+ }
978
+ }
979
+ exports.ChatData = ChatData;
980
+ //# sourceMappingURL=ChatData.node.js.map