Systems Library / Customer Service / How to Build an Instagram DM AI Responder
Customer Service chatbots

How to Build an Instagram DM AI Responder

Respond to Instagram DMs automatically with AI-powered conversations.

Jay Banlasan

Jay Banlasan

The AI Systems Guy

An instagram dm ai auto responder for your business catches every DM the moment it arrives. I build these for brands running Instagram ads where DMs are a primary conversion channel. The ad says "DM us for details" and the bot responds instantly with qualification questions and answers.

Instagram uses the same Messenger Platform API as Facebook, so the architecture is nearly identical to a Messenger bot.

What You Need Before Starting

Step 1: Set Up Instagram Messaging API

In Meta Developer Portal, add Instagram to your Messenger app. Subscribe to instagram_messaging webhooks:

from flask import Flask, request
import requests
import anthropic
import os

app = Flask(__name__)
client = anthropic.Anthropic()
IG_TOKEN = os.getenv("INSTAGRAM_PAGE_TOKEN")

@app.route("/webhook", methods=["GET"])
def verify():
    if request.args.get("hub.verify_token") == os.getenv("VERIFY_TOKEN"):
        return request.args.get("hub.challenge"), 200
    return "Forbidden", 403

@app.route("/webhook", methods=["POST"])
def webhook():
    data = request.json
    for entry in data.get("entry", []):
        for event in entry.get("messaging", []):
            if event.get("message") and event["message"].get("text"):
                handle_dm(event["sender"]["id"], event["message"]["text"])
    return "OK", 200

Step 2: Build the Response Logic

Configure the AI to match your brand voice and handle common DM types:

SYSTEM_PROMPT = """You are responding to Instagram DMs for [Your Brand].
Voice: Friendly, casual, helpful. Match Instagram's vibe.
Keep responses short (under 150 words). Use line breaks for readability.

Handle these scenarios:
1. Product questions - answer from the catalog below
2. Pricing inquiries - share relevant pricing and link to book
3. Collaboration requests - ask for their follower count and niche
4. General questions - answer or direct to the right resource

CATALOG AND PRICING:
[Your product/service info here]"""

def handle_dm(sender_id, text):
    history = get_history(sender_id)
    history.append({"role": "user", "content": text})

    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=300,
        system=SYSTEM_PROMPT,
        messages=history[-10:]
    )

    reply = response.content[0].text
    save_message(sender_id, "user", text)
    save_message(sender_id, "assistant", reply)
    send_instagram_reply(sender_id, reply)

Step 3: Send Replies via the API

def send_instagram_reply(recipient_id, text):
    url = "https://graph.facebook.com/v18.0/me/messages"
    payload = {
        "recipient": {"id": recipient_id},
        "message": {"text": text},
        "messaging_type": "RESPONSE"
    }
    headers = {"Authorization": f"Bearer {IG_TOKEN}"}
    response = requests.post(url, json=payload, headers=headers)
    return response.json()

Step 4: Handle Story Replies and Mentions

Instagram sends story replies as messages with attachments. Detect and handle them:

def handle_story_reply(event):
    sender_id = event["sender"]["id"]
    story_url = event["message"].get("attachments", [{}])[0].get("payload", {}).get("url")
    text = event["message"].get("text", "")

    if story_url:
        reply = f"Thanks for replying to our story! {generate_response(text)}"
        send_instagram_reply(sender_id, reply)

Step 5: Add Business Hours and Away Messages

Outside hours, set expectations:

from datetime import datetime

def is_business_hours():
    now = datetime.now()
    return now.weekday() < 5 and 9 <= now.hour < 18

def handle_dm(sender_id, text):
    if not is_business_hours():
        away_msg = "Thanks for reaching out! Our team is currently offline. We will get back to you first thing in the morning. In the meantime, check out our FAQ: [link]"
        send_instagram_reply(sender_id, away_msg)
        return

    # Normal AI response flow
    process_with_ai(sender_id, text)

What to Build Next

Add keyword triggers from Instagram ad campaigns. When someone DMs a specific word from an ad (like "GUIDE"), automatically send them a lead magnet link and add them to your CRM for follow-up.

Related Reading

Want this system built for your business?

Get a free assessment. We will map every system your business needs and show you the ROI.

Get Your Free Assessment

Related Systems