SMS backend plug-ins

SMS backend plug-ins let tattler deliver SMS through a gateway it does not support out of the box. The same interface also lets you add entirely new vectors: see Delivering a custom vector.

Tattler ships with backends for BulkSMS.com and BulkGate . It selects backends by configuration: every backend whose settings are present and valid takes part in delivery. Backends are grouped by the vector they declare, and failover applies within the group: an SMS delivery only ever attempts backends declaring vector 'sms'. When multiple backends of a vector are configured – built-in or plug-in – tattler tries them in alphabetical order of their name, and falls over to the next when one fails to accept the message.

Writing an SMS backend plug-in

SMS backend plug-ins are python files that

Plug-in filenames must end with _tattler_plugin.py; other filenames are ignored.

A minimal backend declares its vector, declares its settings in required_settings, and implements send():

import re
import requests

from tattler.server.sendable import vector_sendable
from tattler.server.sendable.delivery_backend import DeliveryBackend, SendResult


class AcmeBackend(DeliveryBackend):
    """Deliver SMS through ACME's HTTP API."""

    @classmethod
    def vector(cls):
        return 'sms'

    # settings are looked up as TATTLER_{NAME}_{SUFFIX}, e.g. TATTLER_ACME_TOKEN;
    # each suffix maps to [required, validator]
    required_settings = {
        'TOKEN': [True, lambda v: re.match(r'\w+', v)],
    }

    def send(self, recipients, body, sender=None, priority=None):
        msgids = {}
        for rcpt in recipients:
            resp = requests.post('https://api.acme.example/sms', json={
                'token': vector_sendable.getenv(self.envvar('TOKEN')),
                'to': rcpt,
                'text': body,
            }, timeout=10)
            resp.raise_for_status()
            msgids[rcpt] = resp.json()['message_id']
        return SendResult(recipient_ids=msgids)

A few things to know:

  • Vector. vector() tells tattler which kind of delivery this backend performs; for an SMS backend it must return 'sms'. It also determines which group the backend fails over within.

  • Naming. The backend’s name defaults to the class name, lowercased and without any Backend suffix – AcmeBackend becomes acme. The name namespaces the backend’s settings (TATTLER_ACME_TOKEN) and determines its position in the failover order.

  • Configuration is the on/off switch. A backend is only used when all its required_settings are present and valid. Tattler validates them when it loads the plug-in, so misconfiguration surfaces at startup rather than at first delivery. A backend with none of its settings provided is simply skipped, with an informational log line; one with settings missing or malformed is skipped with an error.

  • What “success” means. Return from send() when the gateway accepted the message for delivery; raise on any failure, so tattler can fall over to the next configured backend.

  • Optional facilities. Implement cost() if your gateway can quote a delivery before sending, and delivery_status() if it supports polling for delivery reports. Both default to “no data available”.

See Deploying plug-ins for tips on deployment.

Delivering a custom vector

A backend may declare any name in vector() – not just 'sms'. Declaring e.g. 'signal' is all it takes for tattler to accept and deliver that vector:

  • Clients may request the vector: tattler_notify -v signal ....

  • Template designers provide content for it in the usual per-vector folder, e.g. my_event/signal/body.txt.

  • Your addressbook must return the recipient’s address under that key, e.g. {'signal': '+19876543210'} from attributes().

  • The usual per-vector settings apply, e.g. TATTLER_SIGNAL_SENDER and TATTLER_DEBUG_RECIPIENT_SIGNAL.

Override validate_recipient() to declare what a valid address looks like for your vector – return the normalized address, or raise ValueError. By default any address is accepted. When multiple backends serve one vector, a recipient is accepted if any backend accepts it, and the first accepting backend provides the normalization:

class SignalBackend(DeliveryBackend):
    """Deliver messages through Signal."""

    @classmethod
    def vector(cls):
        return 'signal'

    @classmethod
    def validate_recipient(cls, recipient):
        if not re.match(r'\+[1-9][0-9]+', recipient):
            raise ValueError(f"Signal recipients are phone numbers like '+19876543210', not '{recipient}'.")
        return recipient

    def send(self, recipients, body, sender=None, priority=None):
        ...

