InstagramMessenger· 8 min read

Instagram and Messenger DM bookings with utility reminders


Offer open times as quick replies in the DM, store the pick in one bookings table, and ask whether the customer wants the reminder on WhatsApp. At reminder time, pick the route the rules allow. That’s WhatsApp if the customer opted in, a free-form DM if the 24-hour window is still open, or a Messenger utility template. Instagram has no templates, so an Instagram booking outside the window gets no automated reminder.

The reminder template, its TTL and the Confirm and Reschedule handler on WhatsApp are in WhatsApp appointment reminders with Confirm and Reschedule. This post covers the part that starts in a DM. The WhatsApp leg works the same way for class session reminders and technician on-the-way notices, which start from a timetable or a job record, not a DM.

What each channel allows at reminder time

The reminder usually goes out a day after the booking, when the conversation has gone quiet. By then, the window the customer’s last DM opened has often closed.

Channel Window still open Window closed, automated Window closed, a person replying
Messenger Any message Utility template, with the utility permission HUMAN_AGENT tag, up to 7 days
Instagram Any message Nothing HUMAN_AGENT tag, up to 7 days
WhatsApp Any message Utility template Not applicable

On Instagram, “Only HUMAN_AGENT is available for Instagram Messaging”, it needs App Review, and it covers a person replying, never an automated job. Instagram DMs by API: the 24-hour window and human agent tag has the detail. On Messenger, the retired event, account and post-purchase tags now return error 100, as covered in Messenger message tags outside 24 hours. Utility messages replaced them.

So an Instagram booking has three possible outcomes at reminder time. It can go inside the window, if the appointment is soon enough. It can go on WhatsApp, if the customer gave a number and agreed. Or there is none, and a person decides what to do.

Messenger utility messages: what Meta requires

Meta lists “order or account status updates, and appointment or event reminders” as the use for utility messages. They “must not contain marketing materials” (utility messages, accessed 2026-11-25). You need the Page ID, the customer’s PSID, a Page access token and the utility permission.

Meta spells that permission two ways. The utility messages page says page_utility_messaging. The Messenger use-case table in the App Dashboard says pages_utility_messaging and marks it “Optional for this use case” (create an app, accessed 2026-11-25). Search for both names when you request it. Subscribe to message_template_status_update as well, so a rejection or a status change reaches your code. According to Meta, the Page doesn’t need to be linked to a business to send utility messages.

Get a template onto the Page

The first route is to clone a library template with GET /message_template_library, then POST /<PAGE_ID>/message_templates with library_template_name. The only library template the page names is order_confirmation_1, and none covers appointments.

The second route is a Page-owned template. POST /<PAGE_ID>/message_templates takes name, language, category: UTILITY, components and an optional parameter_format: NAMED. Meta says approval comes “within seconds of creation”. The third route is to reuse a template the Page already has.

For this post, create a Page-owned template with a body such as “Reminder: your appointment is on {{1}} at {{2}}. Reply to this message to confirm or change it.” Copy the component JSON from Meta’s page. Meta lists these rejection causes:

  • non-sequential placeholders, or a placeholder at the start or end of the text;
  • special characters in parameters;
  • a high ratio of parameters to words;
  • sensitive identifiers.

Send it and read the tap

The send is POST /<PAGE_ID>/messages with recipient.id set to the PSID and message.template holding name, language.code and components[].parameters[]. The response returns recipient_id and message_id. Meta’s examples are inconsistent about "messaging_type": "UTILITY": some include it and some don’t. The service sends it, so watch the first responses.

Templates can carry a BUTTONS component with URL buttons, which take a {{1}} suffix, or POSTBACK buttons, whose payloads take placeholders. The page doesn’t name the webhook a tap produces. A messaging_postbacks event is the likely candidate, so verify it before you rely on it. The template in this post has no button. Any reply opens a new window, and the bot answers with Confirm and Cancel quick replies while the booking is still unconfirmed.

