AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(instagram-business): revive on Graph v23.0 with 27 verified actions (#15618)
Odai Ahmadfa8d0c3aabfd
diff --git a/bun.lock b/bun.lockindex 3f65229e60a..4e12133c35b 100644--- a/bun.lock+++ b/bun.lock@@ -4557,7 +4557,7 @@},"packages/pieces/community/instagram-business": {"name": "@activepieces/piece-instagram-business",- "version": "0.2.7",+ "version": "1.0.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/docs/install/reference/breaking-changes.mdx b/docs/install/reference/breaking-changes.mdxindex 976ecd85ce2..c700014f177 100644--- a/docs/install/reference/breaking-changes.mdx+++ b/docs/install/reference/breaking-changes.mdx@@ -8,6 +8,20 @@ icon: "hammer"### What has changed?+#### Instagram for Business no longer reports success when a reel fails to publish++Publishing a reel uploads the video to Instagram and then waits for Instagram to finish processing it before the post goes live. The piece used to give up after about a hundred seconds and return the boolean `false`, which the flow recorded as a **successful** step. Anything downstream carried on with `false` where a media id was expected, and nothing in the run said the post had not been published.++Upload Reel now throws when Instagram reports an error, and waits up to five minutes, which is the window Instagram's own guidance describes. Upload Photo waits for the same signal instead of publishing blind, so a container Instagram rejects now surfaces as a failed step rather than a confusing error from the next call.++The piece also moves from Graph API v17.0, which expired on 12 September 2025, to v23.0.++#### What you need to do++If a flow branches on the output of Upload Reel being `false`, that branch will no longer be taken — the step fails instead. Handle the failure with the step's error handling options, or with a branch on the run status.++Reconnect your Instagram connections. The piece now requests the permissions needed for comments, insights, content management, direct messages and Page metadata, and a token issued before this release does not carry them. Steps that were saved earlier will also ask you to select the Page again, because messaging needs the Facebook Page id that the Page dropdown now stores.+#### The AI provider config endpoint is removed`GET /v1/ai-providers/:provider/config` returned a provider's decrypted credentials so that an AI step running inside the engine could build the model itself and call the provider directly. AI steps no longer work that way: the worker resolves the credentials and makes the call, which is what lets Activepieces charge managed AI on what the call actually cost. Nothing in the product calls the endpoint any more, and it now returns `404`.diff --git a/packages/pieces/community/instagram-business/package.json b/packages/pieces/community/instagram-business/package.jsonindex d7576ef74f0..a8e7abf33d2 100644--- a/packages/pieces/community/instagram-business/package.json+++ b/packages/pieces/community/instagram-business/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-instagram-business",- "version": "0.2.7",+ "version": "1.0.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {diff --git a/packages/pieces/community/instagram-business/src/i18n/translation.json b/packages/pieces/community/instagram-business/src/i18n/translation.jsonindex bc4ae37179b..fa1e4165967 100644--- a/packages/pieces/community/instagram-business/src/i18n/translation.json+++ b/packages/pieces/community/instagram-business/src/i18n/translation.json@@ -1,14 +1,105 @@{"Grow your business on Instagram": "Grow your business on Instagram",- "\nTo Obtain the following credentials:\n1. Visit https://developers.facebook.com/\n2. Create an application, Select Other for Usecase.\n3. Select Business as App Type.\n4. Copy App Id and App Secret from Basic Settings.\n": "\nTo Obtain the following credentials:\n1. Visit https://developers.facebook.com/\n2. Create an application, Select Other for Usecase.\n3. Select Business as App Type.\n4. Copy App Id and App Secret from Basic Settings.\n",+ "\n**Use the Facebook App ID and App Secret — not the Instagram ones.**\n\n1. Visit https://developers.facebook.com/ and create an app.\n2. Choose **Other** as the use case, then **Business** as the app type. Any other\n combination leaves the app without the Instagram permissions this piece requests.\n3. Add the **Facebook Login for Business** product.\n4. Copy the **App ID** and **App Secret** from **Settings → Basic**.\n\nThe Instagram product page shows a separate *Instagram app ID* and *Instagram app secret*.\n": "\n**Use the Facebook App ID and App Secret — not the Instagram ones.**\n\n1. Visit https://developers.facebook.com/ and create an app.\n2. Choose **Other** as the use case, then **Business** as the app type. Any other\n combination leaves the app without the Instagram permissions this piece requests.\n3. Add the **Facebook Login for Business** product.\n4. Copy the **App ID** and **App Secret** from **Settings → Basic**.\n\nThe Instagram product page shows a separate *Instagram app ID* and *Instagram app secret*.\nThose belong to Instagram Login and will not work here — this piece uses Facebook Login.\n\nYour Instagram account must be a Business or Creator account linked to a Facebook Page.\n","Upload Photo": "Upload Photo","Upload Reel": "Upload Reel",+ "Publish Story": "Publish Story",+ "Publish Carousel": "Publish Carousel",+ "Get Profile": "Get Profile",+ "Get Account Insights": "Get Account Insights",+ "Get Content Publishing Limit": "Get Content Publishing Limit",+ "List Media": "List Media",+ "Get Media": "Get Media",+ "Get Media Insights": "Get Media Insights",+ "List Carousel Children": "List Carousel Children",+ "List Stories": "List Stories",+ "List Tagged Media": "List Tagged Media",+ "Delete Media": "Delete Media",+ "Enable or Disable Comments": "Enable or Disable Comments",+ "List Comments": "List Comments",+ "Get Comment": "Get Comment",+ "List Comment Replies": "List Comment Replies",+ "Create Comment": "Create Comment",+ "Reply To Comment": "Reply To Comment",+ "Hide or Unhide Comment": "Hide or Unhide Comment",+ "Delete Comment": "Delete Comment",+ "List Conversations": "List Conversations",+ "List Messages": "List Messages",+ "Send Message": "Send Message",+ "Send Media Message": "Send Media Message",+ "Send Private Reply": "Send Private Reply","Upload a photo to an Instagram Professional Account": "Upload a photo to an Instagram Professional Account","Upload a reel to an Instagram Professional Account": "Upload a reel to an Instagram Professional Account",+ "Publish a photo or video story to an Instagram professional account.": "Publish a photo or video story to an Instagram professional account.",+ "Publish a carousel album of up to 10 photos or videos.": "Publish a carousel album of up to 10 photos or videos.",+ "Read the profile of the connected Instagram professional account.": "Read the profile of the connected Instagram professional account.",+ "Read reach, views and interaction metrics for the account.": "Read reach, views and interaction metrics for the account.",+ "Check how many posts the account has published in the last 24 hours.": "Check how many posts the account has published in the last 24 hours.",+ "List posts published by the connected Instagram account.": "List posts published by the connected Instagram account.",+ "Read a single Instagram post by its id.": "Read a single Instagram post by its id.",+ "Read reach, likes and comment metrics for one post.": "Read reach, likes and comment metrics for one post.",+ "List the individual items inside a carousel album post.": "List the individual items inside a carousel album post.",+ "List the stories currently live on the connected Instagram account.": "List the stories currently live on the connected Instagram account.",+ "List posts by other accounts that tagged this account.": "List posts by other accounts that tagged this account.",+ "Permanently delete one of your Instagram posts.": "Permanently delete one of your Instagram posts.",+ "Turn commenting on or off for one post.": "Turn commenting on or off for one post.",+ "List the top-level comments on one Instagram post.": "List the top-level comments on one Instagram post.",+ "Read a single comment by its id.": "Read a single comment by its id.",+ "List the replies to one comment.": "List the replies to one comment.",+ "Post a comment on one of your Instagram posts.": "Post a comment on one of your Instagram posts.",+ "Reply to a comment on one of your Instagram posts.": "Reply to a comment on one of your Instagram posts.",+ "Hide a comment from public view, or unhide it again.": "Hide a comment from public view, or unhide it again.",+ "Permanently delete a comment.": "Permanently delete a comment.",+ "List Instagram direct message threads for the account.": "List Instagram direct message threads for the account.",+ "Read the messages inside one direct message thread.": "Read the messages inside one direct message thread.",+ "Send a direct message to an Instagram user.": "Send a direct message to an Instagram user.",+ "Send an image, video or audio file as a direct message.": "Send an image, video or audio file as a direct message.",+ "Reply privately by direct message to someone who commented.": "Reply privately by direct message to someone who commented.","Page": "Page","Photo": "Photo","Caption": "Caption","Video": "Video",+ "Photo URL": "Photo URL",+ "Video URL": "Video URL",+ "Items": "Items",+ "Metrics": "Metrics",+ "Period": "Period",+ "Limit": "Limit",+ "Cursor": "Cursor",+ "Media ID": "Media ID",+ "Carousel Media ID": "Carousel Media ID",+ "Comments Enabled": "Comments Enabled",+ "Comment ID": "Comment ID",+ "Parent Comment ID": "Parent Comment ID",+ "Comment": "Comment",+ "Reply": "Reply",+ "Hidden": "Hidden",+ "Conversation ID": "Conversation ID",+ "Recipient ID": "Recipient ID",+ "Message": "Message",+ "Media Type": "Media Type",+ "Media URL": "Media URL","A URL we can access for the photo (JPG only)": "A URL we can access for the photo (JPG only)",- "A URL we can access for the video (Limit: 1GB or 15 minutes)": "A URL we can access for the video (Limit: 1GB or 15 minutes)"+ "A URL we can access for the video (Limit: 1GB or 15 minutes)": "A URL we can access for the video (Limit: 1GB or 15 minutes)",+ "Public URL of a JPG image. Leave empty when publishing a video story.": "Public URL of a JPG image. Leave empty when publishing a video story.",+ "Public URL of a video. Leave empty when publishing a photo story.": "Public URL of a video. Leave empty when publishing a photo story.",+ "Between 2 and 10 photos or videos, in the order they should appear.": "Between 2 and 10 photos or videos, in the order they should appear.",+ "Metric names, for example reach or profile_views. Defaults to reach.": "Metric names, for example reach or profile_views. Defaults to reach.",+ "Maximum number of posts to return (default 25).": "Maximum number of posts to return (default 25).",+ "Next Cursor from a previous run, to fetch the following page.": "Next Cursor from a previous run, to fetch the following page.",+ "The id of the post, as returned by List Media or a publish action.": "The id of the post, as returned by List Media or a publish action.",+ "Metric names. Defaults to reach, likes and comments (reach, replies and shares for stories).": "Metric names. Defaults to reach, likes and comments (reach, replies and shares for stories).",+ "The id of a post whose media type is CAROUSEL_ALBUM.": "The id of a post whose media type is CAROUSEL_ALBUM.",+ "Maximum number of comments to return (default 25).": "Maximum number of comments to return (default 25).",+ "On hides the comment, off makes it visible again.": "On hides the comment, off makes it visible again.",+ "From List Conversations.": "From List Conversations.",+ "The Instagram-scoped user id of the person to message.": "The Instagram-scoped user id of the person to message.",+ "Publicly reachable URL of the file. Instagram fetches it server side and rejects some hosts with an upload error, so prefer a plain static file URL.": "Publicly reachable URL of the file. Instagram fetches it server side and rejects some hosts with an upload error, so prefer a plain static file URL.",+ "The comment whose author should receive the direct message.": "The comment whose author should receive the direct message.",+ "Day": "Day",+ "Week": "Week",+ "28 Days": "28 Days",+ "Lifetime": "Lifetime",+ "Image": "Image",+ "Audio": "Audio"}\ No newline at end of filediff --git a/packages/pieces/community/instagram-business/src/index.ts b/packages/pieces/community/instagram-business/src/index.tsindex 9ecbf8964f2..6ed54aea01d 100644--- a/packages/pieces/community/instagram-business/src/index.ts+++ b/packages/pieces/community/instagram-business/src/index.ts@@ -1,17 +1,70 @@import { createPiece } from '@activepieces/pieces-framework';import { PieceCategory } from '@activepieces/pieces-framework';-import { uploadPhoto } from './lib/actions/upload-photo';-import { uploadReel } from './lib/actions/upload-reel';+import { getAccountInsights } from './lib/actions/account/get-account-insights';+import { getContentPublishingLimit } from './lib/actions/account/get-content-publishing-limit';+import { getProfile } from './lib/actions/account/get-profile';+import { createComment } from './lib/actions/comments/create-comment';+import { deleteComment } from './lib/actions/comments/delete-comment';+import { getComment } from './lib/actions/comments/get-comment';+import { listCommentReplies } from './lib/actions/comments/list-comment-replies';+import { listMediaComments } from './lib/actions/comments/list-media-comments';+import { replyToComment } from './lib/actions/comments/reply-to-comment';+import { setCommentVisibility } from './lib/actions/comments/set-comment-visibility';+import { deleteMedia } from './lib/actions/media/delete-media';+import { getMedia } from './lib/actions/media/get-media';+import { getMediaInsights } from './lib/actions/media/get-media-insights';+import { listCarouselChildren } from './lib/actions/media/list-carousel-children';+import { listMedia } from './lib/actions/media/list-media';+import { listStories } from './lib/actions/media/list-stories';+import { listTaggedMedia } from './lib/actions/media/list-tagged-media';+import { setMediaCommentsEnabled } from './lib/actions/media/set-media-comments-enabled';+import { listConversations } from './lib/actions/messaging/list-conversations';+import { listMessages } from './lib/actions/messaging/list-messages';+import { sendMediaMessage } from './lib/actions/messaging/send-media-message';+import { sendMessage } from './lib/actions/messaging/send-message';+import { sendPrivateReply } from './lib/actions/messaging/send-private-reply';+import { publishCarousel } from './lib/actions/publishing/publish-carousel';+import { publishStory } from './lib/actions/publishing/publish-story';+import { uploadPhoto } from './lib/actions/publishing/upload-photo';+import { uploadReel } from './lib/actions/publishing/upload-reel';import { instagramCommon } from './lib/common';export const instagramBusiness = createPiece({displayName: 'Instagram for Business',description: 'Grow your business on Instagram',- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.87.0',logoUrl: 'https://cdn.activepieces.com/pieces/instagram.png',categories: [PieceCategory.BUSINESS_INTELLIGENCE],authors: ["kishanprmr","MoShizzle","abuaboud"],auth: instagramCommon.authentication,- actions: [uploadPhoto, uploadReel],+ actions: [+ uploadPhoto,+ uploadReel,+ publishStory,+ publishCarousel,+ getProfile,+ getAccountInsights,+ getContentPublishingLimit,+ listMedia,+ getMedia,+ getMediaInsights,+ listCarouselChildren,+ listStories,+ listTaggedMedia,+ deleteMedia,+ setMediaCommentsEnabled,+ listMediaComments,+ getComment,+ listCommentReplies,+ createComment,+ replyToComment,+ setCommentVisibility,+ deleteComment,+ listConversations,+ listMessages,+ sendMessage,+ sendMediaMessage,+ sendPrivateReply,+ ],triggers: [],});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/account/get-account-insights.ts b/packages/pieces/community/instagram-business/src/lib/actions/account/get-account-insights.tsnew file mode 100644index 00000000000..565fbc89a23--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/account/get-account-insights.ts@@ -0,0 +1,61 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { insightsOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown, parseArrayProp } from '../../common';++export const getAccountInsights = createAction({+ auth: instagramCommon.authentication,+ outputSchema: insightsOutputSchema,+ name: 'get_account_insights',+ classification: 'READ',+ displayName: 'Get Account Insights',+ description: 'Read reach, views and interaction metrics for the account.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Reads account-level Instagram metrics such as reach, profile views and accounts engaged, over a chosen period. Metrics cover professional accounts only and lag real time by a few hours, so a very recent post may not be reflected yet. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ metrics: Property.Array({+ displayName: 'Metrics',+ description: 'Metric names, for example reach or profile_views. Defaults to reach.',+ required: false,+ }),+ period: Property.StaticDropdown({+ displayName: 'Period',+ required: false,+ defaultValue: 'day',+ options: {+ options: [+ { label: 'Day', value: 'day' },+ { label: 'Week', value: 'week' },+ { label: '28 Days', value: 'days_28' },+ { label: 'Lifetime', value: 'lifetime' },+ ],+ },+ }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;+ const metrics = parseArrayProp(propsValue.metrics)+ .map((metric) => String(metric))+ .filter((metric) => metric.length > 0);++ const response = await instagramCommon.graphRequest<{ data?: unknown[] }>({+ method: HttpMethod.GET,+ resourceUri: `/${page.id}/insights`,+ accessToken: page.accessToken,+ query: {+ metric: metrics.length > 0 ? metrics.join(',') : 'reach',+ period: propsValue.period ?? 'day',+ metric_type: 'total_value',+ },+ });++ const insights = response.data ?? [];+ return { insights, count: insights.length };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/account/get-content-publishing-limit.ts b/packages/pieces/community/instagram-business/src/lib/actions/account/get-content-publishing-limit.tsnew file mode 100644index 00000000000..7f04161b766--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/account/get-content-publishing-limit.ts@@ -0,0 +1,46 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';++import { getContentPublishingLimitOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const getContentPublishingLimit = createAction({+ auth: instagramCommon.authentication,+ outputSchema: getContentPublishingLimitOutputSchema,+ name: 'get_content_publishing_limit',+ classification: 'READ',+ displayName: 'Get Content Publishing Limit',+ description: 'Check how many posts the account has published in the last 24 hours.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Reads how much of the Instagram publishing quota the account has consumed in the rolling 24 hour window. Instagram allows 100 API-published posts per 24 hours, and a carousel counts as one. Call this before a batch of posts to avoid hitting the cap mid-run. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const response = await instagramCommon.graphRequest<{+ data?: { quota_usage?: number; config?: { quota_total?: number; quota_duration?: number } }[];+ }>({+ method: HttpMethod.GET,+ resourceUri: `/${page.id}/content_publishing_limit`,+ accessToken: page.accessToken,+ query: { fields: 'config,quota_usage' },+ });++ const entry = response.data?.[0];+ const quotaUsage = entry?.quota_usage ?? 0;+ const quotaTotal = entry?.config?.quota_total ?? 100;++ return {+ quota_usage: quotaUsage,+ quota_total: quotaTotal,+ quota_remaining: Math.max(quotaTotal - quotaUsage, 0),+ quota_duration_seconds: entry?.config?.quota_duration,+ };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/account/get-profile.ts b/packages/pieces/community/instagram-business/src/lib/actions/account/get-profile.tsnew file mode 100644index 00000000000..fdcd9307525--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/account/get-profile.ts@@ -0,0 +1,48 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';++import { getProfileOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const getProfile = createAction({+ auth: instagramCommon.authentication,+ outputSchema: getProfileOutputSchema,+ name: 'get_profile',+ classification: 'READ',+ displayName: 'Get Profile',+ description: 'Read the profile of the connected Instagram professional account.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Reads the profile of one Instagram professional account: username, name, biography, website, profile picture, follower count, follows count and total media count. Use it to identify the connected account or to check follower numbers. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ return instagramCommon.graphRequest<InstagramProfile>({+ method: HttpMethod.GET,+ resourceUri: `/${page.id}`,+ accessToken: page.accessToken,+ query: {+ fields:+ 'id,username,name,biography,website,profile_picture_url,followers_count,follows_count,media_count',+ },+ });+ },+});++type InstagramProfile = {+ id: string;+ username?: string;+ name?: string;+ biography?: string;+ website?: string;+ profile_picture_url?: string;+ followers_count?: number;+ follows_count?: number;+ media_count?: number;+};diff --git a/packages/pieces/community/instagram-business/src/lib/actions/comments/create-comment.ts b/packages/pieces/community/instagram-business/src/lib/actions/comments/create-comment.tsnew file mode 100644index 00000000000..074e44c21ae--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/comments/create-comment.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { commentCreatedOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const createComment = createAction({+ auth: instagramCommon.authentication,+ outputSchema: commentCreatedOutputSchema,+ name: 'create_comment',+ classification: 'WRITE',+ displayName: 'Create Comment',+ description: 'Post a comment on one of your Instagram posts.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Posts a new top-level comment on one of the connected account\u2019s own Instagram posts. To answer an existing comment use Reply To Comment instead, which threads the response. Not idempotent — each call posts another comment.',+ idempotent: false,+ },+ props: {+ page: instagramCommon.page,+ media_id: Property.ShortText({ displayName: 'Media ID', required: true }),+ message: Property.LongText({ displayName: 'Comment', required: true }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const created = await instagramCommon.graphRequest<{ id?: string }>({+ method: HttpMethod.POST,+ resourceUri: `/${propsValue.media_id}/comments`,+ accessToken: page.accessToken,+ body: { message: propsValue.message },+ });++ return { id: created.id, media_id: propsValue.media_id };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/comments/delete-comment.ts b/packages/pieces/community/instagram-business/src/lib/actions/comments/delete-comment.tsnew file mode 100644index 00000000000..313038bc1fd--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/comments/delete-comment.ts@@ -0,0 +1,35 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { identifierResultOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const deleteComment = createAction({+ auth: instagramCommon.authentication,+ outputSchema: identifierResultOutputSchema,+ name: 'delete_comment',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Comment',+ description: 'Permanently delete a comment.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Permanently deletes one Instagram comment by its id. This cannot be undone, and only comments on the connected account\u2019s own media can be deleted. To silence a comment reversibly, use Hide Comment instead. Not idempotent — deleting an already deleted comment fails.',+ idempotent: false,+ },+ props: {+ page: instagramCommon.page,+ comment_id: Property.ShortText({ displayName: 'Comment ID', required: true }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const result = await instagramCommon.graphRequest<{ success?: boolean }>({+ method: HttpMethod.DELETE,+ resourceUri: `/${propsValue.comment_id}`,+ accessToken: page.accessToken,+ });++ return { success: result.success ?? true, id: propsValue.comment_id };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/comments/get-comment.ts b/packages/pieces/community/instagram-business/src/lib/actions/comments/get-comment.tsnew file mode 100644index 00000000000..f6196ebf684--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/comments/get-comment.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { getCommentOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown, COMMENT_FIELDS } from '../../common';++export const getComment = createAction({+ auth: instagramCommon.authentication,+ outputSchema: getCommentOutputSchema,+ name: 'get_comment',+ classification: 'READ',+ displayName: 'Get Comment',+ description: 'Read a single comment by its id.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Reads one Instagram comment by its id, returning its text, author, timestamp, like count, hidden state and the media it belongs to. Use it after a New Comment trigger or List Comments. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ comment_id: Property.ShortText({+ displayName: 'Comment ID',+ required: true,+ }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ return instagramCommon.graphRequest({+ method: HttpMethod.GET,+ resourceUri: `/${propsValue.comment_id}`,+ accessToken: page.accessToken,+ query: { fields: COMMENT_FIELDS },+ });+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/comments/list-comment-replies.ts b/packages/pieces/community/instagram-business/src/lib/actions/comments/list-comment-replies.tsnew file mode 100644index 00000000000..16c82d3b31b--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/comments/list-comment-replies.ts@@ -0,0 +1,40 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { listCommentsOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown, COMMENT_FIELDS } from '../../common';++export const listCommentReplies = createAction({+ auth: instagramCommon.authentication,+ outputSchema: listCommentsOutputSchema,+ name: 'list_comment_replies',+ classification: 'SEARCH',+ displayName: 'List Comment Replies',+ description: 'List the replies to one comment.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the replies made to one Instagram comment, given the parent comment id. A comment with no replies returns an empty list. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ comment_id: Property.ShortText({+ displayName: 'Parent Comment ID',+ required: true,+ }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const response = await instagramCommon.graphRequest<{ data?: unknown[] }>({+ method: HttpMethod.GET,+ resourceUri: `/${propsValue.comment_id}/replies`,+ accessToken: page.accessToken,+ query: { fields: COMMENT_FIELDS },+ });++ const comments = response.data ?? [];+ return { comments, count: comments.length };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/comments/list-media-comments.ts b/packages/pieces/community/instagram-business/src/lib/actions/comments/list-media-comments.tsnew file mode 100644index 00000000000..be25de568d7--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/comments/list-media-comments.ts@@ -0,0 +1,57 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { listCommentsOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown, GraphPaging, COMMENT_FIELDS } from '../../common';++export const listMediaComments = createAction({+ auth: instagramCommon.authentication,+ outputSchema: listCommentsOutputSchema,+ name: 'list_media_comments',+ classification: 'SEARCH',+ displayName: 'List Comments',+ description: 'List the top-level comments on one Instagram post.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the top-level comments on one Instagram post, with author, text, timestamp, like count and whether the comment is hidden. Replies are not included — use List Comment Replies for those. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ media_id: Property.ShortText({+ displayName: 'Media ID',+ required: true,+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Maximum number of comments to return (default 25).',+ required: false,+ }),+ cursor: instagramCommon.cursor,+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const response = await instagramCommon.graphRequest<{+ data?: unknown[];+ paging?: GraphPaging;+ }>({+ method: HttpMethod.GET,+ resourceUri: `/${propsValue.media_id}/comments`,+ accessToken: page.accessToken,+ query: {+ fields: COMMENT_FIELDS,+ limit: propsValue.limit ?? 25,+ after: propsValue.cursor,+ },+ });++ const comments = response.data ?? [];+ return {+ comments,+ count: comments.length,+ next_cursor: instagramCommon.nextCursor(response.paging),+ };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/comments/reply-to-comment.ts b/packages/pieces/community/instagram-business/src/lib/actions/comments/reply-to-comment.tsnew file mode 100644index 00000000000..a29f129f0b4--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/comments/reply-to-comment.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { commentCreatedOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const replyToComment = createAction({+ auth: instagramCommon.authentication,+ outputSchema: commentCreatedOutputSchema,+ name: 'reply_to_comment',+ classification: 'WRITE',+ displayName: 'Reply To Comment',+ description: 'Reply to a comment on one of your Instagram posts.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Replies to an existing Instagram comment, threading the response underneath it. Instagram supports only one level of threading, so replying to a reply attaches the response to the same parent. Not idempotent — each call posts another reply.',+ idempotent: false,+ },+ props: {+ page: instagramCommon.page,+ comment_id: Property.ShortText({ displayName: 'Comment ID', required: true }),+ message: Property.LongText({ displayName: 'Reply', required: true }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const created = await instagramCommon.graphRequest<{ id?: string }>({+ method: HttpMethod.POST,+ resourceUri: `/${propsValue.comment_id}/replies`,+ accessToken: page.accessToken,+ body: { message: propsValue.message },+ });++ return { id: created.id, parent_id: propsValue.comment_id };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/comments/set-comment-visibility.ts b/packages/pieces/community/instagram-business/src/lib/actions/comments/set-comment-visibility.tsnew file mode 100644index 00000000000..c0ce820084d--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/comments/set-comment-visibility.ts@@ -0,0 +1,42 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { identifierResultOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const setCommentVisibility = createAction({+ auth: instagramCommon.authentication,+ outputSchema: identifierResultOutputSchema,+ name: 'set_comment_visibility',+ classification: 'WRITE',+ displayName: 'Hide or Unhide Comment',+ description: 'Hide a comment from public view, or unhide it again.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Hides an Instagram comment from everyone except its author, or unhides a previously hidden one, controlled by the Hidden toggle. Unlike Delete Comment this is reversible and the comment is not destroyed. Idempotent — setting the same state twice leaves the comment unchanged.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ comment_id: Property.ShortText({ displayName: 'Comment ID', required: true }),+ hidden: Property.Checkbox({+ displayName: 'Hidden',+ description: 'On hides the comment, off makes it visible again.',+ required: true,+ defaultValue: true,+ }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const result = await instagramCommon.graphRequest<{ success?: boolean }>({+ method: HttpMethod.POST,+ resourceUri: `/${propsValue.comment_id}`,+ accessToken: page.accessToken,+ body: { hide: propsValue.hidden },+ });++ return { success: result.success ?? true, id: propsValue.comment_id };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/media/delete-media.ts b/packages/pieces/community/instagram-business/src/lib/actions/media/delete-media.tsnew file mode 100644index 00000000000..aaddfb33794--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/media/delete-media.ts@@ -0,0 +1,35 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { identifierResultOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const deleteMedia = createAction({+ auth: instagramCommon.authentication,+ outputSchema: identifierResultOutputSchema,+ name: 'delete_media',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Media',+ description: 'Permanently delete one of your Instagram posts.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Permanently deletes one Instagram post, story, reel or whole carousel album belonging to the connected account. Individual items inside a carousel cannot be deleted, only the album as a whole, and the deletion cannot be undone. Not idempotent, since deleting an already deleted post fails.',+ idempotent: false,+ },+ props: {+ page: instagramCommon.page,+ media_id: Property.ShortText({ displayName: 'Media ID', required: true }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const result = await instagramCommon.graphRequest<{ success?: boolean }>({+ method: HttpMethod.DELETE,+ resourceUri: `/${propsValue.media_id}`,+ accessToken: page.accessToken,+ });++ return { success: result.success ?? true, id: propsValue.media_id };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/media/get-media-insights.ts b/packages/pieces/community/instagram-business/src/lib/actions/media/get-media-insights.tsnew file mode 100644index 00000000000..2302f3b8056--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/media/get-media-insights.ts@@ -0,0 +1,66 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { insightsOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown, parseArrayProp } from '../../common';++export const getMediaInsights = createAction({+ auth: instagramCommon.authentication,+ outputSchema: insightsOutputSchema,+ name: 'get_media_insights',+ classification: 'READ',+ displayName: 'Get Media Insights',+ description: 'Read reach, likes and comment metrics for one post.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Reads per-post Instagram metrics such as reach, likes, comments, saves and shares for one media id. Available metrics differ by media type, since reels and stories expose different ones from feed images, and an unsupported metric returns an error naming it. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ media_id: Property.ShortText({ displayName: 'Media ID', required: true }),+ metrics: Property.Array({+ displayName: 'Metrics',+ description: 'Metric names. Defaults to reach, likes and comments (reach, replies and shares for stories).',+ required: false,+ }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;+ const metrics = parseArrayProp(propsValue.metrics)+ .map((metric) => String(metric))+ .filter((metric) => metric.length > 0);++ const metric =+ metrics.length > 0+ ? metrics.join(',')+ : await defaultMetrics({ mediaId: propsValue.media_id, accessToken: page.accessToken });++ const response = await instagramCommon.graphRequest<{ data?: unknown[] }>({+ method: HttpMethod.GET,+ resourceUri: `/${propsValue.media_id}/insights`,+ accessToken: page.accessToken,+ query: { metric },+ });++ const insights = response.data ?? [];+ return { insights, count: insights.length };+ },+});++async function defaultMetrics({+ mediaId,+ accessToken,+}: {+ mediaId: string;+ accessToken: string;+}): Promise<string> {+ const media = await instagramCommon.graphRequest<{ media_product_type?: string }>({+ method: HttpMethod.GET,+ resourceUri: `/${mediaId}`,+ accessToken,+ query: { fields: 'media_product_type' },+ });+ return media.media_product_type === 'STORY' ? 'reach,replies,shares' : 'reach,likes,comments';+}diff --git a/packages/pieces/community/instagram-business/src/lib/actions/media/get-media.ts b/packages/pieces/community/instagram-business/src/lib/actions/media/get-media.tsnew file mode 100644index 00000000000..44be2724489--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/media/get-media.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { getMediaOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown, MEDIA_FIELDS } from '../../common';++export const getMedia = createAction({+ auth: instagramCommon.authentication,+ outputSchema: getMediaOutputSchema,+ name: 'get_media',+ classification: 'READ',+ displayName: 'Get Media',+ description: 'Read a single Instagram post by its id.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Reads one Instagram post, reel or album by its media id, returning caption, permalink, media type, media URL, timestamp and engagement counts. Use it after List Media, or when a trigger or earlier step supplied a media id. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ media_id: Property.ShortText({+ displayName: 'Media ID',+ description: 'The id of the post, as returned by List Media or a publish action.',+ required: true,+ }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ return instagramCommon.graphRequest({+ method: HttpMethod.GET,+ resourceUri: `/${propsValue.media_id}`,+ accessToken: page.accessToken,+ query: { fields: MEDIA_FIELDS },+ });+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/media/list-carousel-children.ts b/packages/pieces/community/instagram-business/src/lib/actions/media/list-carousel-children.tsnew file mode 100644index 00000000000..9d2087bd31f--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/media/list-carousel-children.ts@@ -0,0 +1,41 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { listCarouselChildrenOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const listCarouselChildren = createAction({+ auth: instagramCommon.authentication,+ outputSchema: listCarouselChildrenOutputSchema,+ name: 'list_carousel_children',+ classification: 'SEARCH',+ displayName: 'List Carousel Children',+ description: 'List the individual items inside a carousel album post.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the individual photos and videos inside one Instagram carousel album, given the album media id. Only works on media whose media_type is CAROUSEL_ALBUM; other posts return an empty list. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ media_id: Property.ShortText({+ displayName: 'Carousel Media ID',+ description: 'The id of a post whose media type is CAROUSEL_ALBUM.',+ required: true,+ }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const response = await instagramCommon.graphRequest<{ data?: unknown[] }>({+ method: HttpMethod.GET,+ resourceUri: `/${propsValue.media_id}/children`,+ accessToken: page.accessToken,+ query: { fields: 'id,media_type,media_url,permalink,timestamp,thumbnail_url' },+ });++ const children = response.data ?? [];+ return { children, count: children.length };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/media/list-media.ts b/packages/pieces/community/instagram-business/src/lib/actions/media/list-media.tsnew file mode 100644index 00000000000..8530c67be10--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/media/list-media.ts@@ -0,0 +1,53 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { listMediaOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown, GraphPaging, MEDIA_FIELDS } from '../../common';++export const listMedia = createAction({+ auth: instagramCommon.authentication,+ outputSchema: listMediaOutputSchema,+ name: 'list_media',+ classification: 'SEARCH',+ displayName: 'List Media',+ description: 'List posts published by the connected Instagram account.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the media (posts, reels and albums) published by the connected Instagram professional account, newest first, with caption, permalink, media type and engagement counts. Use it to find a recent post or its id before reading or commenting on it. Stories are not included — use List Stories for those. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Maximum number of posts to return (default 25).',+ required: false,+ }),+ cursor: instagramCommon.cursor,+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const response = await instagramCommon.graphRequest<{+ data?: unknown[];+ paging?: GraphPaging;+ }>({+ method: HttpMethod.GET,+ resourceUri: `/${page.id}/media`,+ accessToken: page.accessToken,+ query: {+ fields: MEDIA_FIELDS,+ limit: propsValue.limit ?? 25,+ after: propsValue.cursor,+ },+ });++ const media = response.data ?? [];+ return {+ media,+ count: media.length,+ next_cursor: instagramCommon.nextCursor(response.paging),+ };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/media/list-stories.ts b/packages/pieces/community/instagram-business/src/lib/actions/media/list-stories.tsnew file mode 100644index 00000000000..61f82acea42--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/media/list-stories.ts@@ -0,0 +1,36 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';++import { listStoriesOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const listStories = createAction({+ auth: instagramCommon.authentication,+ outputSchema: listStoriesOutputSchema,+ name: 'list_stories',+ classification: 'SEARCH',+ displayName: 'List Stories',+ description: 'List the stories currently live on the connected Instagram account.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the stories that are currently live on the connected Instagram professional account. Stories expire after 24 hours and disappear from this list once they do, so an empty result means nothing is live rather than that something failed. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const response = await instagramCommon.graphRequest<{ data?: unknown[] }>({+ method: HttpMethod.GET,+ resourceUri: `/${page.id}/stories`,+ accessToken: page.accessToken,+ query: { fields: 'id,media_type,media_url,permalink,timestamp,thumbnail_url' },+ });++ const stories = response.data ?? [];+ return { stories, count: stories.length };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/media/list-tagged-media.ts b/packages/pieces/community/instagram-business/src/lib/actions/media/list-tagged-media.tsnew file mode 100644index 00000000000..f5654ec3b8c--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/media/list-tagged-media.ts@@ -0,0 +1,49 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { listMediaOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown, GraphPaging, MEDIA_FIELDS } from '../../common';++export const listTaggedMedia = createAction({+ auth: instagramCommon.authentication,+ outputSchema: listMediaOutputSchema,+ name: 'list_tagged_media',+ classification: 'SEARCH',+ displayName: 'List Tagged Media',+ description: 'List posts by other accounts that tagged this account.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists posts published by other Instagram accounts in which the connected account was tagged. These belong to other people, so they cannot be edited or deleted, and the list is useful for monitoring brand mentions. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ limit: Property.Number({ displayName: 'Limit', required: false }),+ cursor: instagramCommon.cursor,+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const response = await instagramCommon.graphRequest<{+ data?: unknown[];+ paging?: GraphPaging;+ }>({+ method: HttpMethod.GET,+ resourceUri: `/${page.id}/tags`,+ accessToken: page.accessToken,+ query: {+ fields: MEDIA_FIELDS,+ limit: propsValue.limit ?? 25,+ after: propsValue.cursor,+ },+ });++ const media = response.data ?? [];+ return {+ media,+ count: media.length,+ next_cursor: instagramCommon.nextCursor(response.paging),+ };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/media/set-media-comments-enabled.ts b/packages/pieces/community/instagram-business/src/lib/actions/media/set-media-comments-enabled.tsnew file mode 100644index 00000000000..ca8e681a104--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/media/set-media-comments-enabled.ts@@ -0,0 +1,41 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { identifierResultOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const setMediaCommentsEnabled = createAction({+ auth: instagramCommon.authentication,+ outputSchema: identifierResultOutputSchema,+ name: 'set_media_comments_enabled',+ classification: 'WRITE',+ displayName: 'Enable or Disable Comments',+ description: 'Turn commenting on or off for one post.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Turns commenting on or off for one Instagram post belonging to the connected account. Disabling hides the existing comments from public view and blocks new ones, and re-enabling restores them. Idempotent, since setting the same state twice leaves the post unchanged.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ media_id: Property.ShortText({ displayName: 'Media ID', required: true }),+ enabled: Property.Checkbox({+ displayName: 'Comments Enabled',+ required: true,+ defaultValue: true,+ }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const result = await instagramCommon.graphRequest<{ success?: boolean }>({+ method: HttpMethod.POST,+ resourceUri: `/${propsValue.media_id}`,+ accessToken: page.accessToken,+ body: { comment_enabled: propsValue.enabled },+ });++ return { success: result.success ?? true, id: propsValue.media_id };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/messaging/list-conversations.ts b/packages/pieces/community/instagram-business/src/lib/actions/messaging/list-conversations.tsnew file mode 100644index 00000000000..cb890769f0c--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/messaging/list-conversations.ts@@ -0,0 +1,51 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { listConversationsOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown, GraphPaging } from '../../common';++export const listConversations = createAction({+ auth: instagramCommon.authentication,+ outputSchema: listConversationsOutputSchema,+ name: 'list_conversations',+ classification: 'SEARCH',+ displayName: 'List Conversations',+ description: 'List Instagram direct message threads for the account.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the Instagram direct message threads belonging to the connected professional account, newest activity first, with the participants and the time of the last message. Use it to find a conversation id before reading or replying to a thread. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ limit: Property.Number({ displayName: 'Limit', required: false }),+ cursor: instagramCommon.cursor,+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;+ const pageId = instagramCommon.requirePageId(page);++ const response = await instagramCommon.graphRequest<{+ data?: unknown[];+ paging?: GraphPaging;+ }>({+ method: HttpMethod.GET,+ resourceUri: `/${pageId}/conversations`,+ accessToken: page.accessToken,+ query: {+ platform: 'instagram',+ fields: 'id,updated_time,unread_count,message_count,participants',+ limit: propsValue.limit ?? 25,+ after: propsValue.cursor,+ },+ });++ const conversations = response.data ?? [];+ return {+ conversations,+ count: conversations.length,+ next_cursor: instagramCommon.nextCursor(response.paging),+ };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/messaging/list-messages.ts b/packages/pieces/community/instagram-business/src/lib/actions/messaging/list-messages.tsnew file mode 100644index 00000000000..a977e28bdb3--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/messaging/list-messages.ts@@ -0,0 +1,45 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { listMessagesOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const listMessages = createAction({+ auth: instagramCommon.authentication,+ outputSchema: listMessagesOutputSchema,+ name: 'list_messages',+ classification: 'SEARCH',+ displayName: 'List Messages',+ description: 'Read the messages inside one direct message thread.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Reads the messages inside one Instagram direct message thread, given a conversation id from List Conversations, with sender, recipient, text and timestamp for each. Instagram returns only the most recent messages of a thread rather than its full history. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ page: instagramCommon.page,+ conversation_id: Property.ShortText({+ displayName: 'Conversation ID',+ description: 'From List Conversations.',+ required: true,+ }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;++ const response = await instagramCommon.graphRequest<{+ messages?: { data?: unknown[] };+ }>({+ method: HttpMethod.GET,+ resourceUri: `/${propsValue.conversation_id}`,+ accessToken: page.accessToken,+ query: {+ fields: 'messages{id,created_time,from,to,message}',+ },+ });++ const messages = response.messages?.data ?? [];+ return { messages, count: messages.length };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/messaging/send-media-message.ts b/packages/pieces/community/instagram-business/src/lib/actions/messaging/send-media-message.tsnew file mode 100644index 00000000000..877766cb401--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/messaging/send-media-message.ts@@ -0,0 +1,71 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { sendMessageOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const sendMediaMessage = createAction({+ auth: instagramCommon.authentication,+ outputSchema: sendMessageOutputSchema,+ name: 'send_media_message',+ classification: 'WRITE',+ displayName: 'Send Media Message',+ description: 'Send an image, video or audio file as a direct message.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Sends an image, video or audio file as an Instagram direct message, given a publicly reachable URL and the recipient Instagram-scoped user id. The same 24 hour reply window applies as for a text message. Not idempotent, since each call sends another message.',+ idempotent: false,+ },+ props: {+ page: instagramCommon.page,+ recipient_id: Property.ShortText({+ displayName: 'Recipient ID',+ required: true,+ }),+ media_type: Property.StaticDropdown({+ displayName: 'Media Type',+ required: true,+ defaultValue: 'image',+ options: {+ options: [+ { label: 'Image', value: 'image' },+ { label: 'Video', value: 'video' },+ { label: 'Audio', value: 'audio' },+ ],+ },+ }),+ url: Property.ShortText({+ displayName: 'Media URL',+ description: 'Publicly reachable URL of the file. Instagram fetches it server side and rejects some hosts with an upload error, so prefer a plain static file URL.',+ required: true,+ }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;+ const pageId = instagramCommon.requirePageId(page);++ const result = await instagramCommon.graphRequest<{+ recipient_id?: string;+ message_id?: string;+ }>({+ method: HttpMethod.POST,+ resourceUri: `/${pageId}/messages`,+ accessToken: page.accessToken,+ body: {+ recipient: { id: propsValue.recipient_id },+ message: {+ attachment: {+ type: propsValue.media_type,+ payload: { url: propsValue.url },+ },+ },+ },+ });++ return {+ message_id: result.message_id,+ recipient_id: result.recipient_id ?? propsValue.recipient_id,+ };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/messaging/send-message.ts b/packages/pieces/community/instagram-business/src/lib/actions/messaging/send-message.tsnew file mode 100644index 00000000000..a79eba461b4--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/messaging/send-message.ts@@ -0,0 +1,51 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { sendMessageOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const sendMessage = createAction({+ auth: instagramCommon.authentication,+ outputSchema: sendMessageOutputSchema,+ name: 'send_message',+ classification: 'WRITE',+ displayName: 'Send Message',+ description: 'Send a direct message to an Instagram user.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Sends a text direct message to one Instagram user, addressed by their Instagram-scoped user id as supplied by a New Message trigger or List Conversations. Instagram only allows a reply within 24 hours of that user last messaging the account, so an older thread is rejected. Not idempotent, since each call sends another message.',+ idempotent: false,+ },+ props: {+ page: instagramCommon.page,+ recipient_id: Property.ShortText({+ displayName: 'Recipient ID',+ description: 'The Instagram-scoped user id of the person to message.',+ required: true,+ }),+ text: Property.LongText({ displayName: 'Message', required: true }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;+ const pageId = instagramCommon.requirePageId(page);++ const result = await instagramCommon.graphRequest<{+ recipient_id?: string;+ message_id?: string;+ }>({+ method: HttpMethod.POST,+ resourceUri: `/${pageId}/messages`,+ accessToken: page.accessToken,+ body: {+ recipient: { id: propsValue.recipient_id },+ message: { text: propsValue.text },+ },+ });++ return {+ message_id: result.message_id,+ recipient_id: result.recipient_id ?? propsValue.recipient_id,+ };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/messaging/send-private-reply.ts b/packages/pieces/community/instagram-business/src/lib/actions/messaging/send-private-reply.tsnew file mode 100644index 00000000000..0a9641ac79b--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/messaging/send-private-reply.ts@@ -0,0 +1,51 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { sendMessageOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const sendPrivateReply = createAction({+ auth: instagramCommon.authentication,+ outputSchema: sendMessageOutputSchema,+ name: 'send_private_reply',+ classification: 'WRITE',+ displayName: 'Send Private Reply',+ description: 'Reply privately by direct message to someone who commented.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Sends a direct message to the author of a comment, given the comment id rather than a user id, which is how Instagram supports the comment-to-DM pattern. Allowed once per comment and only within 7 days of it, and unlike Send Message it does not need an existing conversation. Not idempotent, and a second private reply to the same comment is rejected.',+ idempotent: false,+ },+ props: {+ page: instagramCommon.page,+ comment_id: Property.ShortText({+ displayName: 'Comment ID',+ description: 'The comment whose author should receive the direct message.',+ required: true,+ }),+ text: Property.LongText({ displayName: 'Message', required: true }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;+ const pageId = instagramCommon.requirePageId(page);++ const result = await instagramCommon.graphRequest<{+ recipient_id?: string;+ message_id?: string;+ }>({+ method: HttpMethod.POST,+ resourceUri: `/${pageId}/messages`,+ accessToken: page.accessToken,+ body: {+ recipient: { comment_id: propsValue.comment_id },+ message: { text: propsValue.text },+ },+ });++ return {+ message_id: result.message_id,+ recipient_id: result.recipient_id,+ };+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/publishing/publish-carousel.ts b/packages/pieces/community/instagram-business/src/lib/actions/publishing/publish-carousel.tsnew file mode 100644index 00000000000..2b2dabb0532--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/publishing/publish-carousel.ts@@ -0,0 +1,107 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { publishedMediaOutputSchema } from '../../output-schemas';+import {+ instagramCommon,+ FacebookPageDropdown,+ parseArrayProp,+ CONTAINER_TIMEOUT_MS,+ CAROUSEL_ALBUM_TIMEOUT_MS,+} from '../../common';++export const publishCarousel = createAction({+ auth: instagramCommon.authentication,+ outputSchema: publishedMediaOutputSchema,+ name: 'publish_carousel',+ classification: 'WRITE',+ displayName: 'Publish Carousel',+ description: 'Publish a carousel album of up to 10 photos or videos.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Publishes a single Instagram carousel album containing between 2 and 10 photos or videos, given their public URLs, with an optional caption. Every item is uploaded first and processed in parallel, with up to five minutes for the items and two more for the album. A carousel counts as one post against the 100-per-24-hours publishing quota. Not idempotent — each call publishes a new album.',+ idempotent: false,+ },+ props: {+ page: instagramCommon.page,+ items: Property.Array({+ displayName: 'Items',+ description: 'Between 2 and 10 photos or videos, in the order they should appear.',+ required: true,+ properties: {+ url: Property.ShortText({+ displayName: 'Media URL',+ description: 'Public URL of the photo (JPG) or video.',+ required: true,+ }),+ is_video: Property.Checkbox({+ displayName: 'Is Video',+ description: 'Turn on when this item is a video rather than a photo.',+ required: false,+ defaultValue: false,+ }),+ },+ }),+ caption: instagramCommon.caption,+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;+ const items = parseArrayProp(propsValue.items);++ if (items.length < 2 || items.length > 10) {+ throw new Error(+ `A carousel needs between 2 and 10 items, but ${items.length} were supplied.`,+ );+ }++ const parsedItems = items.map(parseCarouselItem);+ const deadline = Date.now() + CONTAINER_TIMEOUT_MS;++ const childIds: string[] = [];+ for (const parsed of parsedItems) {+ childIds.push(+ await instagramCommon.createContainer({+ page,+ body: {+ ...(parsed.isVideo ? { video_url: parsed.url } : { image_url: parsed.url }),+ ...(parsed.isVideo ? { media_type: 'VIDEO' } : {}),+ is_carousel_item: true,+ },+ }),+ );+ }++ await Promise.all(+ childIds.map((containerId) =>+ instagramCommon.waitForContainer({ containerId, page, deadline }),+ ),+ );++ const albumId = await instagramCommon.createContainer({+ page,+ body: {+ media_type: 'CAROUSEL',+ children: childIds.join(','),+ caption: propsValue.caption,+ },+ });+ await instagramCommon.waitForContainer({+ containerId: albumId,+ page,+ deadline: Date.now() + CAROUSEL_ALBUM_TIMEOUT_MS,+ });+ return instagramCommon.publishContainer({ containerId: albumId, page });+ },+});++function parseCarouselItem(item: unknown): { url: string; isVideo: boolean } {+ if (typeof item !== 'object' || item === null) {+ throw new Error('Each carousel item must supply a Media URL.');+ }+ const record: Record<string, unknown> = { ...item };+ const url = record['url'];+ if (typeof url !== 'string' || url.trim().length === 0) {+ throw new Error('Each carousel item must supply a Media URL.');+ }+ return { url, isVideo: record['is_video'] === true };+}diff --git a/packages/pieces/community/instagram-business/src/lib/actions/publishing/publish-story.ts b/packages/pieces/community/instagram-business/src/lib/actions/publishing/publish-story.tsnew file mode 100644index 00000000000..76594700467--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/actions/publishing/publish-story.ts@@ -0,0 +1,50 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { publishedMediaOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';++export const publishStory = createAction({+ auth: instagramCommon.authentication,+ outputSchema: publishedMediaOutputSchema,+ name: 'publish_story',+ classification: 'WRITE',+ displayName: 'Publish Story',+ description: 'Publish a photo or video story to an Instagram professional account.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Publishes one photo or video as an Instagram story, which expires after 24 hours. Supply exactly one of Photo URL or Video URL, and the media must be reachable at a public URL. Use Publish Photo or Publish Reel instead for permanent feed posts. Not idempotent — each call publishes a new story.',+ idempotent: false,+ },+ props: {+ page: instagramCommon.page,+ photo: Property.ShortText({+ displayName: 'Photo URL',+ description: 'Public URL of a JPG image. Leave empty when publishing a video story.',+ required: false,+ }),+ video: Property.ShortText({+ displayName: 'Video URL',+ description: 'Public URL of a video. Leave empty when publishing a photo story.',+ required: false,+ }),+ },+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;+ const { photo, video } = propsValue;++ if (!photo && !video) {+ throw new Error('Provide either a Photo URL or a Video URL.');+ }+ if (photo && video) {+ throw new Error('Provide only one of Photo URL or Video URL, not both.');+ }++ return instagramCommon.publishMedia({+ page,+ body: photo+ ? { image_url: photo, media_type: 'STORIES' }+ : { video_url: video, media_type: 'STORIES' },+ });+ },+});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/upload-photo.ts b/packages/pieces/community/instagram-business/src/lib/actions/publishing/upload-photo.tssimilarity index 70%rename from packages/pieces/community/instagram-business/src/lib/actions/upload-photo.tsrename to packages/pieces/community/instagram-business/src/lib/actions/publishing/upload-photo.tsindex 0bd73c84a38..98188bad3cb 100644--- a/packages/pieces/community/instagram-business/src/lib/actions/upload-photo.ts+++ b/packages/pieces/community/instagram-business/src/lib/actions/publishing/upload-photo.ts@@ -1,9 +1,11 @@import { createAction } from '@activepieces/pieces-framework';-import { instagramCommon, FacebookPageDropdown } from '../common';+import { publishedMediaOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';export const uploadPhoto = createAction({auth: instagramCommon.authentication,+ outputSchema: publishedMediaOutputSchema,name: 'upload_photo',classification: 'WRITE',displayName: 'Upload Photo',@@ -16,12 +18,11 @@ export const uploadPhoto = createAction({caption: instagramCommon.caption,},async run({ propsValue }) {- const page: FacebookPageDropdown = propsValue.page!;- const result = await instagramCommon.createPhotoPost(+ const page: FacebookPageDropdown = propsValue.page;+ return instagramCommon.createPhotoPost({page,- propsValue.caption,- propsValue.photo- );- return result;+ caption: propsValue.caption,+ photo: propsValue.photo,+ });},});diff --git a/packages/pieces/community/instagram-business/src/lib/actions/upload-reel.ts b/packages/pieces/community/instagram-business/src/lib/actions/publishing/upload-reel.tssimilarity index 69%rename from packages/pieces/community/instagram-business/src/lib/actions/upload-reel.tsrename to packages/pieces/community/instagram-business/src/lib/actions/publishing/upload-reel.tsindex ecae76f4262..4b96bd49ae7 100644--- a/packages/pieces/community/instagram-business/src/lib/actions/upload-reel.ts+++ b/packages/pieces/community/instagram-business/src/lib/actions/publishing/upload-reel.ts@@ -1,9 +1,11 @@import { createAction } from '@activepieces/pieces-framework';-import { instagramCommon, FacebookPageDropdown } from '../common';+import { publishedMediaOutputSchema } from '../../output-schemas';+import { instagramCommon, FacebookPageDropdown } from '../../common';export const uploadReel = createAction({auth: instagramCommon.authentication,+ outputSchema: publishedMediaOutputSchema,name: 'upload_reel',classification: 'WRITE',displayName: 'Upload Reel',@@ -15,13 +17,12 @@ export const uploadReel = createAction({video: instagramCommon.video,caption: instagramCommon.caption,},- async run(context) {- const page: FacebookPageDropdown = context.propsValue.page!;- const result = await instagramCommon.createVideoPost(+ async run({ propsValue }) {+ const page: FacebookPageDropdown = propsValue.page;+ return instagramCommon.createVideoPost({page,- context.propsValue.caption,- context.propsValue.video- );- return result;+ caption: propsValue.caption,+ video: propsValue.video,+ });},});diff --git a/packages/pieces/community/instagram-business/src/lib/common/index.ts b/packages/pieces/community/instagram-business/src/lib/common/index.tsindex 1b98f8ebf67..b49fce87b05 100644--- a/packages/pieces/community/instagram-business/src/lib/common/index.ts+++ b/packages/pieces/community/instagram-business/src/lib/common/index.ts@@ -4,32 +4,221 @@ import {getAccessTokenOrThrow,} from '@activepieces/pieces-common';import {- OAuth2PropertyValue,PieceAuth,Property,} from '@activepieces/pieces-framework';const markdown = `-To Obtain the following credentials:-1. Visit https://developers.facebook.com/-2. Create an application, Select Other for Usecase.-3. Select Business as App Type.-4. Copy App Id and App Secret from Basic Settings.+**Use the Facebook App ID and App Secret — not the Instagram ones.**++1. Visit https://developers.facebook.com/ and create an app.+2. Choose **Other** as the use case, then **Business** as the app type. Any other+ combination leaves the app without the Instagram permissions this piece requests.+3. Add the **Facebook Login for Business** product.+4. Copy the **App ID** and **App Secret** from **Settings → Basic**.++The Instagram product page shows a separate *Instagram app ID* and *Instagram app secret*.+Those belong to Instagram Login and will not work here — this piece uses Facebook Login.++Your Instagram account must be a Business or Creator account linked to a Facebook Page.`;-const instagramBusinessAuth = PieceAuth.OAuth2({+const instagramBusinessAuth = PieceAuth.OAuth2({description: markdown,authUrl: 'https://graph.facebook.com/oauth/authorize',tokenUrl: 'https://graph.facebook.com/oauth/access_token',required: true,- scope: ['instagram_basic', 'instagram_content_publish', 'business_management', 'pages_show_list'],-})-export const instagramCommon = {- baseUrl: 'https://graph.facebook.com/v17.0',+ scope: [+ 'instagram_basic',+ 'instagram_content_publish',+ 'instagram_manage_comments',+ 'instagram_manage_insights',+ 'instagram_manage_contents',+ 'instagram_manage_messages',+ 'business_management',+ 'pages_show_list',+ 'pages_read_engagement',+ 'pages_manage_metadata',+ 'pages_messaging',+ ],+});++async function graphRequest<T>({+ method,+ resourceUri,+ accessToken,+ query,+ body,+}: GraphRequestParams): Promise<T> {+ const queryParams: Record<string, string> = {};+ if (query) {+ for (const [key, value] of Object.entries(query)) {+ if (value !== undefined && value !== null) {+ queryParams[key] = String(value);+ }+ }+ }++ const response = await httpClient.sendRequest<T>({+ method,+ url: `${INSTAGRAM_API_BASE}${resourceUri}`,+ headers: {+ authorization: `Bearer ${accessToken}`,+ },+ queryParams,+ body,+ });++ return response.body;+}++async function getPages(accessToken: string): Promise<FacebookPage[]> {+ const response = await graphRequest<{ data?: FacebookPage[] }>({+ method: HttpMethod.GET,+ resourceUri: '/me/accounts',+ accessToken,+ query: { fields: 'id,name,access_token,instagram_business_account' },+ });++ return response.data ?? [];+}++async function createContainer({+ page,+ body,+}: CreateContainerParams): Promise<string> {+ const container = await graphRequest<{ id?: string }>({+ method: HttpMethod.POST,+ resourceUri: `/${page.id}/media`,+ accessToken: page.accessToken,+ body,+ });++ if (!container.id) {+ throw new Error(+ 'Instagram did not return a media container id. The media URL may not be publicly reachable.',+ );+ }++ return container.id;+}++async function waitForContainer({+ containerId,+ page,+ deadline = Date.now() + CONTAINER_TIMEOUT_MS,+}: WaitForContainerParams): Promise<void> {+ for (;;) {+ const container = await graphRequest<{+ status_code?: string;+ status?: string;+ }>({+ method: HttpMethod.GET,+ resourceUri: `/${containerId}`,+ accessToken: page.accessToken,+ query: { fields: 'status_code,status' },+ });++ const statusCode = container.status_code;+ if (statusCode === 'FINISHED') {+ return;+ }+ if (statusCode === 'ERROR' || statusCode === 'EXPIRED') {+ throw new Error(+ `Instagram could not process the media (status ${statusCode}): ${+ container.status ?? 'no further detail was returned'+ }`,+ );+ }+ if (Date.now() + CONTAINER_POLL_INTERVAL_MS >= deadline) {+ throw new Error(+ `Instagram did not finish processing the media in time (status ${+ statusCode ?? 'unknown'+ }). The post was not published.`,+ );+ }++ await wait(CONTAINER_POLL_INTERVAL_MS);+ }+}++async function publishContainer({+ containerId,+ page,+}: PublishContainerParams): Promise<PublishedMedia> {+ const published = await graphRequest<{ id?: string }>({+ method: HttpMethod.POST,+ resourceUri: `/${page.id}/media_publish`,+ accessToken: page.accessToken,+ body: { creation_id: containerId },+ });++ if (!published.id) {+ throw new Error('Instagram did not return a media id for the published post.');+ }++ return { id: published.id };+}++async function publishMedia({+ page,+ body,+}: PublishMediaParams): Promise<PublishedMedia> {+ const containerId = await createContainer({ page, body });+ await waitForContainer({ containerId, page });+ return publishContainer({ containerId, page });+}++async function createPhotoPost({+ page,+ caption,+ photo,+}: CreatePhotoPostParams): Promise<PublishedMedia> {+ return publishMedia({ page, body: { image_url: photo, caption } });+}++async function createVideoPost({+ page,+ caption,+ video,+}: CreateVideoPostParams): Promise<PublishedMedia> {+ return publishMedia({+ page,+ body: { video_url: video, caption, media_type: 'REELS' },+ });+}++function requirePageId(page: FacebookPageDropdown): string {+ if (!page.pageId) {+ throw new Error(+ 'This step needs the Facebook Page id. Re-open the step and select the Page again to refresh it.',+ );+ }+ return page.pageId;+}++function nextCursor(paging: GraphPaging | undefined): string | undefined {+ return paging?.next ? paging.cursors?.after : undefined;+}+function wait(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++export const instagramCommon = {authentication: instagramBusinessAuth,+ graphRequest,+ getPages,+ createContainer,+ waitForContainer,+ publishContainer,+ publishMedia,+ requirePageId,+ nextCursor,+ createPhotoPost,+ createVideoPost,- page: Property.Dropdown<FacebookPageDropdown,true,typeof instagramBusinessAuth>({+ page: Property.Dropdown<FacebookPageDropdown, true, typeof instagramBusinessAuth>({auth: instagramBusinessAuth,displayName: 'Page',required: true,@@ -43,26 +232,30 @@ export const instagramCommon = {};}- const accessToken: string = getAccessTokenOrThrow(- auth- );- const pages: any[] = (await instagramCommon.getPages(accessToken))- .map((page: FacebookPage) => {- if (!page.instagram_business_account) {- return null;- }- return {- label: page.name,- value: {- id: page.instagram_business_account.id,- accessToken: page.access_token,- },- };- })- .filter((f: unknown) => f !== null);+ const accessToken = getAccessTokenOrThrow(auth);+ const pages = await getPages(accessToken);+ const options = pages+ .filter((page) => page.instagram_business_account !== undefined)+ .map((page) => ({+ label: page.name,+ value: {+ id: page.instagram_business_account.id,+ pageId: page.id,+ accessToken: page.access_token,+ },+ }));++ if (options.length === 0) {+ return {+ disabled: true,+ options: [],+ placeholder:+ 'No Facebook Page with a linked Instagram professional account was found',+ };+ }return {- options: pages,+ options,placeholder: 'Choose a page',};},@@ -72,6 +265,13 @@ export const instagramCommon = {displayName: 'Caption',required: false,}),++ cursor: Property.ShortText({+ displayName: 'Cursor',+ description: 'Next Cursor from a previous run, to fetch the following page.',+ required: false,+ }),+photo: Property.ShortText({displayName: 'Photo',description: 'A URL we can access for the photo (JPG only)',@@ -83,124 +283,102 @@ export const instagramCommon = {description: 'A URL we can access for the video (Limit: 1GB or 15 minutes)',required: true,}),+};- getPages: async (accessToken: string) => {- const response = await httpClient.sendRequest({- method: HttpMethod.GET,- url: `${instagramCommon.baseUrl}/me/accounts`,- queryParams: {- access_token: accessToken,- fields: 'id,name,access_token,instagram_business_account',- },- });+export const COMMENT_FIELDS =+ 'id,text,timestamp,username,like_count,hidden,parent_id,media{id,media_type,permalink}';- return response.body.data;- },-- createPhotoPost: async (- page: FacebookPageDropdown,- caption: string | undefined,- photo: string- ) => {- const createContainerRequest = await httpClient.sendRequest({- method: HttpMethod.POST,- url: `${instagramCommon.baseUrl}/${page.id}/media`,- body: {- access_token: page.accessToken,- image_url: photo,- caption: caption,- },- });+export const MEDIA_FIELDS =+ 'id,caption,media_type,media_product_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count,is_comment_enabled';- const publishContainerRequest = await httpClient.sendRequest({- method: HttpMethod.POST,- url: `${instagramCommon.baseUrl}/${page.id}/media_publish`,- body: {- access_token: page.accessToken,- creation_id: createContainerRequest.body.id,- },- });+export const INSTAGRAM_API_BASE = 'https://graph.facebook.com/v23.0';- return publishContainerRequest.body;- },-- createVideoPost: async (- page: FacebookPageDropdown,- caption: string | undefined,- video: string- ) => {- const createContainerRequest = await httpClient.sendRequest({- method: HttpMethod.POST,- url: `${instagramCommon.baseUrl}/${page.id}/media`,- body: {- access_token: page.accessToken,- video_url: video,- caption: caption,- media_type: 'REELS',- },- });+export const CONTAINER_POLL_INTERVAL_MS = 5000;- const isUploaded = await isUploadSuccessful(- createContainerRequest.body.id,- page.accessToken,- 0- );+export const CONTAINER_TIMEOUT_MS = 5 * 60 * 1000;- if (isUploaded) {- const publishContainerRequest = await httpClient.sendRequest({- method: HttpMethod.POST,- url: `${instagramCommon.baseUrl}/${page.id}/media_publish`,- body: {- access_token: page.accessToken,- creation_id: createContainerRequest.body.id,- },- });-- return publishContainerRequest.body;- } else {- return false;+export const CAROUSEL_ALBUM_TIMEOUT_MS = 2 * 60 * 1000;++export function parseArrayProp(value: unknown): unknown[] {+ if (Array.isArray(value)) {+ return value;+ }++ if (typeof value === 'string') {+ try {+ const parsed: unknown = JSON.parse(value);+ if (Array.isArray(parsed)) {+ return parsed;+ }+ } catch {+ return [];}- },-};+ }-export interface FacebookPage {+ return [];+}++export type FacebookPage = {id: string;name: string;access_token: string;instagram_business_account: {id: string;};-}+};-export interface FacebookPageDropdown {+export type FacebookPageDropdown = {id: string;+ pageId?: string;accessToken: string;-}+};-async function isUploadSuccessful(- containerId: string,- accessToken: string,- retryCount: number-): Promise<boolean> {- if (retryCount > 20) return false;+export type PublishedMedia = {+ id: string;+};- const request = await httpClient.sendRequest({- method: HttpMethod.GET,- url: `${instagramCommon.baseUrl}/${containerId}`,- queryParams: {- access_token: accessToken,- fields: 'status_code',- },- });+type GraphRequestParams = {+ method: HttpMethod;+ resourceUri: string;+ accessToken: string;+ query?: Record<string, string | number | boolean | undefined>;+ body?: unknown;+};- if (request.body.status_code != 'FINISHED') {- await _wait(5000);- return await isUploadSuccessful(containerId, accessToken, retryCount + 1);- } else {- return true;- }-}+type PublishMediaParams = {+ page: FacebookPageDropdown;+ body: Record<string, unknown>;+};-function _wait(n: number) {- return new Promise((resolve) => setTimeout(resolve, n));-}+type CreateContainerParams = {+ page: FacebookPageDropdown;+ body: Record<string, unknown>;+};++type WaitForContainerParams = {+ containerId: string;+ page: FacebookPageDropdown;+ deadline?: number;+};++type PublishContainerParams = {+ containerId: string;+ page: FacebookPageDropdown;+};++type CreatePhotoPostParams = {+ page: FacebookPageDropdown;+ caption: string | undefined;+ photo: string;+};++type CreateVideoPostParams = {+ page: FacebookPageDropdown;+ caption: string | undefined;+ video: string;+};++export type GraphPaging = {+ next?: string;+ cursors?: { after?: string };+};diff --git a/packages/pieces/community/instagram-business/src/lib/output-schemas.ts b/packages/pieces/community/instagram-business/src/lib/output-schemas.tsnew file mode 100644index 00000000000..69903eb606e--- /dev/null+++ b/packages/pieces/community/instagram-business/src/lib/output-schemas.ts@@ -0,0 +1,313 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const mediaFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Media ID' },+ { key: 'caption', label: 'Caption' },+ {+ key: 'media_type',+ label: 'Media Type',+ description: 'IMAGE, VIDEO or CAROUSEL_ALBUM.',+ },+ {+ key: 'media_product_type',+ label: 'Product Type',+ description: 'FEED, REELS or STORY.',+ },+ { key: 'media_url', label: 'Media URL', format: 'image' },+ {+ key: 'thumbnail_url',+ label: 'Thumbnail URL',+ description: 'Videos and reels only.',+ format: 'image',+ },+ { key: 'permalink', label: 'Permalink', format: 'url' },+ { key: 'timestamp', label: 'Published At', format: 'datetime' },+ { key: 'username', label: 'Username' },+ { key: 'like_count', label: 'Likes', format: 'number' },+ { key: 'comments_count', label: 'Comments', format: 'number' },+ {+ key: 'is_comment_enabled',+ label: 'Comments Enabled',+ format: 'boolean',+ },+];++const storyFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Story ID' },+ { key: 'media_type', label: 'Media Type', description: 'IMAGE or VIDEO.' },+ { key: 'media_url', label: 'Media URL', format: 'image' },+ {+ key: 'thumbnail_url',+ label: 'Thumbnail URL',+ description: 'Video stories only.',+ format: 'image',+ },+ { key: 'permalink', label: 'Permalink', format: 'url' },+ { key: 'timestamp', label: 'Published At', format: 'datetime' },+];++export const publishedMediaOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'id',+ label: 'Media ID',+ description: 'The id of the published post, usable with Get Media.',+ },+ ],+};++export const getProfileOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Instagram Account ID' },+ { key: 'username', label: 'Username' },+ { key: 'name', label: 'Display Name' },+ { key: 'biography', label: 'Biography' },+ { key: 'website', label: 'Website', format: 'url' },+ {+ key: 'profile_picture_url',+ label: 'Profile Picture',+ format: 'image',+ },+ { key: 'followers_count', label: 'Followers', format: 'number' },+ { key: 'follows_count', label: 'Following', format: 'number' },+ { key: 'media_count', label: 'Media Count', format: 'number' },+ ],+};++export const listMediaOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'media',+ label: 'Media',+ labelKey: 'caption',+ listItems: mediaFields,+ },+ { key: 'count', label: 'Count', format: 'number' },+ {+ key: 'next_cursor',+ label: 'Next Cursor',+ description: 'Pass to fetch the following page; absent on the last page.',+ },+ ],+};++export const getMediaOutputSchema: OutputSchema = {+ fields: mediaFields,+};++export const listCarouselChildrenOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'children',+ label: 'Children',+ labelKey: 'media_type',+ listItems: [+ { key: 'id', label: 'Media ID' },+ { key: 'media_type', label: 'Media Type' },+ { key: 'media_url', label: 'Media URL', format: 'image' },+ { key: 'thumbnail_url', label: 'Thumbnail URL', format: 'image' },+ { key: 'permalink', label: 'Permalink', format: 'url' },+ { key: 'timestamp', label: 'Published At', format: 'datetime' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const listStoriesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'stories',+ label: 'Stories',+ labelKey: 'id',+ listItems: storyFields,+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const getContentPublishingLimitOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'quota_usage',+ label: 'Quota Used',+ description: 'Posts published through the API in the current window.',+ format: 'number',+ },+ { key: 'quota_total', label: 'Quota Total', format: 'number' },+ { key: 'quota_remaining', label: 'Quota Remaining', format: 'number' },+ {+ key: 'quota_duration_seconds',+ label: 'Window Length (seconds)',+ description: 'Length of the rolling window, normally 86400.',+ format: 'number',+ },+ ],+};++const commentFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Comment ID' },+ { key: 'text', label: 'Text' },+ { key: 'username', label: 'Author Username' },+ { key: 'timestamp', label: 'Posted At', format: 'datetime' },+ { key: 'like_count', label: 'Likes', format: 'number' },+ { key: 'hidden', label: 'Hidden', format: 'boolean' },+ {+ key: 'parent_id',+ label: 'Parent Comment ID',+ description: 'Present only when this comment is a reply.',+ },+ {+ key: 'media',+ label: 'Media',+ children: [+ { key: 'id', label: 'Media ID' },+ { key: 'media_type', label: 'Media Type' },+ { key: 'permalink', label: 'Permalink', format: 'url' },+ ],+ },+];++export const identifierResultOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'id', label: 'ID' },+ ],+};++export const getCommentOutputSchema: OutputSchema = {+ fields: commentFields,+};++export const listCommentsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'comments',+ label: 'Comments',+ labelKey: 'text',+ listItems: commentFields,+ },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'next_cursor', label: 'Next Cursor' },+ ],+};++export const commentCreatedOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Comment ID' },+ { key: 'media_id', label: 'Media ID' },+ { key: 'parent_id', label: 'Parent Comment ID' },+ ],+};++export const insightsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'insights',+ label: 'Insights',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Metric ID' },+ { key: 'name', label: 'Metric' },+ { key: 'title', label: 'Title' },+ { key: 'description', label: 'Description' },+ { key: 'period', label: 'Period' },+ {+ key: 'total_value',+ label: 'Total Value',+ children: [{ key: 'value', label: 'Value', format: 'number' }],+ },+ {+ key: 'values',+ label: 'Values',+ listItems: [+ { key: 'value', label: 'Value', format: 'number' },+ { key: 'end_time', label: 'End Time', format: 'datetime' },+ ],+ },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const listConversationsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'conversations',+ label: 'Conversations',+ labelKey: 'id',+ listItems: [+ { key: 'id', label: 'Conversation ID' },+ { key: 'updated_time', label: 'Last Activity', format: 'datetime' },+ {+ key: 'participants',+ label: 'Participants',+ children: [+ {+ key: 'data',+ label: 'People',+ labelKey: 'username',+ listItems: [+ { key: 'id', label: 'User ID' },+ { key: 'username', label: 'Username' },+ ],+ },+ ],+ },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'next_cursor', label: 'Next Cursor' },+ ],+};++export const listMessagesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'messages',+ label: 'Messages',+ labelKey: 'message',+ listItems: [+ { key: 'id', label: 'Message ID' },+ {+ key: 'message',+ label: 'Text',+ description: 'Empty for attachment-only messages.',+ },+ { key: 'created_time', label: 'Sent At', format: 'datetime' },+ {+ key: 'from',+ label: 'From',+ children: [+ { key: 'id', label: 'User ID' },+ { key: 'username', label: 'Username' },+ ],+ },+ {+ key: 'to',+ label: 'To',+ children: [+ {+ key: 'data',+ label: 'Recipients',+ labelKey: 'username',+ listItems: [+ { key: 'id', label: 'User ID' },+ { key: 'username', label: 'Username' },+ ],+ },+ ],+ },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const sendMessageOutputSchema: OutputSchema = {+ fields: [+ { key: 'message_id', label: 'Message ID' },+ { key: 'recipient_id', label: 'Recipient ID' },+ ],+};