DEV Community

Cover image for Automating Engagement and Customer Interactions Through Social Media APIs
Kevin Meneses González
Kevin Meneses González

Posted on Originally published at kevinmeneses.com

Automating Engagement and Customer Interactions Through Social Media APIs

Publishing is a solved problem. Replying isn't.

Any scheduler can push a post to six networks. Then the comments arrive on Instagram, a DM lands in Messenger, someone asks about shipping on WhatsApp, and a 2-star review shows up on Google. Each one lives in a different app, under a different API, with different rules about when you're allowed to answer.

If you're:

  • building a SaaS that manages social accounts for customers,
  • running support for a brand that sells through Instagram and WhatsApp,
  • or an agency answering for a dozen clients,

this is where your team's hours actually go.

(If you'd rather have an AI agent handle publishing too, I covered that in Building an AI Social Media Agent with Claude Code and Postproxy MCP.)


Why engagement is harder to automate than publishing

Publishing is outbound. You decide when it happens.

Engagement is inbound. It happens when the customer decides, on whatever platform they picked. To automate it with native APIs you need:

  • Meta's Graph API for Instagram comments, Facebook comments and Messenger
  • The WhatsApp Business Platform, with its own templates and phone numbers
  • The Google Business Profile API for reviews
  • TikTok, YouTube and Threads APIs for their comment sections
  • A webhook receiver for each one, all with different payloads and signatures

And then the rules. Meta only lets you send free-form messages within 24 hours of the customer's last message. A Google review can carry one reply. TikTok lets you pin one comment per video.

Most teams try this, build two integrations, and go back to answering by hand.

The problem isn't the replies.

It's that every inbox speaks a different language.


The unified engagement API approach

A unified social media API puts all of those inboxes behind one schema. Postproxy is the one I'll use here, because its engagement layer goes further than most: the same API that publishes your posts also handles comments, direct messages and reviews.

Three parts of the API do the work:

  • Comments API: list, reply, hide, delete, like and pin comments on Instagram, Facebook, Threads, YouTube, TikTok and Bluesky
  • Direct Messages API: chats and messages on Instagram, Facebook Messenger, WhatsApp, Telegram and Bluesky
  • Profile Comments API: Google Business reviews and Facebook Page recommendations

On top of that, webhooks tell your server the moment something happens: message.received, comment.created, profile_comment.created, and dozens more.

👉 You can try all of this on Postproxy's free plan (10 posts a month, no card). Engagements like comments, DMs and replies are unlimited on the paid plans.


The architecture

Here's what we'll build:

Architecture of a social media engagement bot: DMs arrive by webhook, comments and reviews are swept by a cron job, and anything uncertain goes to a human

DMs go through webhooks, because customers in a chat expect an answer in minutes. Comments and reviews go through a short polling job: they're less urgent, and Google reviews only sync hourly anyway.

The rule behind the whole design: automate the obvious, escalate the rest. A bot that answers "do you ship to Mexico?" saves hours. A bot that answers an angry customer makes things worse.


Step 1. Register a webhook

You register webhooks through the API. Subscribe only to the events you handle:

import os
import requests

API = "https://api.postproxy.dev/api"
HEADERS = {
    "Authorization": f"Bearer {os.environ['POSTPROXY_API_KEY']}",
    "Content-Type": "application/json",
}

response = requests.post(
    f"{API}/webhooks",
    headers=HEADERS,
    json={
        "url": "https://your-app.com/webhooks/postproxy",
        "events": ["message.received", "comment.created", "profile_comment.created"],
        "description": "Engagement bot",
    },
)
response.raise_for_status()
print(response.json()["secret"])  # store it now, e.g. in POSTPROXY_WEBHOOK_SECRET
Enter fullscreen mode Exit fullscreen mode

Save the secret straight away. Postproxy only shows it on creation and when you fetch that single webhook, and you need it to verify every delivery.


Step 2. Receive and verify events

Every delivery carries an X-Postproxy-Signature header in the format t=<timestamp>,v1=<hmac>. The signature is an HMAC-SHA256 of {timestamp}.{raw_body} with your secret. Verify it before you trust anything in the payload.

A minimal Flask receiver:

import hashlib
import hmac
import os

import requests
from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["POSTPROXY_WEBHOOK_SECRET"]


def verify_webhook(payload: str, signature_header: str, secret: str) -> bool:
    parts = dict(p.split("=", 1) for p in signature_header.split(","))
    signed_payload = f"{parts['t']}.{payload}"
    computed = hmac.new(secret.encode(), signed_payload.encode(), hashlib.sha256).hexdigest()
    return hmac.compare_digest(computed, parts["v1"])


@app.post("/webhooks/postproxy")
def postproxy_webhook():
    raw = request.get_data(as_text=True)
    signature = request.headers.get("X-Postproxy-Signature", "")
    if not signature or not verify_webhook(raw, signature, SECRET):
        abort(401)

    event = request.get_json()
    if event["type"] == "message.received":
        handle_message(event["data"]["object"])

    return "", 200
Enter fullscreen mode Exit fullscreen mode

Return a 2xx fast. Postproxy expects a response within 30 seconds and retries a failed delivery up to 5 times with backoff (1 minute, 5 minutes, 30 minutes, 2 hours). For anything slow, like an LLM call, push the event to a queue and answer the webhook right away.


Step 3. Auto-reply to DMs, and know when not to

First, a setup detail that cost me a few minutes: direct messages are opt-in in Postproxy. Until you enable them at app.postproxy.dev/chats, the chat endpoints return 422 with a message telling you to do exactly that.

A message.received event includes the chat_id and the customer's body. That's all you need to answer. Add this to the same file as the receiver:

API = "https://api.postproxy.dev/api"
HEADERS = {
    "Authorization": f"Bearer {os.environ['POSTPROXY_API_KEY']}",
    "Content-Type": "application/json",
}

FAQ = {
    ("ship", "shipping", "envío", "envios"): "Yes, we ship worldwide. Orders leave within 48h.",
    ("return", "refund", "devolución"): "You have 30 days to return any order: https://shop.example.com/returns",
    ("hours", "open", "horario"): "Support is online Monday to Friday, 9:00 to 18:00 CET.",
}


def notify_human(item: dict) -> None:
    print("NEEDS A HUMAN:", item.get("body"))  # replace with Slack, email or your helpdesk


def classify(text: str) -> str | None:
    text = (text or "").lower()
    for keywords, answer in FAQ.items():
        if any(k in text for k in keywords):
            return answer
    return None


def handle_message(message: dict) -> None:
    answer = classify(message["body"])
    if answer is None:
        notify_human(message)
        return

    requests.post(
        f"{API}/chats/{message['chat_id']}/messages",
        headers=HEADERS,
        json={"body": answer},
    ).raise_for_status()
Enter fullscreen mode Exit fullscreen mode

The send returns 202 Accepted with status: "pending". Delivery is asynchronous, and the result arrives later as message.sent, message.delivered or message.failed webhooks.

The keyword matcher is deliberately dumb. Swap classify() for an LLM call when you outgrow it, but keep the same contract: return an answer only when you're confident, return None otherwise. Every None goes to a person.

On Instagram and Messenger you can also send quick replies, so the customer taps instead of typing:

requests.post(
    f"{API}/chats/{chat_id}/messages",
    headers=HEADERS,
    json={
        "body": "What can I help with?",
        "quick_replies": [
            {"title": "Track order", "payload": "TRACK"},
            {"title": "Talk to support", "payload": "HELP"},
        ],
    },
)
Enter fullscreen mode Exit fullscreen mode

Step 4. The 24-hour rule (read this before you ship)

This is where most engagement bots get accounts restricted.

Instagram and Facebook: Meta only allows free-form messages within 24 hours of the customer's last inbound message. After that, a human agent can still answer for up to 7 days by sending with "tag": "HUMAN_AGENT". Postproxy doesn't enforce the 7-day limit; a late message is passed to Meta, rejected, and ends up as failed.

Two rules for that tag:

  • Only a real person should use it. Never put it on bot messages.
  • Never send promotional content with it. Postproxy's docs warn this can get your Page's or Instagram account's messaging suspended.

WhatsApp: no tag. Outside the window you need an approved template. Each chat carries a within_messaging_window flag you can check before sending.

Telegram: no window, but your bot can only message users who have written to it first.

Bluesky: no window either, but the recipient must have DMs enabled.

Build these into the bot from day one. If a webhook arrives for a 3-day-old chat, the bot shouldn't answer it. A person should.


Step 5. Reply to comments on a schedule

Comments are less urgent than DMs, so a polling job every 15 minutes works well. GET /api/comments returns comments across all your posts, newest first, with the post_id and profile_id you need to reply.

One trap I hit while testing this: the from filter works on created_at, which is when Postproxy synced the comment, not when the person wrote it. When you connect an account, Postproxy imports its existing comments. On my YouTube channel, the first sync brought in comments from 2020, all with today's created_at. A bot that trusts from alone would answer five-year-old comments on its first run.

So the sweep also checks posted_at:

import json
from datetime import datetime, timedelta, timezone
from pathlib import Path

SEEN_FILE = Path("seen_comments.json")
OUR_USERNAMES = {"@acmeshop", "acme_shop"}  # as each platform shows it; YouTube adds "@"
MAX_AGE = timedelta(days=2)


def load_seen() -> set:
    return set(json.loads(SEEN_FILE.read_text())) if SEEN_FILE.exists() else set()


def is_recent(comment: dict) -> bool:
    if not comment["posted_at"]:
        return False
    posted = datetime.fromisoformat(comment["posted_at"].replace("Z", "+00:00"))
    return datetime.now(timezone.utc) - posted < MAX_AGE


def sweep_comments() -> None:
    seen = load_seen()
    since = (datetime.now(timezone.utc) - MAX_AGE).date().isoformat()
    response = requests.get(
        f"{API}/comments",
        headers=HEADERS,
        params={"from": since, "per_page": 100},
    )
    response.raise_for_status()

    for comment in response.json()["data"]:
        is_top_level = comment["parent_external_id"] is None
        is_ours = comment["author_username"] in OUR_USERNAMES
        if comment["id"] in seen or not is_top_level or is_ours or not is_recent(comment):
            continue

        answer = classify(comment["body"])
        if answer:
            requests.post(
                f"{API}/posts/{comment['post_id']}/comments",
                headers=HEADERS,
                params={"profile_id": comment["profile_id"]},
                json={"body": answer, "parent_id": comment["id"]},
            ).raise_for_status()
        else:
            notify_human(comment)

        seen.add(comment["id"])

    SEEN_FILE.write_text(json.dumps(sorted(seen)))
Enter fullscreen mode Exit fullscreen mode

Each comment also carries metadata such as follower_count and is_verified_user on Instagram. That's useful for routing: a comment from an account with 50k followers probably deserves a human.

For spam, POST /api/posts/:post_id/comments/:id/hide hides a comment without deleting it. That works on Instagram, Facebook, Threads and TikTok.

And if a question in public deserves a private answer, Instagram and Facebook support a private reply: a DM to the comment's author, sent through POST /api/posts/:post_id/comments/:id/private_reply. You get one per comment, and it works on comments up to 7 days old.


Step 6. Handle Google reviews (carefully)

Reviews are the most public thing your bot will ever touch. Treat them differently.

def sweep_reviews(profile_id: str) -> None:
    response = requests.get(
        f"{API}/profiles/{profile_id}/comments",
        headers=HEADERS,
        params={"per_page": 20},
    )
    response.raise_for_status()

    for review in response.json()["data"]:
        if review["replies"]:
            continue  # already answered

        stars = (review.get("platform_data") or {}).get("star_rating")
        if stars is None or stars <= 3:
            notify_human(review)  # never auto-reply to a bad review
            continue

        requests.post(
            f"{API}/profiles/{profile_id}/comments",
            headers=HEADERS,
            json={
                "parent_id": review["external_id"],
                "body": "Thank you for the review! We're glad you enjoyed it.",
            },
        ).raise_for_status()
Enter fullscreen mode Exit fullscreen mode

A few details the API handles that you'd otherwise discover the hard way:

  • Google reviews can be star-only, with body set to null. The code above doesn't depend on the text.
  • A Google review takes one reply. Replying again updates it.
  • Google can reject a reply for policy reasons. platform_data.reply_state tells you if it's PENDING, APPROVED or REJECTED.
  • Nobody can delete a review through the API, only their own reply. That's a platform rule.

Positive reviews get a fast thank-you. Anything at 3 stars or below goes to a person who can actually fix the problem.


What each platform supports

Not every action exists everywhere. Here's the comments support according to Postproxy's reference:

Action Instagram Facebook Threads Bluesky YouTube TikTok LinkedIn
List ✅ ✅ ✅ ✅ ✅ ✅ Coming soon
Reply ✅ ✅ ✅ — ✅ ✅ Coming soon
Hide ✅ ✅ ✅ — — ✅ Coming soon
Delete ✅ ✅ — — ✅ ✅ Coming soon
Pin — — — — — ✅ —

Calling an unsupported action returns 405 Method Not Allowed, so your code can try and fall back cleanly.


Key takeaways

  • Engagement is an inbound, event-driven problem. Use webhooks for DMs and a short polling job for comments and reviews.
  • Automate only the questions you can answer with confidence. Everything else, and every bad review, goes to a human.
  • The platform rules (24h window, HUMAN_AGENT, one reply per review) are part of the design, not edge cases.

Most brands don't lose customers because of their posts.

They lose them in the replies nobody sent.

👉 Build your engagement bot on Postproxy: one API for comments, DMs and reviews across every platform, with a free plan to start.


Looking for technical content for your company? I can help — LinkedIn · kevinmenesesgonzalez@gmail.com

Top comments (0)