The page is silent on prior-contact rules, pricing and regions, and it doesn’t mention Instagram. A PSID exists only after the person has interacted with the Page, which a DM booking guarantees.

One table for every channel

The data model keeps the booking separate from the channel it started on. The bookings table holds the slot and status, plus channel and channel_user_id: an IGSID on Instagram, a PSID on Messenger. Two columns, whatsapp_phone and whatsapp_optin, hold the optional WhatsApp route. A contacts table stores last_inbound_at per channel and user, which is the only input the window check needs.

Key customers by channel plus ID. Meta scopes a PSID to one Page and an IGSID to one Instagram account, so the same person has different IDs on each. The same table works for a Telegram chat ID, or for a WhatsApp booking keyed by phone.

The DM flow and the payloads that come back

A quick-reply tap arrives as a normal message event, with your code in message.quick_reply.payload and the label in message.text. A button tap on a template arrives as a messaging_postbacks event with postback.payload. Meta sends that payload only to the app that sent the message. Messenger quick replies, button and generic templates shows both shapes, and Instagram DM quick replies covers the Instagram side.

The conversation goes like this. Any message gets three open times as quick replies, each with a payload SLOT|<iso time>. A tap creates the booking and asks for a WhatsApp number. On Messenger, the service adds a user_phone_number quick reply, which fills in the number from the person’s profile. On Instagram, the customer types it. “No thanks” skips WhatsApp.

That question doubles as the consent record. It names the channel and the purpose, and the customer answers it with an action. Store the answer with the booking, as how to collect WhatsApp opt-in recommends.

The service

This file runs on Python 3.9 or later with the standard library and SQLite. It verifies X-Hub-Signature-256 for both products, answers 200 before working, and runs the reminder job on a thread. The receiver follows the pattern in one webhook endpoint for Messenger and Instagram.

"""Instagram and Messenger DMs to one bookings table, with reminders.

Python 3.9+ standard library only. Run:
  VERIFY_TOKEN=... APP_SECRETS=SECRET_ONE,SECRET_TWO PAGE_ID=... PAGE_ACCESS_TOKEN=... \
  INSTAGRAM_ACCESS_TOKEN=... python3 dm_booking.py
Optional: WA_TOKEN and PHONE_NUMBER_ID for WhatsApp reminders, MESSENGER_UTILITY_TEMPLATE
for an approved Page utility template, PROFESSIONAL, BUSINESS_TZ, DB_PATH, PORT.
"""
import hashlib
import hmac
import json
import os
import queue
import re
import sqlite3
import threading
import time
import urllib.error
import urllib.request
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from zoneinfo import ZoneInfo

VERIFY_TOKEN = os.environ["VERIFY_TOKEN"]
APP_SECRETS = [s.strip() for s in os.environ["APP_SECRETS"].split(",") if s.strip()]
PAGE_ID = os.environ["PAGE_ID"]
PAGE_ACCESS_TOKEN = os.environ["PAGE_ACCESS_TOKEN"]
INSTAGRAM_ACCESS_TOKEN = os.environ["INSTAGRAM_ACCESS_TOKEN"]
WA_TOKEN = os.environ.get("WA_TOKEN", "")
PHONE_NUMBER_ID = os.environ.get("PHONE_NUMBER_ID", "")
UTILITY_TEMPLATE = os.environ.get("MESSENGER_UTILITY_TEMPLATE", "")
PROFESSIONAL = os.environ.get("PROFESSIONAL", "our team")
TZ = ZoneInfo(os.environ.get("BUSINESS_TZ", "UTC"))
DB_PATH = os.environ.get("DB_PATH", "bookings.db")
PORT = int(os.environ.get("PORT", "8000"))

GRAPH = "https://graph.facebook.com/v26.0"
IG_GRAPH = "https://graph.instagram.com/v26.0"
CHANNELS = {"page": "messenger", "instagram": "instagram"}
HOUR = 3600
WINDOW = 24 * HOUR
MARGIN = 10 * 60  # no free-form send in the last 10 minutes of a window
LONG_LEAD = 24 * HOUR
SHORT_LEAD = 2 * HOUR

