n8n-nodes-instagram-integrations
Version:
N8N nodes for Instagram API integration with OAuth2 authentication
257 lines • 11.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.InstagramTrigger = void 0;
const n8n_workflow_1 = require("n8n-workflow");
const GenericFunctions_1 = require("./GenericFunctions");
class InstagramTrigger {
constructor() {
this.description = {
displayName: 'Instagram Trigger',
name: 'instagramTrigger',
icon: 'file:instagram-large.svg',
group: ['trigger'],
version: 1,
description: 'Triggers workflow on Instagram webhook events (messages, postbacks, etc.)',
defaults: {
name: 'Instagram Trigger',
},
inputs: [],
outputs: [
{ type: 'main', displayName: 'Messages' },
{ type: 'main', displayName: 'Postbacks' },
{ type: 'main', displayName: 'Opt-ins' },
{ type: 'main', displayName: 'Comments' },
{ type: 'main', displayName: 'Mentions' },
],
credentials: [
{
name: 'instagramOAuth2Api',
required: true,
},
],
webhooks: [
{
name: 'setup',
httpMethod: 'GET',
responseMode: 'onReceived',
path: 'webhook',
},
{
name: 'default',
httpMethod: 'POST',
responseMode: 'onReceived',
path: 'webhook',
},
],
properties: [
{
displayName: 'Events',
name: 'events',
type: 'multiOptions',
options: [
{
name: 'Comments',
value: 'comments',
description: 'Trigger when someone comments on your media',
},
{
name: 'Mentions',
value: 'mentions',
description: 'Trigger when someone mentions you in a comment or story',
},
{
name: 'Messages',
value: 'messages',
description: 'Trigger on new messages received',
},
{
name: 'Opt-Ins',
value: 'messaging_optins',
description: 'Trigger when user opts in',
},
{
name: 'Postbacks',
value: 'messaging_postbacks',
description: 'Trigger when user clicks a button',
},
],
default: ['messages'],
description: 'The events to listen to',
},
{
displayName: 'Ignore Echo Messages',
name: 'ignoreEcho',
type: 'boolean',
default: true,
description: 'Whether to ignore echo messages (messages sent by your own bot)',
displayOptions: {
show: {
events: ['messages'],
},
},
},
{
displayName: 'To set up the webhook, you need to configure it in your Meta App Dashboard. Use this webhook URL in the callback URL field.',
name: 'notice',
type: 'notice',
default: '',
},
],
};
this.webhookMethods = {
default: {
async checkExists() {
return true;
},
async create() {
return true;
},
async delete() {
return true;
},
},
setup: {
async checkExists() {
return true;
},
async create() {
return true;
},
async delete() {
return true;
},
},
};
}
async webhook() {
const req = this.getRequestObject();
const query = this.getQueryData();
const headerData = this.getHeaderData();
const bodyData = this.getBodyData();
const credentials = await this.getCredentials('instagramOAuth2Api');
if (req.method === 'GET') {
const mode = query['hub.mode'];
const token = query['hub.verify_token'];
const challenge = query['hub.challenge'];
const verifyToken = credentials.webhookVerifyToken;
if (mode === 'subscribe' && token === verifyToken) {
return {
webhookResponse: challenge,
};
}
else {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Webhook verification failed: Invalid verify token');
}
}
if (req.method === 'POST') {
const signature = headerData['x-hub-signature-256'];
const appSecret = credentials.clientSecret;
if (!signature) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Webhook authentication failed: No signature provided');
}
const isValid = (0, GenericFunctions_1.validateSignature)(JSON.stringify(bodyData), signature, appSecret);
if (!isValid) {
console.warn('Invalid signature detected, but continuing for testing purposes.');
}
const webhookData = bodyData;
const messagesData = [];
const postbacksData = [];
const optinsData = [];
const commentsData = [];
const mentionsData = [];
const events = this.getNodeParameter('events', []);
const ignoreEcho = this.getNodeParameter('ignoreEcho', true);
for (const entry of webhookData.entry || []) {
if (entry.messaging) {
for (const messagingEvent of entry.messaging) {
const data = {
senderId: messagingEvent.sender.id,
recipientId: messagingEvent.recipient.id,
timestamp: messagingEvent.timestamp,
entryId: entry.id,
};
if (messagingEvent.message && events.includes('messages')) {
const isEcho = messagingEvent.message.is_echo || false;
if (ignoreEcho && isEcho) {
continue;
}
data.eventType = 'message';
data.messageId = messagingEvent.message.mid;
data.text = messagingEvent.message.text;
data.attachments = messagingEvent.message.attachments;
if (messagingEvent.message.quick_reply) {
data.quickReplyPayload = messagingEvent.message.quick_reply.payload;
}
data.isEcho = isEcho;
messagesData.push({ json: data });
}
if (messagingEvent.postback && events.includes('messaging_postbacks')) {
data.eventType = 'postback';
data.payload = messagingEvent.postback.payload;
data.title = messagingEvent.postback.title;
postbacksData.push({ json: data });
}
if (messagingEvent.optin && events.includes('messaging_optins')) {
data.eventType = 'optin';
data.ref = messagingEvent.optin.ref;
optinsData.push({ json: data });
}
}
}
if (entry.changes) {
for (const change of entry.changes) {
if (change.field === 'comments' && events.includes('comments')) {
const commentValue = change.value;
const data = {
eventType: 'comment',
commentId: commentValue.id,
text: commentValue.text,
mediaId: commentValue.media.id,
mediaProductType: commentValue.media.media_product_type,
fromUserId: commentValue.from.id,
fromUsername: commentValue.from.username,
entryId: entry.id,
timestamp: entry.time,
};
if (commentValue.parent_id) {
data.parentCommentId = commentValue.parent_id;
data.isReply = true;
}
else {
data.isReply = false;
}
commentsData.push({ json: data });
}
if (change.field === 'mentions' && events.includes('mentions')) {
const mentionValue = change.value;
const data = {
eventType: 'mention',
mentionId: mentionValue.id,
mediaId: mentionValue.media_id,
entryId: entry.id,
timestamp: entry.time,
};
if (mentionValue.comment_id) {
data.commentId = mentionValue.comment_id;
data.mentionType = 'comment';
}
else {
data.mentionType = 'story';
}
if (mentionValue.text) {
data.text = mentionValue.text;
}
mentionsData.push({ json: data });
}
}
}
}
return {
workflowData: [messagesData, postbacksData, optinsData, commentsData, mentionsData],
};
}
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Method not allowed');
}
}
exports.InstagramTrigger = InstagramTrigger;
//# sourceMappingURL=InstagramTrigger.node.js.map