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)
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:
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.
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
GETwithhub.mode=subscribe,hub.challengeandhub.verify_token. If the token is the one you typed into the App Dashboard, you answer with thehub.challengevalue. - Event notifications. Each event arrives as a
POSTwith anX-Hub-Signature-256header: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 withcrypto.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);
}
verifyChallengetakes the query parameters and your verify token. If the mode issubscribeand the token matches, it returnshub.challengefor your server to send back; otherwisenull.isSignedByMetarejects a missing header, or one that does not start withsha256=.expectedis the HMAC-SHA256 of the raw body, the bytes exactly as they arrived, keyed with the App Secret;receivedturns the hex part of the header into bytes.timingSafeEqualcompares 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();
}
normalizelowercases and strips accents, except the tilde of ñ (\u0303), so Spanish año and ano stay different words.matchingCommentswalks everyentryand every change, and skips anything that is not thecommentsfield.- The ID comes from
value.id, as in the Business Login for Instagram example; another example on the same page calls itcomment_id, so both are accepted. - The text is split into words on anything that is not a letter or a digit:
#comentamatches;comentarioandcomenta2do not. seenholds the handled IDs. Here it is an in-memorySet; in production, store the ID in your database under a unique constraint, so neither a retry nor a restart sends two DMs.sendPrivateReplymakes the documentedPOSTto/<IG_ID>/messageswithrecipient.comment_idandmessage.text, and throws on a non-2xxresponse.graph.instagram.comis the Instagram Login host; Unified Login and Facebook Login usegraph.facebook.com.v26.0is 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.
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:
| Topic | Unified Login | Instagram Login | Facebook Login |
|---|---|---|---|
| Access token | Business Integration System User | Instagram User | Facebook Page |
| Host | graph.facebook.com | graph.instagram.com | graph.facebook.com |
| Login type | Facebook Login for Business | Business Login for Instagram | Facebook Login for Business |
| Permissions | instagram_basic, instagram_manage_comments and instagram_manage_messages | instagram_business_basic and instagram_business_manage_comments | instagram_basic, instagram_manage_comments and pages_read_engagement |
| Facebook Page | Not required | Not required | Required |
| Webhook fields | comments, live_comments | comments, live_comments | comments, 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
POSTto its/subscribed_appsedge, 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
===. UsetimingSafeEqual, which compares in constant time. - Matching the keyword as a substring.
"buen comentario".includes("comenta")istrue. 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
GETwithhub.challengewhen the verify token matches. - Every
POSTis validated withX-Hub-Signature-256over the raw body, usingtimingSafeEqual. - 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

Published November 3, 2026