db = sqlite3.connect(DB_PATH, check_same_thread=False)
db.row_factory = sqlite3.Row
lock = threading.Lock()
db.executescript("""
CREATE TABLE IF NOT EXISTS bookings (
  id INTEGER PRIMARY KEY,
  channel TEXT NOT NULL,                  -- messenger or instagram, where the booking started
  channel_user_id TEXT NOT NULL,          -- PSID or IGSID
  start_at TEXT NOT NULL,                 -- ISO 8601 in UTC
  created_at REAL NOT NULL,
  status TEXT NOT NULL DEFAULT 'booked',  -- booked, confirmed, cancelled
  whatsapp_phone TEXT,
  whatsapp_optin INTEGER NOT NULL DEFAULT 0,
  reminder TEXT                           -- NULL, sending:<route>, sent:<route>, failed:<route>, none, skipped
);
CREATE TABLE IF NOT EXISTS contacts (
  channel TEXT NOT NULL,
  channel_user_id TEXT NOT NULL,
  last_inbound_at REAL,
  state TEXT,
  PRIMARY KEY (channel, channel_user_id)
);
CREATE TABLE IF NOT EXISTS seen (key TEXT PRIMARY KEY);
""")
jobs = queue.Queue()


def sql(query, params=()):
    with lock, db:
        cur = db.execute(query, params)
        return cur.fetchall() if cur.description else cur.lastrowid


def first_seen(key):
    try:
        sql("INSERT INTO seen (key) VALUES (?)", (key,))
        return True
    except sqlite3.IntegrityError:
        return False


def now_iso():
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def label(iso):
    return datetime.fromisoformat(iso).astimezone(TZ).strftime("%a %b %d, %I:%M %p")


def post_json(url, body, headers=None, attempts=3):
    data = json.dumps(body).encode()
    for attempt in range(1, attempts + 1):
        req = urllib.request.Request(url, data=data, method="POST",
                                     headers={"Content-Type": "application/json", **(headers or {})})
        try:
            with urllib.request.urlopen(req, timeout=15) as resp:
                return json.loads(resp.read() or b"{}")
        except urllib.error.HTTPError as err:
            detail = err.read().decode(errors="replace")
            if (err.code != 429 and err.code < 500) or attempt == attempts:
                raise RuntimeError(f"HTTP {err.code}: {detail}") from None
        except urllib.error.URLError:
            if attempt == attempts:
                raise
        time.sleep(2 ** attempt)


def send_dm(channel, user_id, message, messaging_type="RESPONSE"):
    if channel == "messenger":
        body = {"recipient": {"id": user_id}, "messaging_type": messaging_type, "message": message}
        return post_json(f"{GRAPH}/me/messages?access_token={PAGE_ACCESS_TOKEN}", body)
    body = {"recipient": {"id": user_id}, "message": message}
    return post_json(f"{IG_GRAPH}/me/messages?access_token={INSTAGRAM_ACCESS_TOKEN}", body)


def quick_replies(text, options):
    return {"text": text, "quick_replies": [
        {"content_type": "text", "title": title[:20], "payload": payload} for title, payload in options]}


def set_state(channel, user, state):
    sql("UPDATE contacts SET state = ? WHERE channel = ? AND channel_user_id = ?", (state, channel, user))


def open_slots():
    """Stub: replace with a query on your calendar. Returns ISO start times in UTC."""
    base = datetime.now(TZ).replace(hour=10, minute=0, second=0, microsecond=0)
    return [(base + timedelta(days=d)).astimezone(timezone.utc).isoformat(timespec="seconds") for d in (1, 2, 3)]


