n8n-nodes-chat-data
Version:
Chatdata integration for n8n. Manage chatbots, send messages, and retrieve leads from your Chatdata account.
344 lines • 15.5 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChatDataTrigger = void 0;
const n8n_workflow_1 = require("n8n-workflow");
const TriggerDescription_1 = require("./TriggerDescription");
class ChatDataTrigger {
constructor() {
this.description = {
displayName: 'Chat Data Trigger',
name: 'chatDataTrigger',
icon: 'file:ChatData.svg',
group: ['trigger'],
version: 1,
subtitle: '={{$parameter["operation"]}}',
description: 'Triggers workflows on Chat Data events',
defaults: {
name: 'Chat Data Trigger',
},
inputs: [],
outputs: ["main"],
webhooks: [
{
name: 'default',
httpMethod: 'POST',
responseMode: 'onReceived',
path: 'webhook',
isFullPath: false,
},
],
credentials: [
{
name: 'chatDataApi',
required: true,
},
],
properties: [
TriggerDescription_1.triggerResource,
...TriggerDescription_1.triggerOperations,
...TriggerDescription_1.triggerFields,
],
};
this.methods = {
loadOptions: {
async getChatbots() {
const credentials = await this.getCredentials('chatDataApi');
if (!credentials.baseUrl) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), new Error('Base URL is missing in credentials. Please check your credentials configuration.'), { itemIndex: 0 });
}
const baseUrl = credentials.baseUrl;
const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
const fullUrl = `${baseUrlFormatted}/api/v2/get-chatbots`;
try {
const response = await this.helpers.httpRequest({
url: fullUrl,
method: 'GET',
headers: {
Authorization: `Bearer ${credentials.apiKey}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
json: true,
ignoreHttpStatusErrors: true,
});
if (response.status === 'error') {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: 0 });
}
if (!response.chatbots || !Array.isArray(response.chatbots)) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), new Error('Invalid response format. Expected chatbots array.'), {
itemIndex: 0,
});
}
const options = response.chatbots.map((chatbot) => ({
name: chatbot.chatbotName,
value: chatbot.chatbotId,
}));
return options;
}
catch (error) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), new Error(`Failed to fetch chatbots: ${error.message}`), { itemIndex: 0 });
}
},
},
};
this.webhookMethods = {
default: {
async checkExists() {
const webhookData = this.getWorkflowStaticData('node');
const chatbotId = webhookData.chatbotId;
const webhookUrl = webhookData.webhookUrl;
if (chatbotId && webhookUrl) {
try {
return true;
}
catch (error) {
return false;
}
}
return false;
},
async create() {
try {
const webhookUrl = this.getNodeWebhookUrl('default');
const operation = this.getNodeParameter('operation');
let eventType = '';
if (operation === 'onLeadSubmission') {
eventType = 'lead-submission';
}
else if (operation === 'onLiveChatEscalation') {
eventType = 'live-chat-escalation';
}
else if (operation === 'onNewMessage') {
eventType = 'chat';
}
else {
return false;
}
const chatbotId = this.getNodeParameter('chatbot_id');
const credentials = await this.getCredentials('chatDataApi');
const baseUrl = credentials.baseUrl;
const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
const fullUrl = `${baseUrlFormatted}/api/v2/add-webhook`;
const response = await this.helpers.httpRequest({
url: fullUrl,
method: 'POST',
body: {
url: webhookUrl,
event: eventType,
chatbotId,
},
headers: {
Authorization: `Bearer ${credentials.apiKey}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
json: true,
ignoreHttpStatusErrors: true,
});
if (response.status === 'error') {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message || 'Failed to register webhook');
}
const webhookData = this.getWorkflowStaticData('node');
webhookData.chatbotId = chatbotId;
webhookData.eventType = eventType;
webhookData.webhookUrl = webhookUrl;
webhookData.isPersistent = true;
webhookData.setupInfo = {
response,
chatbotId,
eventType,
webhookUrl,
createdAt: new Date().toISOString(),
};
return true;
}
catch (error) {
throw error;
}
},
async delete() {
try {
const webhookData = this.getWorkflowStaticData('node');
const nodeSettings = this.getNode();
const workflowMode = this.getMode();
const isNodeRemoved = nodeSettings.disabled === true;
const isWorkflowDeleted = workflowMode === 'internal';
if (!isNodeRemoved && !isWorkflowDeleted) {
return true;
}
const chatbotId = webhookData.chatbotId;
const webhookUrl = webhookData.webhookUrl;
if (chatbotId && webhookUrl) {
const credentials = await this.getCredentials('chatDataApi');
const baseUrl = credentials.baseUrl;
const baseUrlFormatted = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
const fullUrl = `${baseUrlFormatted}/api/v2/delete-webhook`;
const response = await this.helpers.httpRequest({
url: fullUrl,
method: 'POST',
body: {
url: webhookUrl,
chatbotId,
},
headers: {
Authorization: `Bearer ${credentials.apiKey}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
json: true,
ignoreHttpStatusErrors: true,
});
if (response.status === 'error') {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), response.message, { itemIndex: 0 });
}
delete webhookData.chatbotId;
delete webhookData.eventType;
delete webhookData.webhookUrl;
delete webhookData.isPersistent;
return true;
}
return false;
}
catch (error) {
throw error;
}
},
},
};
}
async webhook() {
let bodyData;
try {
const rawBody = this.getRequestObject().rawBody;
bodyData = JSON.parse(rawBody.toString());
}
catch (error) {
}
const operation = this.getNodeParameter('operation', 0);
if (operation === 'onLeadSubmission' && bodyData.event !== 'lead-submission') {
return {};
}
else if (operation === 'onLiveChatEscalation' && bodyData.event !== 'live-chat-escalation') {
return {};
}
else if (operation === 'onNewMessage' && bodyData.event !== 'chat') {
return {};
}
const chatbotId = bodyData.chatbot_id;
const configuredChatbotId = this.getNodeParameter('chatbot_id', '');
if (configuredChatbotId && chatbotId !== configuredChatbotId) {
return {};
}
return {
workflowData: [this.helpers.returnJsonArray([{
...bodyData,
pairedItem: {
item: 0,
input: 0
}
}])]
};
}
async execute() {
var _a, _b;
const items = this.getInputData();
const returnData = [];
const operation = this.getNodeParameter('operation', 0);
const webhookData = this.getWorkflowStaticData('node');
if (operation === 'onLeadSubmission' || operation === 'onLiveChatEscalation' || operation === 'onNewMessage') {
let incomingData;
if (items.length === 0 && webhookData.setupInfo) {
const setupInfo = webhookData.setupInfo;
incomingData = {
webhookSetup: {
status: 'success',
message: 'Webhook registered successfully. Waiting for events...',
response: setupInfo.response,
chatbotId: setupInfo.chatbotId,
eventType: setupInfo.eventType,
webhookUrl: setupInfo.webhookUrl,
createdAt: setupInfo.createdAt
},
};
}
else if (typeof ((_a = items[0]) === null || _a === void 0 ? void 0 : _a.json) === 'object' && items[0].json !== null) {
incomingData = items[0].json;
}
else if ((_b = items[0]) === null || _b === void 0 ? void 0 : _b.json) {
try {
incomingData = JSON.parse(String(items[0].json));
}
catch (error) {
incomingData = {
data: items[0].json,
parseError: 'Could not parse incoming data as JSON'
};
}
}
else {
incomingData = {
status: 'waiting',
message: 'Waiting for webhook data...',
webhookInfo: webhookData.setupInfo || {
eventType: webhookData.eventType,
chatbotId: webhookData.chatbotId,
webhookUrl: webhookData.webhookUrl,
},
};
}
const newItem = {
json: incomingData,
};
returnData.push(newItem);
}
else {
for (let i = 0; i < items.length; i++) {
try {
const pollInterval = this.getNodeParameter('pollInterval', i);
const newItem = {
json: {
...items[i].json,
success: true,
operation,
pollInterval,
},
};
returnData.push(newItem);
}
catch (error) {
let errorMessage = error.message;
if (error.response && error.response.body) {
const responseBody = error.response.body;
if (typeof responseBody === 'object' && responseBody.message) {
errorMessage = responseBody.message;
}
else if (typeof responseBody === 'string') {
try {
const parsedBody = JSON.parse(responseBody);
if (parsedBody.message) {
errorMessage = parsedBody.message;
}
}
catch (e) {
}
}
}
if (this.continueOnFail()) {
returnData.push({
json: {
...items[i].json,
error: errorMessage,
},
pairedItem: i,
});
continue;
}
throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage, { itemIndex: i });
}
}
}
return [returnData.length ? returnData : items];
}
}
exports.ChatDataTrigger = ChatDataTrigger;
//# sourceMappingURL=ChatDataTrigger.node.js.map