Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Driver Twilio Laravel Package

botman/driver-twilio

Twilio driver for BotMan that connects your PHP chatbot to Twilio SMS, letting you send and receive messages through Twilio phone numbers. Install via Composer and wire it into BotMan to handle SMS conversations.

Deep Wiki
Context7

Getting Started

  • Confirm compatibility first. This driver’s last release was in 2018, so check it against your BotMan version and the Twilio SDK it pulls in:

    composer require botman/botman botman/driver-twilio
    composer show botman/driver-twilio
    composer why-not botman/driver-twilio
    

    If you are starting a new Laravel app, evaluate whether to use this driver for inbound SMS/MMS and the official Twilio SDK for outbound/proactive sends.

  • Configure Twilio credentials and sender. Use a Twilio phone number in E.164 format:

    TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    TWILIO_AUTH_TOKEN=your_auth_token
    TWILIO_FROM=+15551234567
    

    In a BotMan Studio-style app, look for the published BotMan/Twilio config and map it to account_sid, auth_token, and from. In a standalone BotMan setup, pass a twilio config block to BotManFactory::create().

  • Expose one webhook endpoint. Twilio sends application/x-www-form-urlencoded POSTs to your Messaging webhook:

    use BotMan\BotMan\BotMan;
    
    Route::post('/botman/twilio', function (BotMan $bot) {
        $bot->listen();
    })->withoutMiddleware([\App\Http\Middleware\VerifyCsrfToken::class]);
    

    In Twilio Console, point the phone number or Messaging Service “A message comes in” webhook to the public HTTPS URL, e.g. https://example.com/botman/twilio.

  • Start with an echo/FAQ bot. This validates the entire path: Twilio webhook → BotMan driver → cache → Twilio REST reply.

    $bot->hears('hello|hi|start', function (BotMan $bot) {
        $bot->reply('Hi. Text MENU for options.');
    });
    
    $bot->fallback(function (BotMan $bot) {
        $bot->reply('Sorry, I did not understand that. Text HELP for help.');
    });
    
  • Where to look first in the package: inspect src/TwilioDriver.php for inbound payload keys and outbound message support, the service provider for config binding/registration, and any config file for expected keys. On the Twilio side, use Messaging logs and Debugger to confirm webhook delivery and response codes.

  • First realistic use case: an SMS support/FAQ bot for one Twilio number, with a small set of hears() handlers, persisted conversation cache, and a fallback that directs users to a human or help channel.

Implementation Patterns

  • Keep handlers channel-agnostic. Use normal BotMan patterns: hears(), ask(), conversations, middleware, and fallback handlers. That lets the same bot code work across web, Slack, Telegram, and Twilio with channel-specific formatting only at the edges.

  • Treat SMS as a short-message interface. Keep replies concise, use numbered menus instead of unsupported rich UI, and avoid expecting button/quick-reply payloads. Twilio SMS/MMS does not provide native BotMan buttons; fall back to text instructions and keyword parsing.

  • Use middleware to normalize Twilio metadata. Incoming Twilio payloads include fields such as From, To, Body, MessageSid, NumMedia, and MediaUrl0. Capture what you need in middleware so handlers do not depend directly on raw request shape:

    $bot->middleware(function ($message, $next) {
        $payload = $message->getPayload();
        // Log MessageSid, From, To, NumMedia, etc.
        return $next($message);
    });
    
  • Handle MMS explicitly. Inbound media is delivered as Twilio media URLs. Download and store media promptly if it matters; do not assume Twilio media URLs are permanent. For outbound media, send publicly reachable HTTPS URLs through BotMan image/file messages or the Twilio SDK.

  • Persist conversation state. Multi-step ask() flows depend on BotMan’s conversation cache. In Laravel, configure a real cache store such as Redis, database, or file. The default array cache will not survive between webhook requests, so conversations will appear to restart every SMS.

  • Use queues for slow work. Twilio expects a quick webhook response. If a handler calls slow APIs, writes large files, or performs multi-step business logic, acknowledge quickly and dispatch a queued job. For user-visible replies, either let the queued job send via Twilio SDK/BotMan say() or keep the immediate response short.

  • Store phone numbers in E.164. Normalize numbers before saving or matching users. Use From as the conversation identity for inbound SMS, and keep To if you operate multiple Twilio numbers or tenants.

  • For proactive messages, prefer the official Twilio SDK unless BotMan’s say() path is already proven. Store the destination number and send from a valid Twilio sender. Use status callbacks to track delivery and failures rather than assuming a 200 from your app means delivery.

  • Log the Twilio MessageSid everywhere. It is the best correlation key across Laravel logs, Twilio Messaging logs, delivery callbacks, and support tickets. Consider storing inbound message SIDs to make retries idempotent.

  • Test with Twilio’s console and local tunneling. Use ngrok or equivalent for local webhook testing, send from a verified trial number, and inspect the exact form payload. Add feature tests around your handlers by faking BotMan messages where possible, and isolate Twilio SDK calls behind a small service for mocking.