def book(channel, user, start_at):
    try:
        start = datetime.fromisoformat(start_at)
    except ValueError:
        return None
    if start <= datetime.now(timezone.utc):
        return send_dm(channel, user, {"text": "That time has passed. Send any message to see new times."})
    # Check here that the slot is still free in your calendar.
    existing = sql("SELECT id FROM bookings WHERE channel = ? AND channel_user_id = ? AND start_at = ? "
                   "AND status != 'cancelled'", (channel, user, start_at))
    booking_id = existing[0]["id"] if existing else sql(
        "INSERT INTO bookings (channel, channel_user_id, start_at, created_at) VALUES (?, ?, ?, ?)",
        (channel, user, start_at, time.time()))
    set_state(channel, user, f"ask_whatsapp|{booking_id}")
    options = [{"content_type": "text", "title": "No thanks", "payload": f"NO_WA|{booking_id}"}]
    if channel == "messenger":
        options.insert(0, {"content_type": "user_phone_number"})  # documented for Messenger
    return send_dm(channel, user, {
        "text": f"Booked for {label(start_at)}. Want a reminder on WhatsApp? "
                "Send your WhatsApp number with the country code, or tap No thanks.",
        "quick_replies": options,
    })


def update_booking(channel, user, booking_id, action):
    rows = sql("SELECT * FROM bookings WHERE id = ? AND channel = ? AND channel_user_id = ?",
               (booking_id, channel, user))
    if not rows:
        return None
    b = rows[0]
    if b["status"] == "cancelled":
        return send_dm(channel, user, {"text": "This booking is already cancelled."})
    if b["start_at"] <= now_iso():
        return send_dm(channel, user, {"text": "This booking has already passed."})
    new_status = "confirmed" if action == "CONFIRM" else "cancelled"
    if b["status"] == new_status:
        return None  # a repeated tap
    sql("UPDATE bookings SET status = ? WHERE id = ?", (new_status, b["id"]))  # the write-back
    if new_status == "confirmed":
        return send_dm(channel, user, {"text": f"Confirmed for {label(b['start_at'])}."})
    return send_dm(channel, user, {"text": "Your booking is cancelled."})


def handle(channel, event):
    user = str(event.get("sender", {}).get("id"))
    message = event.get("message") or {}
    postback = event.get("postback") or {}
    payload = postback.get("payload") or (message.get("quick_reply") or {}).get("payload") or ""
    text = (message.get("text") or "").strip()
    sql("INSERT INTO contacts (channel, channel_user_id, last_inbound_at) VALUES (?, ?, ?) "
        "ON CONFLICT (channel, channel_user_id) DO UPDATE SET last_inbound_at = excluded.last_inbound_at",
        (channel, user, (event.get("timestamp") or time.time() * 1000) / 1000))
    rows = sql("SELECT state FROM contacts WHERE channel = ? AND channel_user_id = ?", (channel, user))
    state = rows[0]["state"] if rows else None

    if text.upper() == "STOP":
        sql("UPDATE bookings SET whatsapp_optin = 0 WHERE channel = ? AND channel_user_id = ?", (channel, user))
        return send_dm(channel, user, {"text": "OK. No WhatsApp reminders for your bookings."})
    if payload.startswith("SLOT|"):
        return book(channel, user, payload.split("|", 1)[1])
    if payload.startswith("NO_WA|"):
        set_state(channel, user, None)
        return send_dm(channel, user, {"text": "OK, no WhatsApp reminder. See you then."})
    if payload.startswith(("CONFIRM|", "CANCEL|")):
        action, booking_id = payload.split("|", 1)
        return update_booking(channel, user, booking_id, action)
    if state and state.startswith("ask_whatsapp|"):
        number = re.sub(r"\D", "", payload or text)
        if 8 <= len(number) <= 15:
            sql("UPDATE bookings SET whatsapp_phone = ?, whatsapp_optin = 1 WHERE id = ?",
                (number, int(state.split("|")[1])))
            set_state(channel, user, None)
            return send_dm(channel, user, {
                "text": "Thanks. Reminders for this booking will come on WhatsApp. Reply STOP here to turn them off."})
    upcoming = sql("SELECT id, start_at FROM bookings WHERE channel = ? AND channel_user_id = ? "
                   "AND status = 'booked' AND start_at > ? ORDER BY start_at LIMIT 1", (channel, user, now_iso()))
    if upcoming and payload != "NEW":
        b = upcoming[0]
        return send_dm(channel, user, quick_replies(
            f"You have a booking on {label(b['start_at'])}. What would you like to do?",
            [("Confirm", f"CONFIRM|{b['id']}"), ("Cancel", f"CANCEL|{b['id']}"), ("Book another time", "NEW")]))
    return send_dm(channel, user, quick_replies(
        "Which time works for you?", [(label(s), f"SLOT|{s}") for s in open_slots()]))


