Skip to content

I built my own Instagram comment-to-DM system

From the work/ 12 min read

A signed webhook, a keyword filter and a private reply: how an Instagram comment-to-DM system works, with tested Node code and the Meta app setup it needs.

  • AI
  • Claude Code
  • Node.js
In this article (7)
  1. Why I built it
  2. The flow in three steps: webhook, filter and DM
  3. The hard part: the Meta app and Instagram permissions
  4. How I built it with Claude Code
  5. Common mistakes
  6. Frequently asked questions
  7. Checklist

Instagram comment to DM automation takes three pieces: a webhook that receives every new comment, a filter that looks for your keyword, and a private reply that sends the message using the comment's ID. That is how Comenta, the system I built, works. The hard part is not the code: it is the Meta app and its permissions.

This post walks through the flow, what Meta's documentation says about webhooks, signatures and private replies, how the app is set up, and how I built it with Claude Code. The code here is not Comenta's: it is a minimal example that follows Meta's public docs, tested with node --test.

Why I built it

Every Reel in this series ends the same way: comment a word and I'll send you the guide. For that to work without living on your phone, something has to read the comments, recognize the word and answer by direct message. These are the keywords from the November Reels and the guide that goes with each one:

the Reel keywords and the guide for each onekeywordtopicguidePARCHENext.js security releaseecomlabs.dev/g/parche-guiaRAMNext.js memory on Railwayecomlabs.dev/g/ram-guiaRCEunpatched Next.js 14ecomlabs.dev/g/rce-guiaTRAMPAtests the agent deletedecomlabs.dev/g/trampa-guiaNODENode in Docker: patchesecomlabs.dev/g/node-guiaDIALOGaccessible <dialog> modalecomlabs.dev/g/dialog-guiaREWINDClaude Code checkpointsecomlabs.dev/g/rewind-guiaHMACShopify webhook HMACecomlabs.dev/g/hmac-guiaCOLASPostgres job queueecomlabs.dev/g/colas-guiaJSONreliable JSON from an LLMecomlabs.dev/g/json-guiaPWAPWA vs native appecomlabs.dev/g/pwa-guiaCOMENTAInstagram comment to DMecomlabs.dev/g/comenta-guiaone keyword per Reel, one guide per keywordpublic /g/<keyword>-guia short links, the same ones printed in each Reel's caption

Scroll the figure sideways to see all of it

Comenta (comenta.ecomlabs.dev) is the comment-to-DM system I built: when someone comments your keyword on a post, they get your link by direct message. Its page says that GUÍA, guia and Guía count the same, and that a dashboard shows the comments with your keyword, the DMs sent and the link clicks.

This post does not cover how Comenta is built inside: it covers the general architecture, which is the same for any system like this, and what Meta requires at each step. Two limits shape the whole design: a private reply must go out within 7 days of the comment, and only one message can be sent to the commenter.

The flow in three steps: webhook, filter and DM

Meta's private replies guide describes the path: someone comments on a professional account's post, Meta sends your server a webhook with the comment ID, the commenter and the text, and your app uses that ID to send a private reply. Your filter sits in between.

from an Instagram comment to a DMcommentsomeone typesCOMENTAon your ReelwebhookPOST from Metafield: commentsX-Hub-Signature-256filterwhole wordany caseaccents ignoredDMprivate replyPOST /messagesrecipient.comment_idbad signature:droppedno keyword orduplicate: skipwithin 7 daysone message onlyanswer 200 fast and dedupe: Meta retries for 36 hthe signature is computed over the raw body, keyed with the App Secret

Scroll the figure sideways to see all of it

1. The webhook: check that the notification came from Meta

Per Meta's guide to setting up Instagram webhooks, your callback URL, always HTTPS with a valid certificate, handles two kinds of request:

  • Verification. When you configure the Webhooks product, Meta sends a GET with hub.mode=subscribe, hub.challenge and hub.verify_token. If the token is the one you typed into the App Dashboard, you answer with the hub.challenge value.
  • Event notifications. Each event arrives as a POST with an X-Hub-Signature-256 header: sha256= plus the signature. Meta describes it as a SHA256 signature generated with the payload and the App Secret, and its Node example for Messenger computes it with crypto.createHmac("sha256", appSecret): an HMAC-SHA256.

