DEV Community

ZoomApps
ZoomApps

Posted on

Building an Instagram Direct bot with the Messaging API: permissions, webhooks and review

A first Instagram Direct bot usually works within an afternoon. You subscribe to a webhook, receive a message from your own test account, send a reply, and everything looks finished. The trouble starts when a real customer writes in: no webhook arrives because the app lacks the right access level, a Cyrillic reply is rejected for being too long, the bot talks over a manager who has just answered from the phone, or the subscription silently disappears after an hour of downtime.

This post covers the parts that decide whether the integration survives production. Versions and limits match Meta's documentation at the time of writing (Graph API v27.0), so recheck them before you ship.

Step 1: pick the login path first

The login path determines your host, token type, permissions and whether a Facebook Page is involved. Changing it later means asking every connected account to authorize again.

Instagram Login Facebook Login Unified Login
Host graph.instagram.com graph.facebook.com graph.facebook.com
Token Instagram User Facebook User or Page See current docs
Facebook Page Not required Required Not required
Other requirement Professional account Page linked to the account Business portfolio

Meta's overview now recommends Unified Login for new integrations, so read that section before committing. Instagram Login is the shortest path for a bot that only handles Direct, and the examples below use it. In every case the account must be professional.

Step 2: request the smallest permission set

For messaging, you need these scopes:

  • Instagram Login: instagram_business_basic, instagram_business_manage_messages
  • Facebook Login: instagram_basic, instagram_manage_messages, pages_show_list, pages_read_engagement, pages_manage_metadata

The older business_basic style scope names are deprecated, so replace them if you are copying from an old tutorial.

Access level matters as much as the scope name. Standard Access covers accounts you own or manage and people with a role on your app. Advanced Access is required to serve accounts you do not own, and it requires both App Review and Business Verification. This explains the classic "works for me, silent for the client" bug: the code is correct, but the app has never been approved to handle that account.

Instagram Login tokens follow a simple lifecycle:

# Exchange a short-lived token (1 hour) for a long-lived one (60 days). Server-side only.
curl -G "https://graph.instagram.com/access_token" \
  -d grant_type=ig_exchange_token \
  -d client_secret="$IG_APP_SECRET" \
  -d access_token="$SHORT_LIVED_TOKEN"

# Refresh: the token must be at least 24 hours old and still valid.
curl -G "https://graph.instagram.com/refresh_access_token" \
  -d grant_type=ig_refresh_token \
  -d access_token="$LONG_LIVED_TOKEN"
Enter fullscreen mode Exit fullscreen mode

An expired token cannot be refreshed, and the owner has to log in again. Run a daily job that refreshes anything older than 30 days and alerts on failure.

Step 3: a webhook receiver that acknowledges fast

Meta's Messenger Platform webhook docs ask for a 200 OK within 5 seconds. A language model call or a CRM lookup can easily exceed that, so the receiver should do three things only: verify, persist, acknowledge.

import hashlib
import hmac
import os

from fastapi import FastAPI, Header, HTTPException, Query, Request, Response

app = FastAPI()
APP_SECRET = os.environ["IG_APP_SECRET"].encode()
VERIFY_TOKEN = os.environ["IG_VERIFY_TOKEN"].encode()


@app.get("/webhooks/instagram")
def verify(
    mode: str = Query(alias="hub.mode"),
    token: str = Query(alias="hub.verify_token"),
    challenge: str = Query(alias="hub.challenge"),
):
    if mode != "subscribe" or not hmac.compare_digest(token.encode(), VERIFY_TOKEN):
        raise HTTPException(status_code=403)
    return Response(challenge, media_type="text/plain")


def signature_ok(raw_body: bytes, header: str | None) -> bool:
    if not header or not header.startswith("sha256="):
        return False
    expected = hmac.new(APP_SECRET, raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header.removeprefix("sha256="))


@app.post("/webhooks/instagram")
async def receive(
    request: Request,
    x_hub_signature_256: str | None = Header(default=None),
):
    raw_body = await request.body()
    if not signature_ok(raw_body, x_hub_signature_256):
        raise HTTPException(status_code=401)
    await enqueue(raw_body)  # Redis stream, SQS, or a Postgres table
    return Response(status_code=200)
Enter fullscreen mode Exit fullscreen mode

Compute the signature over the raw request bytes. If you parse the JSON and serialize it again, the bytes change and verification fails. Meta also notes that it signs an escaped-Unicode form of the payload, so ä is hashed as the escape sequence \u00e4. Non-ASCII text is exactly where a naive implementation breaks, so include a Cyrillic or emoji message in your integration tests instead of testing only with "hello".

After deploying the endpoint, subscribe the account. Configuring the webhook in the App Dashboard is not enough on its own:

curl -X POST "https://graph.instagram.com/v27.0/$IG_ID/subscribed_apps" \
  -d subscribed_fields=messages,messaging_postbacks,messaging_seen \
  -d access_token="$IG_TOKEN"
Enter fullscreen mode Exit fullscreen mode

Step 4: normalize events and expect duplicates

An inbound text message looks like this:

{
  "object": "instagram",
  "entry": [{
    "id": "IG_BUSINESS_ID",
    "time": 1569262486134,
    "messaging": [{
      "sender": { "id": "CUSTOMER_IGSID" },
      "recipient": { "id": "IG_BUSINESS_ID" },
      "timestamp": 1569262485349,
      "message": { "mid": "MESSAGE_ID", "text": "Do you have this in size M?" }
    }]
  }]
}
Enter fullscreen mode Exit fullscreen mode