def pick_route(b, now):
    if b["whatsapp_optin"] and b["whatsapp_phone"] and WA_TOKEN and PHONE_NUMBER_ID:
        return "whatsapp"
    if b["last_inbound_at"] and now < b["last_inbound_at"] + WINDOW - MARGIN:
        return "dm"
    if b["channel"] == "messenger" and UTILITY_TEMPLATE:
        return "messenger_utility"
    return "none"  # Instagram outside the window has no automated path


def send_reminder(b, route, lead):
    start = datetime.fromisoformat(b["start_at"]).astimezone(TZ)
    date_text = start.strftime("%A, %B %d")
    time_text = start.strftime("%I:%M %p").lstrip("0")
    if route == "whatsapp":
        # reminder_24h and reminder_2h from the WhatsApp reminder post. Taps reach your WhatsApp webhook.
        components = [{"type": "body", "parameters": [
            {"type": "text", "parameter_name": "customer_name", "text": "there"},
            {"type": "text", "parameter_name": "date", "text": date_text},
            {"type": "text", "parameter_name": "time", "text": time_text},
            {"type": "text", "parameter_name": "professional", "text": PROFESSIONAL},
        ]}]
        for index, action in enumerate(("confirm", "reschedule")):
            components.append({"type": "button", "sub_type": "quick_reply", "index": str(index),
                               "parameters": [{"type": "payload", "payload": f"bk|{b['id']}|{action}"}]})
        return post_json(f"{GRAPH}/{PHONE_NUMBER_ID}/messages", {
            "messaging_product": "whatsapp", "to": b["whatsapp_phone"], "type": "template",
            "template": {"name": f"reminder_{lead}", "language": {"code": "en_US"}, "components": components},
        }, {"Authorization": f"Bearer {WA_TOKEN}"})
    if route == "dm":
        return send_dm(b["channel"], b["channel_user_id"], quick_replies(
            f"Reminder: your appointment is on {date_text} at {time_text}.",
            [("Confirm", f"CONFIRM|{b['id']}"), ("Cancel", f"CANCEL|{b['id']}")]), messaging_type="UPDATE")
    # Messenger utility template approved on the Page. Check the parameter shape against Meta's page.
    return post_json(f"{GRAPH}/{PAGE_ID}/messages?access_token={PAGE_ACCESS_TOKEN}", {
        "recipient": {"id": b["channel_user_id"]},
        "messaging_type": "UTILITY",
        "message": {"template": {"name": UTILITY_TEMPLATE, "language": {"code": "en_US"}, "components": [
            {"type": "body", "parameters": [{"type": "text", "text": date_text}, {"type": "text", "text": time_text}]},
        ]}},
    })


