Back to Blog
Language How-Tos

How to Build an SMS Auto-Reply Bot in Twilio Using Python

Build a keyword-based SMS auto-reply bot in Python using Flask and TwiML that responds intelligently to inbound messages.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
8 min read
Twilio
Python
How-To
Code
How to Build an SMS Auto-Reply Bot in Twilio Using Python

This tutorial builds a keyword-driven SMS auto-reply bot using Flask, Twilio's TwiML, and Python that responds to inbound messages based on the words or phrases they contain. It targets developers who need to automate responses to common customer questions without a human agent, such as store hours, pricing, or FAQ answers. You will build a Flask webhook with a configurable keyword-to-response dictionary and a sensible fallback for messages that do not match any known keyword.

Prerequisites and Setup

You need Python 3.7 or higher, Flask, and the Twilio SDK installed with pip install twilio flask. Configure your Twilio number to POST inbound SMS to your Flask route in the Twilio Console under the number's Messaging settings. The bot uses a dictionary to map normalized keyword strings to response text, making it easy to add or modify responses without changing the routing logic. Expose your local server with ngrok during development so Twilio can reach your endpoint.

pip install twilio flask

# Twilio Console: set SMS webhook to
# https://xxxx.ngrok.io/bot (HTTP POST)

The Complete Code

The bot normalizes each inbound message to lowercase, strips punctuation, and checks it against a keyword map using substring matching so partial matches work correctly. Storing responses in a dictionary at module level keeps the routing logic separate from the response content, making updates straightforward. A fallback response handles messages that do not match any keyword, ensuring every inbound message gets a reply. The MessagingResponse helper builds the TwiML XML without string concatenation, preventing malformed XML responses.

import re
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)

RESPONSES = {
    "hours":    "We are open Monday to Friday 9am to 6pm ET and Saturday 10am to 4pm ET.",
    "price":    "Our plans start at $29/month. Reply PLANS for a full breakdown.",
    "plans":    "Starter: $29/mo, Professional: $79/mo, Enterprise: custom. Reply TALK for a demo.",
    "support":  "For technical support email support@telphi.com or call 1-800-TELPHI.",
    "talk":     "A sales rep will call you within 1 business hour. Reply with your name to get started.",
    "location": "We serve clients nationwide with remote support. Our HQ is in New York, NY.",
    "stop":     "You have been unsubscribed. Reply START to resubscribe.",
    "start":    "Welcome back! You are now resubscribed to messages from Telphi.",
}

FALLBACK = (
    "Thanks for your message! Reply HOURS, PRICE, SUPPORT, PLANS, or TALK "
    "to get instant answers, or a team member will follow up shortly."
)

def normalize(text: str) -> str:
    return re.sub(r"[^a-z0-9 ]", "", text.lower().strip())

@app.route("/bot", methods=["POST"])
def bot():
    body = normalize(request.form.get("Body", ""))
    resp = MessagingResponse()

    matched = False
    for keyword, reply in RESPONSES.items():
        if keyword in body:
            resp.message(reply)
            matched = True
            break

    if not matched:
        resp.message(FALLBACK)

    return str(resp), 200, {"Content-Type": "text/xml"}

if __name__ == "__main__":
    app.run(port=5000, debug=True)

Testing and Debugging

Send test messages containing each keyword to your Twilio number and verify the bot returns the correct response for each one. Test the fallback by sending a message with no matching keywords, such as "hello" or "what do you do", and confirm the fallback text is returned. Check the Flask terminal for each inbound POST to see the normalized body and confirm your keyword matching logic is working as expected. If the bot fails to respond, check the ngrok terminal for the incoming POST and verify Flask is returning a 200 with valid TwiML XML in the body.

Taking It Further

Load keyword-response pairs from a database or JSON file so non-technical staff can update bot responses without modifying Python code. Add fuzzy matching using the difflib module or a library like rapidfuzz to handle misspellings and near-matches for keywords. Implement a conversation state tracker using a session dictionary keyed by phone number so the bot can ask follow-up questions and maintain multi-turn conversations. Integrate an LLM API for free-text messages that do not match any keyword, so the bot can answer arbitrary questions using your product documentation as context.

Contact Telphi Consulting to build a production SMS bot with NLP integration, conversation tracking, and CRM sync.

Share this article:
0 views

Ready to Transform Your Business Communications?

Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.

Comments (0)

Join the discussion and share your thoughts (AI-moderated for quality)

Protected by AI moderation

Be the first to comment

No comments yet. Share your thoughts below.