Day 9 of the Anvil Advent Calendar

Build a web app every day until Christmas, with nothing but Python!

Text your tree

A few days ago we built a beautiful web-app-controlled Christmas tree, but what do you do when your iPhone battery runs out and you’re left with only a Nokia 3310? Well, you’re in luck, because receiving SMS messages is just a few minutes’ work with Anvil and the Nexmo API!



Loading video...

To make this work, open up the app you built the other day and add a server module. We’ll create a function in a new Server Module to receive SMS messages from a Nexmo Webhook:

allowed_senders = ['<YOUR_PHONE_NUMBER_GOES_HERE>']

@anvil.server.http_endpoint("/receive-sms")
def receive_sms(msisdn, text, **kwargs):
  print(f"Incoming SMS from {msisdn}")
  
  try:
    if msisdn in allowed_senders:
      if "ON" in text.upper():
        print("Turning lights on")
        anvil.server.call("lights_on")
      elif "OFF" in text.upper():
        print("Turning lights off")
        anvil.server.call("lights_off")
  except Exception as e:
    print(e)

Now head over to a service like Nexmo, sign up, and register a number to receive your messages. Then configure the Webhook endpoint to the URL of the function we wrote above. In my case, that’s https://tree-lights.anvil.app/_/api/receive-sms.

That’s all there is to it! Now all you have to do is remember how to send SMS messages, and you can turn your Christmas Tree lights on and off. Happy texting!


Give the Gift of Python

Share this post: