Metadata-Version: 2.4
Name: vintasend-twilio
Version: 3.8.0
Summary: Twilio SMS adapter for VintaSend
License-Expression: MIT
License-File: LICENSE.txt
Author: Hugo bessa
Author-email: hugo@vinta.com.br
Requires-Python: >=3.10,<3.15
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Dist: twilio (>=9.0.0,<10.0.0)
Requires-Dist: vintasend (==3.8.0)
Description-Content-Type: text/markdown

# vintasend-twilio

A [Twilio](https://www.twilio.com/) SMS adapter for
[vintasend](https://github.com/vintasoftware/vintasend).

VintaSend records every notification, renders it from a template at send time, and hands the
result to an **adapter** for delivery. This package is an adapter for the `SMS` notification type:
it renders the notification with any `BaseTemplatedSMSRenderer` and posts the body to Twilio's
Messages API. Pair it with any vintasend backend and an SMS renderer (for example
`vintasend-jinja`, or `vintasend-managed-templates`' `ManagedTemplateSMSRenderer`).

Both service flavours are covered:

| Class | For |
|---|---|
| `TwilioSMSNotificationAdapter` | `NotificationService` (sync) |
| `TwilioAsyncIOSMSNotificationAdapter` | `AsyncIONotificationService` (awaits Twilio through its async HTTP client) |

## Install

```bash
poetry add vintasend-twilio
# or
pip install vintasend-twilio
```

`twilio` comes as a dependency.

## Usage

```python
from vintasend.services.notification_service import NotificationService
from vintasend_twilio import TwilioSMSNotificationAdapter

adapter = TwilioSMSNotificationAdapter(
    my_sms_renderer,                      # any BaseTemplatedSMSRenderer
    my_backend,                           # any vintasend backend
    account_sid="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    auth_token="...",
    from_phone_number="+15550001234",
)

service = NotificationService(notification_adapters=[adapter], notification_backend=my_backend)
```

Or let the service build it from settings. Every option below is an adapter keyword argument,
so it goes in the kwargs half of a `NOTIFICATION_ADAPTERS` entry:

```python
NOTIFICATION_ADAPTERS = [
    (
        ("vintasend_twilio.TwilioSMSNotificationAdapter", {"from_phone_number": "+15550001234"}),
        "vintasend_jinja.services.notification_template_renderers.jinja_template_renderer.JinjaTemplatedSMSRenderer",
    ),
]
```

With credentials left out of the kwargs, they are read from the environment (see below), which
keeps the auth token out of your settings module.

### Options

| Keyword argument | Environment fallback | Meaning |
|---|---|---|
| `account_sid` | `TWILIO_ACCOUNT_SID` | Twilio account SID. Required unless `client` is given. |
| `auth_token` | `TWILIO_AUTH_TOKEN` | Twilio auth token. Required unless `client` is given. |
| `from_phone_number` | `TWILIO_FROM_PHONE_NUMBER` | E.164 number to send from. Exactly one of this and `messaging_service_sid` is required. |
| `messaging_service_sid` | `TWILIO_MESSAGING_SERVICE_SID` | Twilio Messaging Service to send through instead of a fixed number. |
| `phone_number_context_key` | — | Context key holding the recipient's number for regular notifications. Default `"phone_number"`. |
| `status_callback` | — | URL Twilio calls with delivery status updates. |
| `client` | — | A prebuilt `twilio.rest.Client`. Overrides `account_sid`, `auth_token` and `client_kwargs`. |
| `client_kwargs` | — | Extra keyword arguments for `twilio.rest.Client` (`region`, `edge`, `http_client`, ...). |

A missing sender or missing credentials raises `TwilioConfigurationError` when the adapter is
constructed, not at the first send.

### Where the recipient's number comes from

- A **one-off notification** carries its destination on itself (`email_or_phone`), so nothing
  else is needed.
- A **regular notification** only knows the user, and vintasend's backend seam has no phone
  lookup. The adapter reads the number from the context the notification's context generator
  returns, under `phone_number_context_key` (default `phone_number`):

  ```python
  from vintasend.services.dataclasses import NotificationContextDict
  from vintasend.services.notification_service import register_context

  @register_context("sms_verification")
  def sms_verification(user_id: str) -> NotificationContextDict:
      user = get_user(user_id)
      return {"phone_number": user.phone_number, "code": user.pending_code}
  ```

  A regular notification whose context has no non-empty number raises
  `MissingRecipientPhoneNumberError` before anything is sent.

Like the email adapters, the adapter also adds `base_url` to the context handed to the renderer
(from `NOTIFICATION_DEFAULT_BASE_URL_PROTOCOL` and `NOTIFICATION_DEFAULT_BASE_URL_DOMAIN`), so an
SMS template can build absolute links.

### Errors

Every exception derives from vintasend's `NotificationError`:

- `TwilioConfigurationError` -- no usable sender or credentials, raised at construction.
- `MissingRecipientPhoneNumberError` -- a regular notification's context has no number.
- `TwilioSendError` -- Twilio rejected the message. It carries Twilio's HTTP `status` and
  error `code`, names the notification id, and chains the original `TwilioRestException` as
  `__cause__`. Its own message never includes the recipient's number.

Both send errors subclass `NotificationSendError`, so the service marks the notification as
failed the same way it does for any other adapter.

### AsyncIO

`TwilioAsyncIOSMSNotificationAdapter` takes the same options. Unless you inject a `client`, it
builds Twilio's `Client` with `AsyncTwilioHttpClient` (aiohttp-backed) and awaits
`messages.create_async`, so the request never blocks the event loop. The client is built on first
send rather than in the constructor, because the aiohttp session needs a running event loop and
`AsyncIONotificationService` instantiates its adapters synchronously. An injected `client` must
have been built with an async `http_client`.

### Injecting a client

For a shared client, an API key instead of the auth token, a region or edge, or a custom HTTP
client:

```python
from twilio.rest import Client

client = Client(api_key_sid, api_key_secret, account_sid, region="ie1")
TwilioSMSNotificationAdapter(renderer, backend, from_phone_number="+15550001234", client=client)
```

## Development

```bash
poetry install --with dev
poetry run pytest
poetry run ruff check .
poetry run mypy
poetry run tox        # the suite across Python 3.10-3.13
```

The tests drive the real adapter against a recording Twilio HTTP client, so nothing touches the
network.

