How to build an SMS chatbot with Twilio and Python
The problem
You want customers to text a number and get automatic, useful replies, with follow-ups and a link to your CRM.
Step by step
- Buy a Twilio number that supports SMS in your country and check local rules for business messaging.
- Run a web server with a public HTTPS address (a tunnel works for testing).
- In the Twilio console, set the number's incoming message webhook to your server URL.
- Reply with TwiML. Start with a fixed answer, then add the AI call.
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
@app.post("/sms")
def sms():
text = request.form["Body"]
reply = MessagingResponse()
reply.message("Thanks! You said: " + text)
return str(reply)To use an AI model, call its API inside sms() with the incoming text and return its answer. Keep replies short.
Compliance
- Message only people who agreed to receive texts.
- Honour STOP and keep an opt-out list.
- Check the laws of each country you text.
Store each conversation in your CRM with a timestamp so a human can take over.
