Back to Blog
Language How-Tos

How to Handle STOP Opt-Out Replies Automatically in Twilio Using Python

Build a Python webhook that handles STOP, UNSTOP, and HELP keyword replies from Twilio to manage opt-outs and compliance automatically.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
8 min read
Twilio
Python
How-To
Code
How to Handle STOP Opt-Out Replies Automatically in Twilio Using Python

This tutorial builds a Flask webhook that receives inbound SMS replies, detects opt-out keywords such as STOP, UNSTOP, and HELP, and responds with compliant TwiML messages in Python. It targets developers who need to respect carrier opt-out regulations and maintain a clean recipient list in their application's database. You will handle the three core keyword categories and update an internal opt-out store so opted-out numbers are never messaged again.

Prerequisites and Setup

You need Python 3.7 or higher, Flask, and the Twilio SDK installed with pip install twilio flask. Twilio automatically handles STOP and UNSTOP at the platform level for most cases, but building your own handler gives you visibility into opt-outs and lets you update your own database in real time. Set your Twilio number's inbound SMS webhook to your Flask route in the Twilio Console so your server receives a copy of every inbound message. Note that Twilio's automatic opt-out handling runs before your webhook, so your webhook still fires but the opt-out is already registered at the Twilio level.

pip install twilio flask

# Configure your Twilio number's SMS webhook to:
# https://yourdomain.com/sms/inbound (POST)

The Complete Code

The handler normalizes the incoming body to uppercase and strips whitespace to reliably catch keyword variations regardless of how the user typed them. Matching against a set of known keywords for each category avoids false positives from messages that happen to contain those words in context. The function updates an in-memory opt-out set that in production would be replaced by a database write. Returning appropriate TwiML messages for each keyword keeps your application compliant with CTIA messaging guidelines.

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

app = Flask(__name__)

OPT_OUT_LIST = set()

STOP_KEYWORDS   = {"STOP", "STOPALL", "UNSUBSCRIBE", "CANCEL", "END", "QUIT"}
UNSTOP_KEYWORDS = {"START", "UNSTOP", "YES"}
HELP_KEYWORDS   = {"HELP", "INFO"}

@app.route("/sms/inbound", methods=["POST"])
def inbound_sms():
    sender = request.form.get("From", "")
    body   = request.form.get("Body", "").strip().upper()

    resp = MessagingResponse()

    if body in STOP_KEYWORDS:
        OPT_OUT_LIST.add(sender)
        print(f"Opted out: {sender}")
        resp.message(
            "You have been unsubscribed and will receive no further messages. "
            "Reply START to resubscribe."
        )
    elif body in UNSTOP_KEYWORDS:
        OPT_OUT_LIST.discard(sender)
        print(f"Re-subscribed: {sender}")
        resp.message(
            "You have been resubscribed and will receive messages again. "
            "Reply STOP at any time to unsubscribe."
        )
    elif body in HELP_KEYWORDS:
        resp.message(
            "For assistance, contact support at support@telphi.com. "
            "Reply STOP to unsubscribe."
        )
    else:
        resp.message("Thank you for your message. A team member will respond shortly.")

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

def is_opted_out(phone_number: str) -> bool:
    return phone_number in OPT_OUT_LIST

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

Testing and Debugging

Send the word STOP from a test phone to your Twilio number and verify the webhook prints the opt-out log line and the TwiML response contains the unsubscribe confirmation. Send START immediately after and confirm the number is removed from the opt-out set. Test HELP and an unrecognized keyword to verify each branch of the conditional returns the correct response. Check the Twilio Console under Messaging Logs to see your TwiML responses alongside the inbound messages for a complete conversation view.

Taking It Further

Replace the in-memory OPT_OUT_LIST set with a database table that records the phone number, opt-out timestamp, and keyword used so you have a compliance audit log. Add a pre-send check in every outbound message function that queries the opt-out table before calling messages.create(), raising an exception or silently skipping opted-out numbers. Extend the keyword matching to handle multi-word phrases like "please stop" or "no more messages" using case-insensitive substring checks for broader opt-out detection. Export the opt-out list periodically to your CRM or marketing platform to keep suppression lists synchronized across all channels.

Contact Telphi Consulting to build a compliant opt-out management system integrated with your marketing and CRM tools.

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.