Gotchas and Tips

  • This package is old. A 2018 release means the Twilio SDK and BotMan dependencies may be outdated. Pin versions, run a dependency audit, and test against the Twilio API behavior you actually need. For newer Twilio features, use the official SDK directly and keep this driver focused on inbound webhook handling.

  • Do not return TwiML by accident. This driver typically sends replies through the Twilio REST API. Your webhook response should be an empty 200 unless you deliberately want TwiML. Returning TwiML can cause duplicate messages.

  • CSRF and auth middleware will break the webhook. Twilio cannot send Laravel CSRF tokens. Exempt the webhook route from CSRF and do not put it behind session auth. If you need security, validate X-Twilio-Signature with Twilio’s RequestValidator using the auth token.

  • Conversation cache is the most common “bot forgets everything” cause. Confirm the cache driver, cache prefix, and TTL. In multi-server deployments, use a shared cache such as Redis or the database. Clear cache when changing conversation keys or user identity rules.

  • Phone-number identity can collide. The driver generally keys conversations by the inbound From number. If one bot serves multiple Twilio numbers or tenants, add middleware or extend the driver to include To/tenant in the conversation identity.

  • Trial accounts and compliance matter. Twilio trial accounts can only message verified numbers. For production, handle opt-outs (STOP, UNSUBSCRIBE, etc.), help keywords, and regional sender requirements. US A2P/10DLC registration and consent rules are outside the driver but will affect delivery.

  • SMS length affects cost and UX. GSM-7 messages are commonly billed in 160-character segments; Unicode/emoji reduces that to about 70 characters per segment. Long BotMan replies may be split and billed as multiple messages. Sanitize, shorten, and avoid unnecessary emoji.

  • MMS support is carrier-dependent. Not every carrier or country supports MMS. Media URLs must be publicly reachable over HTTPS; auth-protected URLs may fail. Inbound media URLs can expire, so persist media immediately if your workflow depends on it.

  • Twilio retries failed webhooks. If your endpoint returns a non-2xx status or times out, Twilio may retry, causing duplicate handler execution. Use MessageSid for idempotency and return 200 quickly. Twilio’s webhook timeout is short enough that slow synchronous handlers are risky.

  • Debug from both sides. Check Laravel logs and the Twilio Debugger/Messaging logs. Confirm the webhook URL exactly, including HTTPS, path, and trailing slash. Also verify whether the webhook is configured on the phone number or a Messaging Service; both can be relevant.

  • Unsupported BotMan message types should degrade gracefully. Buttons, cards, and similar rich messages are not native SMS features. Detect the Twilio channel and send text fallbacks rather than assuming the driver can render rich payloads.

  • Extension points: use BotMan middleware for logging/normalization, a custom driver subclass if you need signature validation or multi-number conversation keys, and Laravel service bindings/queues for Twilio SDK calls. Keep Twilio-specific behavior out of domain handlers so the bot remains portable to other channels.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core