Both checks, in webhook.mjs, with no dependencies:

import { createHmac, timingSafeEqual } from "node:crypto";

// GET: Meta calls your callback URL with hub.* parameters when you set up webhooks.
export function verifyChallenge(params, verifyToken) {
  if (params.get("hub.mode") !== "subscribe" || params.get("hub.verify_token") !== verifyToken) return null;
  return params.get("hub.challenge");
}

// POST: X-Hub-Signature-256 is "sha256=" + the HMAC-SHA256 of the raw body, keyed with the app secret.
export function isSignedByMeta(rawBody, header, appSecret) {
  if (typeof header !== "string" || !header.startsWith("sha256=")) return false;
  const expected = createHmac("sha256", appSecret).update(rawBody).digest();
  const received = Buffer.from(header.slice("sha256=".length), "hex");
  return received.length === expected.length && timingSafeEqual(received, expected);
}
  1. verifyChallenge takes the query parameters and your verify token. If the mode is subscribe and the token matches, it returns hub.challenge for your server to send back; otherwise null.
  2. isSignedByMeta rejects a missing header, or one that does not start with sha256=.
  3. expected is the HMAC-SHA256 of the raw body, the bytes exactly as they arrived, keyed with the App Secret; received turns the hex part of the header into bytes.
  4. timingSafeEqual compares in constant time, which the Node.js docs recommend for HMAC digests. It throws when the lengths differ, which is why the lengths are compared first.

Call isSignedByMeta before parsing the JSON. The guide also asks you to respond promptly and handle duplicate deliveries: when a delivery fails, Meta retries for up to 36 hours. Its troubleshooting checklist sums it up: return a success response before you start slow work.

2. The filter: the whole word, only once

According to Meta's webhook notification examples, a comment arrives in entry[].changes[], with field set to comments and a value holding the ID, the commenter and the text. The filter has three jobs: COMENTA and coménta count the same, comentario does not count, and a retry is not handled twice. It lives in keyword.mjs, with the private reply:

// Lowercase and drop accents (é → e), but keep ñ: "año" and "ano" are different words.
const normalize = (s) => s.toLowerCase().normalize("NFD").replace(/(?!\u0303)\p{M}/gu, "").normalize("NFC");

// New comments whose text contains the keyword as a whole word.
export function matchingComments(payload, keyword, seen) {
  const word = normalize(keyword);
  const found = [];
  for (const entry of payload?.entry ?? []) {
    for (const change of entry.changes ?? []) {
      if (change.field !== "comments") continue;
      const id = change.value?.id ?? change.value?.comment_id;
      const words = normalize(change.value?.text ?? "").split(/[^\p{L}\p{N}]+/u);
      if (!id || seen.has(id) || !words.includes(word)) continue;
      seen.add(id);
      found.push({ accountId: entry.id, commentId: id });
    }
  }
  return found;
}

// Private reply: POST /<IG_ID>/messages with the comment ID as the recipient.
export async function sendPrivateReply({ accountId, commentId }, text, accessToken) {
  const res = await fetch(`https://graph.instagram.com/v26.0/${accountId}/messages`, {
    method: "POST",
    headers: { "content-type": "application/json", authorization: `Bearer ${accessToken}` },
    body: JSON.stringify({ recipient: { comment_id: commentId }, message: { text } }),
  });
  if (!res.ok) throw new Error(`private reply failed with ${res.status}`);
  return res.json();
}
  1. normalize lowercases and strips accents, except the tilde of ñ (\u0303), so Spanish año and ano stay different words.
  2. matchingComments walks every entry and every change, and skips anything that is not the comments field.
  3. The ID comes from value.id, as in the Business Login for Instagram example; another example on the same page calls it comment_id, so both are accepted.
  4. The text is split into words on anything that is not a letter or a digit: #comenta matches; comentario and comenta2 do not.
  5. seen holds the handled IDs. Here it is an in-memory Set; in production, store the ID in your database under a unique constraint, so neither a retry nor a restart sends two DMs.
  6. sendPrivateReply makes the documented POST to /<IG_ID>/messages with recipient.comment_id and message.text, and throws on a non-2xx response. graph.instagram.com is the Instagram Login host; Unified Login and Facebook Login use graph.facebook.com. v26.0 is the version in Meta's current examples.

