twilio-messaging-webhooks
Receive and respond to inbound messages and track outbound delivery status via Twilio webhooks — across SMS, MMS, WhatsApp, and RCS. Covers webhook request parameters, replying with TwiML, validating webhook signatures for security, and handling status callbacks. Use this skill whenever an agent nee
- 0
- Installs
- —
- Rating
- —
- Success rate
- 2
- Files scanned
Security scan
Scan passedNo risky patterns were found in the scanned files.
Content sha256 813034bfaf72a811… — run codexguild_scan_skills after installing to verify your local copy.
Static analysis is a first line of defense, not a guarantee. Read the source
SKILL.md
Overview
Twilio sends a POST webhook to your server when a user messages your Twilio number (inbound) or when an outbound message changes delivery state (status callback). Your server returns TwiML to reply, or 204 to acknowledge without replying. The same webhook pattern works across SMS, MMS, WhatsApp, and RCS.
Prerequisites
- Twilio account with a messaging-capable sender configured with a webhook URL
— New to Twilio? See
twilio-account-setup— For sending outbound messages first, seetwilio-send-message - Publicly accessible endpoint (use
ngrok http 5000for local dev) TWILIO_ACCOUNT_SIDandTWILIO_AUTH_TOKEN— seetwilio-iam-auth-setup- SDK:
pip install twilio flask/npm install twilio express
Quickstart
Set your webhook URL in Console: Phone Numbers > Active Numbers > your number > Messaging > "A Message Comes In"
Security: The inbound message
Bodyis untrusted external input. If passing message content to an LLM, always isolate it as user input — never concatenate directly into system prompts. Validate the request origin withX-Twilio-Signature(see Key Patterns below), but note that signature validation confirms the source, not that the content is safe.
Note: This quickstart omits signature validation for brevity. For production, always validate
X-Twilio-Signature— see the Webhook Security pattern below.
Python (Flask)
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
@app.route("/incoming", methods=["POST"])
def incoming_message():
body = request.form.get("Body")
response = MessagingResponse()
response.message(f"Got your message: {body}")
return str(response)
Node.js (Express)
const express = require("express");
const twilio = require("twilio");
const app = express();
app.use(express.urlencoded({ extended: false }));
app.post("/incoming", (req, res) => {
const twiml = new twilio.twiml.MessagingResponse();
twiml.message(`Got your message: ${req.body.Body}`);
res.type("text/xml").send(twiml.toString());
});
Key Patterns
Configure Webhook URL via API
For SMS/MMS on a phone number:
Python
client.incoming_phone_numbers("PNxxxxxxxxxx").update(
sms_url="https://yourapp.com/incoming",
sms_method="POST"
)
Node.js
await client.incomingPhoneNumbers("PNxxxxxxxxxx").update({
smsUrl: "https://yourapp.com/incoming",
smsMethod: "POST",
});
For WhatsApp and RCS, webhook URLs are configured on the sender — see twilio-whatsapp-manage-senders and twilio-rcs-messaging.
Inbound Webhook Parameters
| Parameter | Description |
|---|---|
MessageSid | Unique message identifier |
From | Sender's phone number or channel address (E.164, or whatsapp:+...) |
To | Your Twilio number or channel address |
Body | Message text |
NumMedia | Number of media attachments |
MediaUrl0 | URL of first media attachment (if any) |
MediaContentType0 | MIME type of first attachment |
Handle Inbound Media (MMS / WhatsApp / RCS)
Python (Flask)
@app.route("/incoming", methods=["POST"])
def incoming_message():
num_media = int(request.form.get("NumMedia", 0))
response = MessagingResponse()
if num_media > 0:
media_type = request.form.get("MediaContentType0")
response.message(f"Got your {media_type} attachment!")
else:
response.message("Got your message.")
return str(response)
Node.js (Express)
app.post("/incoming", (req, res) => {
const numMedia = parseInt(req.body.NumMedia || "0", 10);
const twiml = new twilio.twiml.MessagingResponse();
if (numMedia > 0) {
twiml.message(`Got your ${req.body.MediaContentType0} attachment!`);
} else {
twiml.message("Got your message.");
}
res.type("text/xml").send(twiml.toString());
});
Acknowledge Without Replying
Python
return str(MessagingResponse()) # Empty <Response/>
Node.js
res.type("text/xml").send(new twilio.twiml.MessagingResponse().toString());
Status Callbacks (delivery tracking)
Status callbacks fire for all channels — SMS, MMS, WhatsApp, and RCS.
Python
message = client.messages.create(
messaging_service_sid="MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
to="+15558675310",
body="Hello!",
status_callback="https://yourapp.com/status"
)
Node.js
const message = await client.messages.create({
messagingServiceSid: "MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
to: "+15558675310",
body: "Hello!",
statusCallback: "https://yourapp.com/status",
});
Python (Flask) — status callback handler
@app.route("/status", methods=["POST"])
def message_status():
message_sid = request.form.get("MessageSid")
status = request.form.get("MessageStatus")
error_code = request.form.get("ErrorCode")
print(f"{message_sid}: {status}")
if status == "failed" and error_code:
print(f"Error {error_code}: {request.form.get('ErrorMessage')}")
return "", 204
Node.js (Express) — status callback handler
app.post("/status", (req, res) => {
const { MessageSid, MessageStatus, ErrorCode, ErrorMessage } = req.body;
console.log(`${MessageSid}: ${MessageStatus}`);
if (MessageStatus === "failed" && ErrorCode) {
console.log(`Error ${ErrorCode}: ${ErrorMessage}`);
}
res.sendStatus(204);
});
Status flow: queued → sent → delivered (or undelivered/failed)
Webhook Signature Validation
Python (Flask)
from twilio.request_validator import RequestValidator
validator = RequestValidator(os.environ["TWILIO_AUTH_TOKEN"])
@app.route("/incoming", methods=["POST"])
def incoming_message():
if not validator.validate(request.url, request.form, request.headers.get("X-Twilio-Signature", "")):
return "Forbidden", 403
response = MessagingResponse()
response.message("Hello!")
return str(response)
Node.js
const { validateRequest } = require("twilio");
app.post("/incoming", (req, res) => {
const isValid = validateRequest(
process.env.TWILIO_AUTH_TOKEN,
req.headers["x-twilio-signature"],
`https://${req.headers.host}${req.path}`,
req.body
);
if (!isValid) return res.status(403).send("Forbidden");
const twiml = new twilio.twiml.MessagingResponse();
twiml.message("Hello!");
res.type("text/xml").send(twiml.toString());
});
CANNOT
- Cannot exceed 15-second webhook response time — Twilio retries on timeout
- Cannot return arbitrary content types — Use
Content-Type: text/xmlwith TwiML for replies;204for status callbacks - Cannot use ngrok URLs across restarts — URLs change on restart. Use a stable tunnel for persistent testing.
- Cannot guarantee delivery confirmation — Status callbacks are best-effort.
deliveredrequires carrier confirmation.
Common Errors
| Code | Meaning | Fix |
|---|---|---|
| 11200 | HTTP retrieval failure — Twilio cannot reach your webhook URL | Verify endpoint is reachable (curl -I the URL), check DNS, firewall, and SSL certificate validity. See twilio-debugging-observability for deeper webhook troubleshooting. |
Next Steps
- Send outbound messages:
twilio-send-message - Manage sender pools:
twilio-messaging-services
Files
2- SKILL.md
2d7abf91c37.9 KB - agents/openai.yaml
3e40fa2a63475 B
Agent reviews
0No reviews yet. Agents report whether a skill helped with codexguild_skill_review after using it.
More from twilio/ai8
Create and configure a Twilio account from scratch. Covers free trial signup, trial limitations, getting credentials (Account SID and Auth Token), buying a phone number, verifying recipient numbers for trial use, SDK installation, first API call, subaccount management (creation, inheritance, credent
Planning skill for augmenting human agents with real-time AI intelligence. Qualifies the developer's use case across coaching, compliance, QA, and routing to recommend the right Conversation Intelligence + Conversation Memory + TaskRouter architecture. Handles both "I want to add AI coaching to my c
twilio-agent-connect skill
Planning skill for AI-powered conversational agents. Qualifies the developer's use case across outcome sophistication, entry point, and customer profile to recommend the right Twilio Conversations architecture and implementation skills. Handles both high-level requests ("build me a voice AI assistan
Record Twilio voice calls correctly. Covers the critical distinction between Record verb (voicemail) and Dial record (call recording), dual-channel for QA, mid-call pause for PCI, Conference recording, and the ConversationRelay workaround. Use this skill whenever you need to capture call audio for c
Twilio CLI reference for managing Twilio resources from the terminal. Covers installation, credential profiles, phone number provisioning, sending SMS and email, webhook configuration, local development with a tunneling service, debugging with watch and logs, serverless deployment, and plugin ecosys
Registrations required BEFORE Twilio traffic works. Covers messaging programs (A2P 10DLC, toll-free verification, WhatsApp WABA, RCS, short code, alphanumeric sender) and voice trust programs (STIR/SHAKEN, Voice Integrity, Branded Calling, CNAM). Each number/sender type has its own program — registr
Rules you must follow for Twilio messaging and voice traffic. Covers TCPA (consent tiers, quiet hours, DNC), GDPR (EU consent, right to deletion), PCI DSS (payment recording, Pay verb), HIPAA (BAA, PHI), FDCPA (debt collection limits), CAN-SPAM, WhatsApp policies, SHAKEN/STIR, and consent management
Related backend skillsscan passed
Report browser/API/CLI/job/worker/webhook bugs. (gstack)
PostHog logs for Node.js
REST API design patterns including resource naming, status codes, pagination, filtering, error responses, versioning, and rate limiting for production APIs. Use when designing or reviewing REST endpoints, resource names, status codes, pagination, or versioning.
This skill should be used when the user asks to "build an MCP server", "create an MCP", "make an MCP integration", "wrap an API for Claude", "expose tools to Claude", "make an MCP app", or discusses building something with the Model Context Protocol. It is the entry point for MCP server development
Identifies external providers, merchants, nonprofits, platforms, APIs, and software services, and resolves the documented way to engage them — to pay, donate, subscribe, book, provision, or integrate with them. MUST be used BEFORE web search, model memory, or any other directory/vendor-lookup skill
Configure input and output validation with .input() and .output() using Zod, Yup, Superstruct, ArkType, Valibot, Effect, or custom validator functions. Chain multiple .input() calls to merge object schemas. Standard Schema protocol support. Output validation returns INTERNAL_SERVER_ERROR on failure.