def reminder_loop():
    while True:
        time.sleep(60)
        now = time.time()
        rows = sql("SELECT b.*, c.last_inbound_at FROM bookings b LEFT JOIN contacts c "
                   "ON c.channel = b.channel AND c.channel_user_id = b.channel_user_id "
                   "WHERE b.reminder IS NULL AND b.status IN ('booked', 'confirmed')")
        for b in rows:
            start = datetime.fromisoformat(b["start_at"]).timestamp()
            lead = "24h" if b["created_at"] <= start - LONG_LEAD else "2h"
            if lead == "24h" and now >= start - LONG_LEAD + 12 * HOUR:
                lead = "2h"  # too late for the day-ahead reminder: wait for T-2h
            if now < start - (LONG_LEAD if lead == "24h" else SHORT_LEAD):
                continue
            if now >= start or b["created_at"] > start - SHORT_LEAD:
                sql("UPDATE bookings SET reminder = 'skipped' WHERE id = ?", (b["id"],))
                continue
            route = pick_route(b, now)
            if route == "none":
                sql("UPDATE bookings SET reminder = 'none' WHERE id = ?", (b["id"],))
                print("no reminder route, hand to a person:", b["id"], flush=True)
                continue
            sql("UPDATE bookings SET reminder = ? WHERE id = ?", (f"sending:{route}", b["id"]))
            try:
                send_reminder(b, route, lead)
                sql("UPDATE bookings SET reminder = ? WHERE id = ?", (f"sent:{route}", b["id"]))
            except Exception as exc:
                sql("UPDATE bookings SET reminder = ? WHERE id = ?", (f"failed:{route}", b["id"]))
                print("reminder failed", b["id"], route, exc, flush=True)


def process(payload):
    for envelope in payload if isinstance(payload, list) else [payload]:
        channel = CHANNELS.get(envelope.get("object"))
        if not channel:
            continue
        for entry in envelope.get("entry", []):
            for event in entry.get("messaging", []):
                message = event.get("message") or {}
                postback = event.get("postback") or {}
                if message.get("is_echo") or not (message or postback):
                    continue  # our own messages, reads, reactions
                mid = message.get("mid") or postback.get("mid") or f"{event.get('timestamp')}:{postback.get('payload')}"
                if not first_seen(f"{channel}:{entry.get('id')}:{mid}"):
                    continue  # a retried delivery
                try:
                    handle(channel, event)
                except Exception as exc:
                    print("handler error", channel, mid, exc, flush=True)


def worker():
    while True:
        payload = jobs.get()
        process(payload)
        jobs.task_done()


def valid_signature(raw_body, header):
    if not header or not header.startswith("sha256="):
        return False
    received = header[len("sha256="):].encode()
    return any(hmac.compare_digest(received, hmac.new(s.encode(), raw_body, hashlib.sha256).hexdigest().encode())
               for s in APP_SECRETS)


class Webhook(BaseHTTPRequestHandler):
    def do_GET(self):
        query = parse_qs(urlparse(self.path).query)
        token = query.get("hub.verify_token", [""])[0]
        if query.get("hub.mode", [""])[0] == "subscribe" and hmac.compare_digest(token.encode(), VERIFY_TOKEN.encode()):
            self.reply(200, query.get("hub.challenge", [""])[0].encode())
        else:
            self.reply(403, b"")

    def do_POST(self):
        raw_body = self.rfile.read(int(self.headers.get("Content-Length") or 0))
        if not valid_signature(raw_body, self.headers.get("X-Hub-Signature-256")):
            return self.reply(401, b"")
        try:
            payload = json.loads(raw_body)
        except ValueError:
            return self.reply(400, b"")
        self.reply(200, b"")  # answer first, work later
        jobs.put(payload)

    def reply(self, status, body):
        self.send_response(status)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


if __name__ == "__main__":
    threading.Thread(target=worker, daemon=True).start()
    threading.Thread(target=reminder_loop, daemon=True).start()
    ThreadingHTTPServer(("", PORT), Webhook).serve_forever()

The WhatsApp branch sends the two templates from the pillar post, with the booking ID in each payload. Their taps arrive on your WhatsApp webhook, not this endpoint. Point that handler at the same bookings table so Confirm and Reschedule update the same row.

Test the DM side with signed bodies, as in the one-endpoint post. This one is a Messenger quick-reply tap for a time two days ahead. Export APP_SECRET set to one of the values in APP_SECRETS, and replace the slot with a future time. The “10:00 AM” label assumes BUSINESS_TZ=America/New_York.