DeliveryBackend reference

class tattler.server.sendable.delivery_backend.DeliveryBackend

Base class for delivery providers of any vector.

Backends declare the vector they deliver for in vector() and their configuration in required_settings (keyed by envvar suffix), and implement send(); cost() and delivery_status() are optional. A backend is only used when its configuration is present and valid.

cost(recipients, body, sender=None)

Estimate the delivery cost before sending, in the provider’s native unit.

Best-effort: providers without a pre-send quoting facility return None.

Parameters:
  • recipients (Iterable[str]) – Recipient numbers the message would be sent to.

  • body (str) – Text that would be sent.

  • sender (Optional[str]) – Sender ID that would be used, if any.

Return type:

Optional[float]

Returns:

Estimated cost, or None if the provider cannot quote before sending.

delivery_status(result)

Look up the delivery status of a previously-sent message.

Best-effort: providers without a status-polling facility return an empty map.

Parameters:

result (SendResult) – Result of the send() call to look up status for.

Return type:

Mapping[str, DeliveryStatus]

Returns:

Map of recipient address to its delivery status; empty if the provider cannot report it.

classmethod envvar(suffix)

Return the name of the environment variable holding a given setting of this backend.

Parameters:

suffix (str) – Setting name as declared in required_settings.

Return type:

str

Returns:

Full environment variable name, e.g. ‘TATTLER_BULKSMS_TOKEN’.

classmethod name()

Return the identifier of this backend, used to namespace its settings.

Defaults to the class name, lowercased and with any ‘backend’ suffix dropped.

Return type:

str

Returns:

Lowercase backend name, e.g. ‘bulksms’.

send(recipients, body, sender=None, priority=None)

Deliver a message to some recipients.

Parameters:
  • recipients (Iterable[str]) – Recipient addresses, e.g. ‘+19876543210’.

  • body (str) – Text of the message.

  • sender (Optional[str]) – Sender ID to deliver as, or None for the provider’s default.

  • priority (Optional[int]) – Delivery priority, provider-specific interpretation.

Raises:

ValueError – When the provider rejected the request or returned an unusable response.

Return type:

SendResult

Returns:

Identifiers to look up delivery status with, see delivery_status().

classmethod validate_recipient(recipient)

Return the recipient normalized for this backend, or raise if the backend cannot deliver to it.

Permissive default: accept any recipient unchanged. Override to declare the address format of the vector this backend delivers for.

Parameters:

recipient (str) – Recipient address as requested, e.g. ‘+19876543210’.

Raises:

ValueError – When this backend cannot deliver to this recipient.

Return type:

str

Returns:

Normalized recipient address.

classmethod vector()

Return the name of the vector this backend delivers for.

Return type:

str

Returns:

Vector name, e.g. ‘sms’.

class tattler.server.sendable.delivery_backend.SendResult(recipient_ids=<factory>, batch_id=None)

Provider-native identifiers returned by a send, usable to look up delivery status later.

Parameters:
  • recipient_ids (Mapping[str, str]) – Map of recipient number to the provider’s message identifier for it.

  • batch_id (Optional[str]) – Provider’s identifier for the whole batch, if it issues one instead of per-recipient IDs.

class tattler.server.sendable.delivery_backend.DeliveryStatus(status, raw_status=None, cost=None, detail=None)

Normalized delivery state of a message to one recipient.

Parameters:
  • status (str) – One of ‘pending’, ‘sent’, ‘delivered’, ‘failed’, ‘unknown’.

  • raw_status (Optional[str]) – Provider’s native status string, for logging and debugging.

  • cost (Optional[float]) – Realized delivery cost in the provider’s native unit, if reported.

  • detail (Optional[str]) – Free-form provider detail, e.g. failure reason.