This tutorial shows how to track real-time delivery status for Twilio SMS messages using a StatusCallback webhook in Python and Flask. It targets developers who need to know whether each message was delivered, failed at the carrier, or bounced so they can trigger retries, log outcomes, or alert operations teams. You will send a message with a status_callback URL and build a Flask endpoint that receives and logs the delivery status events Twilio POSTs to it.
Prerequisites and Setup
You need Python 3.7 or higher, Flask, and the Twilio SDK installed with pip install twilio flask python-dotenv. Run ngrok with ngrok http 5000 to expose your local Flask server with a public HTTPS URL that Twilio can reach. Twilio POSTs status updates to the callback URL at multiple points in the message lifecycle: queued, sent, delivered, and failed or undelivered. The callback contains the message SID so you can match each event back to the original send in your database.
pip install twilio flask python-dotenv
# Start ngrok
ngrok http 5000
# Note the https URL for use as status_callback
The Complete Code
Pass the status_callback parameter to messages.create() pointing to your Flask route that will receive the delivery events. The Flask endpoint reads MessageSid, MessageStatus, To, and ErrorCode from the POST form data. Twilio sends multiple POST requests per message as the status progresses, so your handler must be idempotent and handle the same SID appearing multiple times with different statuses. Returning a 204 No Content response with an empty body is the correct response to Twilio's status callback; a 200 with content is also accepted.
import os
from flask import Flask, request
from twilio.rest import Client
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
client = Client(os.environ["TWILIO_ACCOUNT_SID"], os.environ["TWILIO_AUTH_TOKEN"])
STATUS_LOG = {}
@app.route("/status", methods=["POST"])
def message_status():
sid = request.form.get("MessageSid", "")
status = request.form.get("MessageStatus", "")
error = request.form.get("ErrorCode", "")
to = request.form.get("To", "")
STATUS_LOG[sid] = {"status": status, "error": error, "to": to}
print(f"[STATUS] {sid} -> {status}" + (f" (error {error})" if error else ""))
if status in ("failed", "undelivered"):
print(f" ALERT: Message to {to} failed with error code {error}")
return "", 204
def send_with_tracking(to: str, body: str, callback_url: str):
message = client.messages.create(
body=body,
from_=os.environ["TWILIO_PHONE_NUMBER"],
to=to,
status_callback=callback_url,
)
print(f"Sent {message.sid} to {to}")
return message.sid
if __name__ == "__main__":
app.run(port=5000, debug=True)
Testing and Debugging
Start the Flask server, send a message using send_with_tracking() with your ngrok URL as the callback, and watch the terminal for incoming status events over the next few seconds. You should see at least queued followed by sent and then delivered for a successful message to a mobile number. If no callbacks arrive, verify your ngrok tunnel is running and check the Twilio Console under Monitor for webhook delivery attempts and any HTTP errors. Error code 30003 in the callback means the destination number is unreachable; error 30008 means the message was blocked by the carrier.
Taking It Further
Persist each status update to a relational database with the SID, status, timestamp, and error code so you have a full delivery audit trail for every message. Build a retry mechanism that catches failed or undelivered statuses and queues the message for a second send attempt after a configurable delay. Add monitoring alerts that fire a notification (via PagerDuty, Slack, or email) when the failure rate for a batch of messages exceeds a threshold. Use Twilio's Messaging Insights dashboard alongside your webhook data to correlate carrier error codes with specific destinations or time windows.
Contact Telphi Consulting to build a delivery monitoring and alerting system for your Twilio SMS operations.
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)
Be the first to comment
No comments yet. Share your thoughts below.