BODY='{"object":"page","entry":[{"id":"PAGE_ID","time":1795608000000,"messaging":[{"sender":{"id":"PSID_TEST"},"recipient":{"id":"PAGE_ID"},"timestamp":1795608000000,"message":{"mid":"m_test_1","text":"Fri Nov 27, 10:00 AM","quick_reply":{"payload":"SLOT|2026-11-27T15:00:00+00:00"}}}]}]}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$APP_SECRET" | awk '{print $NF}')
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:8000/ \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data-binary "$BODY"

The server answers 200 and inserts the booking. It then tries to send the WhatsApp question to PSID_TEST, which fails against the real Send API and lands in the log.

How the reminder picks a route

A booking made more than 24 hours ahead gets its reminder at T-24h. A booking made between 24 and 2 hours ahead gets it at T-2h instead, which falls inside the window the booking conversation opened. A booking made less than 2 hours ahead gets none, because the booking message already said the time.

At the due time, pick_route checks the options in order. WhatsApp comes first when the customer opted in, because they chose it. Next is a free-form DM with Confirm and Cancel quick replies, if last_inbound_at plus 24 hours, minus a 10-minute margin, is still ahead. On Messenger, the utility template follows. If nothing applies, the row is marked none and logged for a person.

The reminder column is claimed as sending:<route> before the call. Two ticks never send the same reminder twice, even when a send is slow.

When the loop breaks

The window closes before the reminder

This is the normal case for Instagram bookings made days ahead. The service can’t fix it with a tag. HUMAN_AGENT is for a person answering, so a bot reminder sent with it breaks the rule the tag exists for. Ask for the WhatsApp number during the booking, while the window is open. That’s the only automated path Instagram leaves.

The customer replies after the reminder

A reply to the Messenger utility template opens a new window. The service sees an upcoming booked row for that user and answers with Confirm, Cancel and “Book another time”. The same happens when an Instagram customer writes in on their own. Only the latest upcoming booking is offered, so a customer with two bookings needs a person or a list.

Duplicate deliveries and echoes

Meta can deliver the same event more than once. The seen table rejects a repeat by channel, account and mid, and a repeated tap on the same button does nothing. Instagram sends echoes of your own messages with the message subscription, so the service skips anything with is_echo.

The utility template is rejected or changed

Template status changes arrive on message_template_status_update. If the template stops being usable, the send fails, the row becomes failed:messenger_utility, and nobody gets reminded. Alert on that state rather than retrying, because a rejected template fails the same way every time.

The customer opts out

STOP in the DM clears whatsapp_optin on all of that user’s bookings. A STOP sent on WhatsApp reaches your WhatsApp handler instead, which should clear the same column.

Where Z-API Omni fits

Omni connects Instagram and Messenger as META_INSTAGRAM and META_MESSENGER channels, next to WhatsApp and Telegram in one subscription. Inbound DMs arrive as MESSAGE_RECEIVED. INTERACTIVE_BUTTON sends up to three quick replies on both channels, while INTERACTIVE_LIST does not work on them. The opt-in WhatsApp reminder goes out as a template on a Meta Cloud API channel.

Messenger utility templates are not available there today: the docs say support “is being implemented”. That route needs your own Meta app with the utility permission, or a wait. Instagram has no templates at all. The docs also don’t show the inbound quick-reply payload on these channels yet.

curl -X POST "https://api.omni.z-api.io/v1/channels/$CHANNEL_ID/messages" \
  -H "Authorization: Bearer $OMNI_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "recipient": { "identifier": "CONTACT_IDENTIFIER" },
    "content": {
      "type": "INTERACTIVE_BUTTON",
      "body": { "message": "Which time works for you?" },
      "attachments": [
        { "id": "SLOT|2026-11-27T15:00:00+00:00", "title": "Fri Nov 27, 10:00 AM" },
        { "id": "SLOT|2026-11-28T15:00:00+00:00", "title": "Sat Nov 28, 10:00 AM" },
        { "id": "SLOT|2026-11-29T15:00:00+00:00", "title": "Sun Nov 29, 10:00 AM" }
      ]
    }
  }'

View documentation

Z-API Omni team