Why Twilio for OpenClaw?
Twilio is a communications API platform. It gives you a real phone number, a way to send and receive SMS, and a programmable voice stack that can route a live call to a webhook that Twilio then streams to your server. OpenClaw is the reasoning layer — the part that understands the request and decides what to say back. Twilio is the telephony transport. Splitting them this way is what makes the integration clean: Twilio never needs to understand your business logic, and your agent never needs to know carrier routing or media streaming.
The practical payoff is that a customer can text or call a business number and get a genuinely useful answer, then hang up or stop texting without ever knowing they were talking to an agent. That is the difference between an AI agent that lives in a chat window and one that lives where customers already are. Concretely, one Twilio number unlocks:
- Inbound SMS handling — A customer texts a Twilio number; your agent replies, confirms a booking, or hands off to a human
- Outbound SMS — Appointment reminders, order confirmations, delivery updates, and two-way replies to inbound messages
- Programmable Voice — An inbound call is answered by an agent that can transcribe the caller, reason about the request, and speak a response back
- Shared state — The same agent context handles the text thread and the phone call, so a customer does not have to repeat themselves after switching channels
- Escalation paths — After N failed attempts, or on a specific phrase, the agent transfers the conversation to a human and sends a summary by SMS
Twilio Credentials and Environment Variables
Everything you need from Twilio lives on the Twilio Console. Create an account, then note three values: the Account SID (your account identifier, prefixed AC), the Auth Token (a secret that also signs inbound requests), and a Twilio phone number you purchase from the console. These map to the three environment variables the OpenClaw Twilio plugin reads:
export TWILIO_ACCOUNT_SID="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" export TWILIO_AUTH_TOKEN="your_auth_token_here" export TWILIO_PHONE_NUMBER="+15551234567"
Keep the Auth Token out of your repository and out of your agent's system prompt. Put it in a secrets file or your process manager's environment, and make sure the file is not world-readable. The Auth Token is the key to webhook signature verification — if it leaks, an attacker can forge inbound requests to your endpoint and impersonate a customer.
Inbound SMS: Webhooks and Signature Verification
Twilio calls your endpoint when a message arrives on your number. Point your Twilio number's "A message comes in" webhook at a publicly reachable HTTPS URL — for example https://your-domain.example/hooks/twilio/sms. Twilio sends a POST with application/x-www-form-urlencoded content, and the fields are the useful ones you would expect:
From=+15551234567 To=+15559876543 Body=Do you have a table for 7pm tonight? MessageSid=SM1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d NumMedia=0
Do not trust that payload just because it arrived at your URL. Anyone who learns the URL can POST a fake Body and make your agent answer as if a customer asked. Twilio solves this with X-Twilio-Signature: it is an HMAC-SHA1 of your full webhook URL concatenated with the POST parameters sorted by key, keyed with your Auth Token. You recompute that HMAC server-side and compare it against the header with a constant-time comparison. Only if they match do you act on the message.
def verify_twilio_signature(url, params, auth_token, header):
payload = url + "".join(
sorted(f"{k}{params[k]}" for k in params)
)
mac = hmac.new(
auth_token.encode("utf-8"),
payload.encode("utf-8"),
hashlib.sha1,
).hexdigest()
return hmac.compare_digest(mac, header or "")
Twilio also ships official helper libraries that do this correctly — use them rather than rolling your own if you can. The critical detail people get wrong is the exact URL: it must be the full public URL Twilio requested, including the scheme and query string, or the signature will never match and every legitimate message will look forged.
A signature mismatch is not a glitch to log and ignore. It means the request did not come from Twilio. Reject it, and never let the agent act on it.
Outbound SMS: Confirmations, Reminders, Replies
Outbound is the simpler direction and often the higher-value one. The agent calls the Twilio Messages API and creates a message with your `TWILIO_PHONE_NUMBER` as the sender. Three patterns cover most of what a restaurant, clinic, or service business needs:
- Booking confirmation — Sent the moment a reservation or appointment is created, restating the time, party size, and location so the customer does not have to check their own app
- Appointment reminder — Scheduled ahead of time, sent from the agent's own logic, with a short reply path if the customer wants to reschedule
- Follow-up and reply — Post-interaction messages, plus direct replies to inbound threads that keep the conversation in one place
Keep messages short. SMS is not email, and long messages are billed and often split into multiple segments. Put the essential fact in the first line, and let the customer reply with a keyword to hand off to a human.
Programmable Voice: Taking Live Calls
Voice works on the same webhook pattern but with a different URL shape. When you configure your number's "A call comes in" webhook, Twilio posts to it and waits for your TwiML response — an XML document telling Twilio what to do next. To give the agent time to think, you return a <Say> that plays something like "Let me check that for you" and then point Twilio at a media-streaming URL so audio flows to your server in near real time.
Two additional variables matter here. TWILIO_VOICE_FROM sets the caller ID your agent dials from — use a number you have verified for voice, because Twilio treats messaging and voice eligibility separately and a number that sends SMS fine may be blocked from originating calls. For inbound calls, the number your agent answers on becomes the identity customers see, so keep it consistent with the SMS number where possible.
A typical voice turn looks like this: caller dials in, Twilio hits your webhook, you answer with TwiML and start a media stream, you transcribe the caller's speech to text, you send that text plus the conversation state to the OpenClaw agent, the agent returns a spoken reply, and you stream synthesized audio back. Many teams keep the voice loop deliberately narrow — a bounded set of intents — because every extra turn adds both latency and per-minute telephony cost.
How the Agent Connects: Webhook to Reply
Think of the integration as a loop with four stages, and it stays the same whether the input is a text or a call:
- Transport — Twilio delivers the event to your HTTPS endpoint and waits
- Verification — You validate the signature before trusting anything in the payload
- Reasoning — You hand the normalized message plus conversation state to the OpenClaw agent and get a reply
- Response — You send the reply back through Twilio and return an appropriate empty or success response
Twilio's webhook timeout is short, so if your agent needs to reason for a while, acknowledge the request first and deliver the reply asynchronously with a second API call. For SMS that is natural. For voice, acknowledge with TwiML that keeps the call open and stream the reply when it is ready.
Number Geography, Messaging Limits, and the Cost Model
Twilio numbers are tied to a country, and that country shapes what your customers pay and what your agent can legally do. A local number in the customer's country reads as more trustworthy and generally costs less for them to receive than a foreign one; international delivery to that same number is billed as a separate international message. Many businesses keep a local number for the primary country and an international-capable route for customers who travel or live abroad.
On limits, three mechanics matter more than any headline throughput figure. A messaging number has a per-day send ceiling that scales with your account's messaging history, so a brand-new account may be capped conservatively and scale up as it demonstrates legitimate volume. Message throughput is also shaped by the recipient's country and carrier — traffic to certain destinations is filtered more heavily, which is why you should look at delivery status callbacks rather than assuming a message landed because you got a success response back. Finally, US regulations require registered messaging for some categories of traffic; Twilio's A2P registration process is part of getting a production messaging number, not an optional extra.
On cost, avoid quoting anyone a hard per-message figure without checking Twilio's current pricing page, because it varies by destination country, message type, and carrier path. The mechanics are stable even when the numbers are not: SMS is billed per message segment, so a long message is billed as several segments and you should keep outbound texts short. Voice is billed per minute, with separate rates for the inbound leg, the outbound leg, and any media streaming or recording add-ons, and you are charged for the whole minute once a call connects. Twilio also sells number rental per month, which is a fixed cost regardless of usage. Budget for a fixed number rental plus a variable per-segment or per-minute cost, and add your model inference cost on top for anything the agent does per turn.
Twilio vs Alternatives
The telephony market splits into three broad categories, and the right choice depends on whether you need carrier-grade reliability, API maturity, or control over your own stack.
- Twilio — SMS and voice both supported, a large and mature API with strong documentation, and the easiest setup path because the console handles number provisioning, webhook configuration, and messaging registration in one place. The trade-off is that you are inside a closed platform with per-segment and per-minute pricing and no control over the underlying carrier paths.
- Vonage / MessageBird — Comparable SMS and voice coverage with its own programming model and regional numbering options. Worth evaluating if you need numbers in markets where Twilio's coverage is thinner, or if you want a second vendor for redundancy.
- SignalWire — Positions itself on messaging and voice with a lower-cost emphasis. Reasonable for text-heavy workloads, but with a smaller ecosystem and less community tooling than Twilio.
- Self-hosted SIP — Using a trunk provider with your own telephony stack gives you control over carriers, costs, and data handling, but you inherit SIP trunking, media servers, and compliance work that Twilio handles for you.
For most OpenClaw deployments, the deciding question is simple: do you want to spend engineering time on telephony, or on the agent? Twilio answers that question by existing.
Where Twilio Fits: The Restaurant AI Agent
The Restaurant AI Agent Guide uses Twilio for exactly this pattern — a customer calls or texts to book a table, the agent confirms the reservation by SMS, and the WhatsApp channel handles order follow-ups. That guide's communication step configures the Twilio number and credentials alongside the WhatsApp Business API, then falls back to SMS when a WhatsApp conversation is not appropriate. If you are building a phone-first agent, read that guide next: it covers the surrounding workflow — menu Q&A, order handling, and the escalation logic — that makes the telephony integration pay off.
Twilio also sits naturally next to the rest of your channel stack. Many agents answer on one channel and confirm on another — a call that ends with a booked table and a text confirmation is a better experience than either channel alone.
Production Checklist
- Signature verification on every inbound webhook, with constant-time comparison
- Auth Token stored as a secret, never committed and never exposed to the model context
- Message and voice numbers both tested for sending and calling, including international destinations
- A2P messaging registration complete before you rely on outbound SMS at volume
- A human handoff path for frustrated callers and for anything the agent is not confident about
- Delivery status callbacks wired up so you can measure what actually landed
- Short outbound messages, because every extra segment is billed and hurts readability
Next Steps
Install OpenClaw, get a Twilio number, set the three environment variables, and send one inbound text end to end before you build anything elaborate. Once that loop works, the same pattern extends to voice with surprisingly little extra machinery.
🔥 Ready to Build Your AI Agent?
Get 10 production-ready AI agent tools and guides — $29 for the complete bundle
Get the Complete Bundle — 10 AI agent tools for $29 →Not ready yet? Start with the free pack: Download the free starter templates