Twilio Communications Engine
Production-ready skill that handles build, communication, features, twilio. Includes structured workflows, validation checks, and reusable patterns for enterprise communication.
Twilio Communications Engine
A comprehensive skill for building communication applications with Twilio — covering SMS messaging, voice calls, WhatsApp integration, phone number management, webhook handlers, and multi-channel communication workflows.
When to Use This Skill
Choose Twilio Communications Engine when you need to:
- Send and receive SMS messages programmatically
- Build interactive voice response (IVR) systems
- Integrate WhatsApp messaging into your application
- Set up phone number provisioning and management
- Create multi-channel notification systems (SMS + email + voice)
Consider alternatives when:
- You need email-only communications (use an email service skill)
- You need chat bot functionality (use a Slack/Discord bot skill)
- You need push notifications only (use a push notification skill)
Quick Start
# Install Twilio SDK npm install twilio dotenv express
// send-sms.js — Send an SMS message const twilio = require("twilio"); require("dotenv").config(); const client = twilio( process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN ); async function sendSMS(to, body) { const message = await client.messages.create({ body, from: process.env.TWILIO_PHONE_NUMBER, to, // E.164 format: +12345678901 }); console.log(`Sent: ${message.sid} | Status: ${message.status}`); return message; } // Send a message sendSMS("+12345678901", "Your order #1234 has shipped!");
// receive-sms.js — Webhook to receive SMS const express = require("express"); const { twiml } = require("twilio"); const app = express(); app.use(express.urlencoded({ extended: false })); app.post("/sms", (req, res) => { const { From, Body } = req.body; console.log(`SMS from ${From}: ${Body}`); const response = new twiml.MessagingResponse(); if (Body.toLowerCase().includes("status")) { response.message("Your order is being processed. ETA: 2 days."); } else { response.message("Thanks for your message! Reply STATUS for order updates."); } res.type("text/xml").send(response.toString()); }); app.listen(3000, () => console.log("SMS webhook listening on :3000"));
Core Concepts
Twilio Communication Channels
| Channel | Send | Receive (Webhook) | Use Case |
|---|---|---|---|
| SMS | messages.create() | /sms endpoint | Transactional alerts |
| MMS | messages.create() + mediaUrl | /sms endpoint | Rich media messages |
| Voice | calls.create() | /voice endpoint | IVR, call forwarding |
messages.create() (whatsapp:) | /whatsapp endpoint | Customer support |
Voice Call with TwiML
// voice-ivr.js — Interactive Voice Response const express = require("express"); const { twiml } = require("twilio"); const app = express(); app.use(express.urlencoded({ extended: false })); app.post("/voice", (req, res) => { const response = new twiml.VoiceResponse(); const gather = response.gather({ numDigits: 1, action: "/voice/menu", method: "POST", }); gather.say( { voice: "alice" }, "Welcome to Acme Support. Press 1 for sales, 2 for support, 3 for billing." ); response.say("We didn't receive any input. Goodbye!"); res.type("text/xml").send(response.toString()); }); app.post("/voice/menu", (req, res) => { const response = new twiml.VoiceResponse(); const digit = req.body.Digits; switch (digit) { case "1": response.say("Connecting you to sales."); response.dial("+12345678901"); break; case "2": response.say("Connecting you to support."); response.dial("+12345678902"); break; case "3": response.say("Connecting you to billing."); response.dial("+12345678903"); break; default: response.say("Invalid option. Goodbye."); } res.type("text/xml").send(response.toString()); }); app.listen(3000);
Status Callbacks
// Track message delivery status async function sendTrackedSMS(to, body) { const message = await client.messages.create({ body, from: process.env.TWILIO_PHONE_NUMBER, to, statusCallback: "https://yourdomain.com/sms/status", }); return message; } // Status callback handler app.post("/sms/status", (req, res) => { const { MessageSid, MessageStatus, To } = req.body; console.log(`Message ${MessageSid} to ${To}: ${MessageStatus}`); // Status: queued → sending → sent → delivered / failed / undelivered res.sendStatus(200); });
Configuration
| Parameter | Description | Example |
|---|---|---|
account_sid | Twilio Account SID | process.env.TWILIO_ACCOUNT_SID |
auth_token | Twilio Auth Token | process.env.TWILIO_AUTH_TOKEN |
phone_number | Twilio phone number (E.164) | "+12345678901" |
webhook_base | Base URL for webhook callbacks | "https://yourdomain.com" |
status_callback | URL for delivery status updates | "/sms/status" |
voice | TwiML voice for text-to-speech | "alice" / "man" |
Best Practices
-
Validate webhook signatures in production — Twilio signs webhook requests with your auth token. Verify the signature to prevent attackers from sending fake webhooks to your endpoints. Use
twilio.webhook()Express middleware for automatic validation. -
Format all phone numbers in E.164 before sending — Twilio requires E.164 format (+country code + number). Use the Twilio Lookup API or a library like
libphonenumberto validate and format numbers before sending. Malformed numbers cause API errors and waste money. -
Implement opt-out handling for SMS — Carriers and regulations (TCPA, GDPR) require honoring STOP/unsubscribe requests. Twilio handles basic opt-outs automatically, but you should also track opt-out status in your database and check before sending.
-
Use messaging services for high-volume SMS — Sending thousands of messages from a single number risks carrier filtering. Twilio Messaging Services pool multiple numbers and handle compliance features (opt-out, sticky sender). Use them for any sending volume above a few hundred messages per day.
-
Handle delivery failures gracefully — Not every message will be delivered. Set up
statusCallbackURLs to track delivery status, and implement retry logic for transient failures. For critical messages, consider fallback channels (email if SMS fails).
Common Issues
SMS messages are not delivered but show "sent" status — "Sent" means Twilio delivered to the carrier, not to the recipient's phone. Check for "delivered" status via status callbacks. If messages consistently show "sent" but not "delivered," the destination number may be invalid, blocked, or a landline.
Webhook endpoint returns 502/503 errors — Twilio webhooks have a 15-second timeout. If your webhook handler does heavy processing (database writes, external API calls), it may timeout. Acknowledge the webhook immediately, then process asynchronously. Return a 200 status quickly and handle the work in a background job.
Voice calls play no audio or drop immediately — TwiML responses must be valid XML. Verify your TwiML with Twilio's TwiML Bin tool. Common issues: response content-type not set to text/xml, TwiML tags not properly closed, or <Say> verb missing text content.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Full-Stack Code Reviewer
Comprehensive code review skill that checks for security vulnerabilities, performance issues, accessibility, and best practices across frontend and backend code.
Test Suite Generator
Generates comprehensive test suites with unit tests, integration tests, and edge cases. Supports Jest, Vitest, Pytest, and Go testing.
Pro Architecture Workspace
Battle-tested skill for architectural, decision, making, framework. Includes structured workflows, validation checks, and reusable patterns for development.