DEV Community

Cover image for Instagram DM automation: let code own prices and slots, and check every draft against it
MatIntellect
MatIntellect

Posted on Edited on Originally published at matintellect.com AI-assisted

Instagram DM automation: let code own prices and slots, and check every draft against it

Problem: a booking bot in Instagram Direct can write a fluent reply with a price that is not in the price list or a time that is already taken. Result: a split where code returns exact prices and free slots, and a checker rejects any drafted reply that contains a number code did not return or touches a forbidden topic. Stack: Python 3.10+ standard library (tested on 3.15.2). Boundaries: the model that drafts replies is not included; the example uses hand-written drafts to show what the checker accepts and rejects

AI-generated illustration of Instagram DM automation with checks

The design

In Direct, people write in their own words, send voice notes, ask several things at once and come back a day later. A language model handles that conversational part well. Prices, dates and appointment times are a different matter: they must be exact, so they come from code that reads the price list and the calendar

On top of that, a second check looks at every drafted reply before it is sent. In production I use a second model for the rule part, for example "do not discuss contraindications", and code for the numeric part. The example below implements both as simple code so the idea is testable in isolation

I built an AI receptionist for a clinic in Instagram Direct on this pattern. It answers only from the clinic's documents, about 114 price items and 48 services, takes prices from the price list rather than the model's memory, and sends a card to the doctor in Telegram; the booking appears only after the doctor confirms. This article is a teaching version of the idea, not that bot's code

Input, processing, output

Input: a requested service and day; a drafted reply from the conversation model

Processing: code looks up the price and free slots, or the nearest day with slots; the checker extracts every number-like token from the draft and rejects it unless code returned it, and rejects forbidden topics

Output: the facts for the model to use, and a list of problems for each draft (empty means it may be sent)

Discussing an appointment

The example

Prices, dates and drafts are invented for illustration

PRICES = {"consultation": 50, "cleaning": 80}
CALENDAR = {"2026-11-14": ["11:00", "14:00"], "2026-11-15": []}
FORBIDDEN = ("contraindication",)

def facts(service, day):
    """Code side: exact data only, never guessed."""
    price = PRICES.get(service)
    slots = CALENDAR.get(day)
    if slots == []:
        nearest = next(((d, s) for d, s in sorted(CALENDAR.items()) if s), None)
        return {"price": price, "slots": [], "nearest": nearest}
    return {"price": price, "slots": slots or [], "nearest": None}

def check_reply(reply: str, data: dict) -> list[str]:
    """Checker side: the drafted reply may only use numbers code returned and must respect rules."""
    problems = [f"forbidden topic: {w}" for w in FORBIDDEN if w in reply.lower()]
    allowed = {str(data["price"])} | set(data["slots"]) | ({data["nearest"][1][0]} if data["nearest"] else set())
    for token in reply.replace(",", " ").split():
        if any(ch.isdigit() for ch in token) and token.strip(".") not in allowed:
            problems.append(f"number not from code: {token}")
    return problems

if __name__ == "__main__":
    d = facts("cleaning", "2026-11-14")
    print("facts:", d)
    print("draft 1:", check_reply("Cleaning costs 80, free at 11:00 or 14:00", d) or "ok")
    print("draft 2:", check_reply("Cleaning costs 75, free at 11:00", d) or "ok")
    print("draft 3:", check_reply("No contraindication for you, 80 at 14:00", d) or "ok")
    print("sunday:", facts("cleaning", "2026-11-15"))
Enter fullscreen mode Exit fullscreen mode

Output, exactly as printed when I ran it:

facts: {'price': 80, 'slots': ['11:00', '14:00'], 'nearest': None}
draft 1: ok
draft 2: ['number not from code: 75']
draft 3: ['forbidden topic: contraindication']
sunday: {'price': 80, 'slots': [], 'nearest': ('2026-11-14', ['11:00', '14:00'])}
Enter fullscreen mode Exit fullscreen mode

Draft 2 is the failure this design exists for: a plausible price that appears nowhere. Draft 3 is the other one: a correct number wrapped in a topic the bot must not discuss

Design notes

Code returns, the model phrases. The model never decides a price or a slot; it receives them and turns them into a sentence. If code returns nothing, the model says it will check with the receptionist

Nearest options instead of invention. When a day is full, code returns the nearest day with slots, and the model offers that. It never proposes a time code did not return

Check what is sent, not what was intended. The checker reads the final draft. A model can receive the right price and still type a different one; only a check on the outgoing text catches that

Separate checkers for separate jobs. Rules about topics need judgement, which is why production uses a second model for them; numbers need exactness, which is why code checks them. Neither check relies on the model that wrote the reply

Phone and planner for bookings

Errors and limits

Token matching is crude. "80.00" versus "80", or a time written as "2 pm", will be flagged. Normalise formats in the drafting prompt or in the checker

Forbidden topics by keyword are only a demo. Real rules need a model check, because customers ask cleverly and in many languages

Test on real messages. Voice notes with noise, three questions in one message and a return to the price a day later are where both the model and the checker are tested properly

Reproduce it

  1. Save the code as booking.py and run python3 booking.py
  2. Compare with the output above
  3. Add a slot for 2026-11-15 and confirm the "sunday" line returns it with no nearest suggestion
  4. Change draft 2 to 80 and confirm it passes

A bot like this, with one core for Direct, WhatsApp and website chat, takes me about 2–3 weeks including testing. The non-technical version: Instagram DM automation: booking with checks

This article was created with the help of AI.

Top comments (0)