Three properties of this feed shape the worker:

  1. Delivery is at least once. Failed notifications are retried, so the same mid can arrive twice.
  2. Order is not guaranteed after failures. Sort by timestamp when rebuilding a conversation.
  3. Your own messages come back. Anything the business sends produces an event with message.is_echo: true, where the sender is your account and the recipient is the customer. If you treat it as inbound, the bot starts replying to itself.
def iter_events(payload: dict):
    if payload.get("object") != "instagram":
        return
    for entry in payload.get("entry", []):
        for item in entry.get("messaging", []):
            message = item.get("message")
            if not message or "mid" not in message:
                continue  # reactions, seen receipts and postbacks go elsewhere
            echo = bool(message.get("is_echo"))
            yield {
                "kind": "echo" if echo else "inbound",
                "account_id": entry["id"],
                "customer_id": item["recipient" if echo else "sender"]["id"],
                "mid": message["mid"],
                "text": message.get("text"),
                "attachments": message.get("attachments", []),
                "ts": item["timestamp"],
            }
Enter fullscreen mode Exit fullscreen mode

Make deduplication a database constraint so that two workers cannot both win:

INSERT INTO ig_message (mid, account_id, customer_id, direction, body, sent_at)
VALUES ($1, $2, $3, $4, $5, to_timestamp($6 / 1000.0))
ON CONFLICT (mid) DO NOTHING
RETURNING mid;
Enter fullscreen mode Exit fullscreen mode

If the query returns no row, the event has already been processed and the worker should stop there.

Step 5: use echoes for human handoff

Managers will keep answering from the Instagram app, whatever your dashboard offers. Echoes let you detect this. When an echo arrives with a mid your bot did not send, a person has joined the conversation and the bot should pause for that customer.

There is a race here. The echo can arrive before your send call returns and stores its message_id, so the bot's own reply may look human. On an unknown echo, wait about three seconds, look up the mid again, and only then set bot_paused_until for the conversation.

Step 6: the messaging window and send limits

You can normally reply within 24 hours of the customer's last message. A person arriving from a Click-to-Direct ad can open a window of up to 7 days. A separate 7-day Human Agent window exists for cases that could not be resolved in the standard window, such as a question sent just before a closed weekend. It is meant for real people, so an automated reply must not use that tag.

from datetime import datetime, timedelta

STANDARD = timedelta(hours=24)
HUMAN_AGENT = timedelta(days=7)


def send_options(last_inbound: datetime, now: datetime, from_human: bool) -> dict | None:
    age = now - last_inbound
    if age <= STANDARD:
        return {}
    if from_human and age <= HUMAN_AGENT:
        return {"messaging_type": "MESSAGE_TAG", "tag": "HUMAN_AGENT"}
    return None  # window closed: do not send
Enter fullscreen mode Exit fullscreen mode

Text is capped at 1000 bytes of UTF-8, not 1000 characters. A Cyrillic letter takes two bytes, so a Russian or Kazakh reply hits the limit at roughly 500 characters. Split on word boundaries:

def split_utf8(text: str, limit: int = 1000) -> list[str]:
    parts, current = [], ""
    for word in text.split(" "):
        candidate = f"{current} {word}" if current else word
        if len(candidate.encode()) <= limit:
            current = candidate
            continue
        if current:
            parts.append(current)
        current = ""
        for char in word:
            if len((current + char).encode()) > limit:
                parts.append(current)
                current = ""
            current += char
    if current:
        parts.append(current)
    return parts
Enter fullscreen mode Exit fullscreen mode

The other numbers worth putting in your rate limiter, per professional account:

API Limit
Send API, text, links, reactions, stickers 100 calls/second
Send API, audio and video 10 calls/second
Conversations API 2 calls/second
Private Replies, posts and reels 750 calls/hour

Attachment limits are 8 MB for images (PNG, JPEG) and 25 MB for audio, video and PDF. The Conversations API limit is the tightest, so run history backfills through a separate slow queue.

Pitfalls that show up in production

The app gets unsubscribed. According to the Messenger Platform docs, webhook failures trigger a developer alert after 15 minutes. After an hour, the app is unsubscribed from the account and must be subscribed again. Monitor the time since the last valid webhook during business hours, and make resubscription part of your recovery runbook.

Messages sit in Requests. First messages from non-followers land in the Requests folder, and inbox folders are not exposed through the API. Replying from a third-party app moves the conversation to General, which can surprise a team that uses folders as a workflow. Requests inactive for 30 days are no longer returned by API calls.

Some content has no usable payload. Disappearing media arrives as ephemeral with no URL, and a shared post gives you only its URL. The bot needs a fallback that asks the customer to describe what they want.

Getting through App Review

Before submitting, make the reviewer's job easy:

  • Request only the permissions the product uses, and describe each one in terms of a user-visible action.
  • Record a screencast of the entire flow: login, granting access, a customer message arriving, the reply being sent and visible in Instagram.
  • Provide a working test account and clear steps, including anything a reviewer must do to trigger the bot.
  • Complete Business Verification early, since Advanced Access depends on it and it can become the slowest step.
  • Set the app to Live. Meta states that an app must be published to receive notifications for its app users.

A useful test before submission is to connect an Instagram account that has no role on your app. If that account fails, you have found the access problem before your first client does.

Wrapping up

A reliable Direct bot comes down to a few decisions: choose the login path deliberately, acknowledge webhooks quickly, deduplicate by mid, treat echoes as a handoff signal, count bytes, and enforce the messaging window in code. To see these constraints in a finished business setup, with answers limited to a price list and complex requests passed to a person along with the history, here is how we run an assistant inside Instagram Direct.

Top comments (0)