Sending SMS with Twilio

Tagged with: python twilio

My eldest child is at the age where friends often have phones. I'm an old fuddy-duddy so I'm going to try to delay for a few more years, but I did see it as a nice opportunity for a child-friendly programming project. We headed over to Twilio and set up an account.

From there it was actually very easy to get up-and-running, with pass managing all the secret bits. A few lines of python and twilio's REST library were all that was needed to send messages.

"""Simple command line tool for sending messages from twilio

Example usage
-------------
python3 send.py "dad" "Hi dad!"

This will send the message `Hi dad!` to the number associated with
dad in RECIPIENTS.

"""

import subprocess
import sys
from twilio.rest import Client


RECIPIENTS = dict(
    dad="Dad's number",
    mum="Mum's number",
)


def get_secret(account):
    """Decrypts token for SMS/`item` from pass and returns a string"""
    return subprocess.check_output(
        "pass SMS/" + account, shell=True
    ).splitlines()[0].decode("utf-8")


if __name__ == "__main__":
    client = Client(get_secret("mySID"), get_secret("myToken"))
    client.messages.create(
        to=RECIPIENTS.get(sys.argv[1].lower(), None),
        from_=get_secret("myNumber"),
        body=sys.argv[2],
    )

As far as receiving replies is concerned we just looked at them on the twilio account's logs. There is an extra step you'll need to go through if you want to avoid twilio sending an automated response to any replies.

Is that a viable replacement for a phone? No. But that's half the point :-)