3. The DM: a private reply, with rules

A private reply is tied to the comment. The limitations Meta lists:

  • "Only one message can be sent to the commenter."
  • It must go out within 7 days of the comment; on a Live, only during the broadcast.
  • Follow-ups can only be sent if the person responds, within 24 hours of that response.
  • It lands in the Inbox if they follow the account, or in Requests if not, with a link to the commented post.

All 11 tests in comment-to-dm.test.mjs passed with node --test on Node 22, using fake notifications shaped like the documented example: the challenge, valid, tampered and malformed signatures, case, accents and ñ, rejecting comentario, a retry, and the exact private reply request with a mocked fetch. I did not call Meta's real API.

The hard part: the Meta app and Instagram permissions

The code fits on one screen; the app setup does not, and every step depends on which of the three API setups you pick. The Instagram Platform overview (October 29, 2026) recommends the Instagram API with Unified Login for new integrations: new API features are released only for that setup.

the Meta app for Instagram, step by step1 · create the appa Business type Meta appconnected to a verified business2 · Instagram productUnified, Instagram or Facebook LoginMeta recommends Unified Login3 · permissionsinstagram_manage_commentsinstagram_manage_messages4 · webhooksHTTPS callback + verify tokencomments field + /subscribed_apps5 · App Review + LiveAdvanced Access per permissionscreencast and business verificationwithout Live and Advanced Access: only accounts with a roleUnified Login permission names; Instagram Login uses instagram_business_*

Scroll the figure sideways to see all of it

To answer comments with a DM, the private replies guide requires the following for each setup:

TopicUnified LoginInstagram LoginFacebook Login
Access tokenBusiness Integration System UserInstagram UserFacebook Page
Hostgraph.facebook.comgraph.instagram.comgraph.facebook.com
Login typeFacebook Login for BusinessBusiness Login for InstagramFacebook Login for Business
Permissionsinstagram_basic, instagram_manage_comments and instagram_manage_messagesinstagram_business_basic and instagram_business_manage_commentsinstagram_basic, instagram_manage_comments and pages_read_engagement
Facebook PageNot requiredNot requiredRequired
Webhook fieldscomments, live_commentscomments, live_commentscomments, live_comments

What stays the same across setups:

  • A public professional account. You need an Instagram professional account, business or creator, and a public one: private accounts do not receive comment notifications.
  • A subscription per account. Configuring the webhook in the dashboard is not enough: each connected account is subscribed with a POST to its /subscribed_apps edge, with the same fields for all of them.
  • Standard and Advanced Access. Standard Access only lets you test with people who have a role on the app. For anyone else you need Advanced Access to each permission, which takes App Review and Business Verification, plus the app in Live mode: per the webhooks guide, without it your users' notifications do not arrive.
  • A real account to test with. The Unified Login getting started guide asks for a real professional account, invited as an Instagram Tester: test users are not supported.

Then comes App Review. Meta asks that the app can be tested externally, for reviewer instructions, a screencast per permission, a 1024×1024 icon, your privacy policy and, for some permissions, at least one successful API call. Request permissions you do not use and the submission will not be approved.

Watch out: two Meta pages disagree. The App Review page says an app that only serves your own business works with Standard Access and no review; the webhooks guide lists Advanced Access as a requirement for comments notifications. If you depend on the comments webhook, plan on App Review.

How I built it with Claude Code

I built Comenta with Claude Code, and the working rules live in the project's CLAUDE.md. These are the ones that matter for a system like this:

  • Done means verified. Before saying "done", type checking, linting and tests must pass, with the real output shown.
  • Test first where failure is not an option. Webhook signature checks and keyword matching are written test-first: the test, then the code.
  • No inventing Meta's API. The agent may not make up fields, permissions, endpoints or versions: it only uses what is in notes checked against the documentation. If something is missing, it takes the safe path and logs it as pending.
  • Every external input is validated, starting with Meta's webhooks, and logs never carry tokens, secrets or personal data such as usernames or comment text.
  • Work in blocks from a plan. Each block closes with green tests, a code review, an update to a progress file and a small commit. When work resumes, that progress file is read first.

It is the long version of my 4-step Claude Code workflow: decide before you build, and leave everything ready for the next session. For a big block, start with Claude Code plan mode; when an agent's change goes sideways, rewinding to a checkpoint with /rewind is cheaper than fixing on top of it. The verified-notes rule has a reason: instagram_business_manage_comments and instagram_manage_comments look alike, but Meta warns that host, token, account ID and fields are not interchangeable between setups.

Common mistakes

  • Signing the parsed JSON. Meta's Messenger webhooks guide notes that the signature is computed over an escaped-unicode payload (äöå as \u00e4\u00f6\u00e5). JSON.stringify(JSON.parse(body)) changes the bytes and the signature stops matching, as one of the tests shows.
  • Comparing signatures with ===. Use timingSafeEqual, which compares in constant time.
  • Matching the keyword as a substring. "buen comentario".includes("comenta") is true. Compare whole words.
  • Skipping deduplication. Meta retries for 36 hours, and its guide asks you to confirm that a duplicate notification does not repeat an action.
  • Testing with a private account, or one that is not subscribed. Neither one receives comment notifications.
  • Requesting extra permissions. App Review does not approve a submission with permissions your app does not use.
  • Forgetting message access. If the account has "Allow access to messages" turned off in its Instagram app, messaging API calls fail with error (#200), according to the Unified Login eligibility page.
  • Logging tokens. Meta asks you to keep tokens, the App Secret and credentials out of logs and support requests.

Frequently asked questions

Do I need an Instagram professional account?

Yes. The Instagram Platform only works with professional accounts, business or creator. On top of that, the account that owns the post must be public for comment notifications to arrive.

How long do I have to send the DM?

Seven days from when the comment was created. On a Live, only while the broadcast is running: once it ends, private replies to those comments can no longer be sent.

Can I send the commenter more than one message?

With the private reply, only one. If the person replies, you can send follow-up messages within 24 hours of their response. The Instagram messaging API also has a separate 7-day window for human agent replies, with its own tag.

Where does the message land?

In their Inbox if they follow your account, or in the Requests folder if they do not. The message includes a link to the post they commented on.

Checklist

  • The account is professional (business or creator) and public.
  • You picked an API setup (Meta recommends Unified Login for new integrations) and request only its permissions.
  • Your callback answers the verification GET with hub.challenge when the verify token matches.
  • Every POST is validated with X-Hub-Signature-256 over the raw body, using timingSafeEqual.
  • The filter compares whole words, ignoring case and accents.
  • You store each handled comment ID so nobody gets two DMs.
  • The private reply goes out within 7 days, with recipient.comment_id, and every account is subscribed through /subscribed_apps.
  • You have Advanced Access through App Review, a verified business and the app in Live mode.
  • No log carries tokens, the App Secret or personal data.

Meta's signature is the same idea as Shopify's: an HMAC-SHA256 of the raw body, keyed with a secret only you and the platform know. I walk through it in how to verify Shopify webhook HMAC signatures. And if you are building something like this with an agent, start with my Claude Code workflow and keep Claude Code checkpoints and /rewind close at hand.

Saw this on Instagram? Comment COMENTA on the Reel and I'll send you the guide.

Written by

Luis Morales

Luis Morales

Frontend and Shopify developer, EcomLabs

@luismoralesdev on Instagram

Published November 3, 2026

← Blog