Setting up a Twilio Serverless Function

Head over to your Twilio Dashboard. On the left sidebar, click the All Products & Services Icon:

In the expanded sidebar, scroll down to the Runtime section and click the Functions item. You should be on this page:

Twilio Runtime Functions page

Click the plus icon. Twilio is kind enough to offer us a set of boilerplate templates. Go ahead and choose the Hello SMS template and click the Create button:

Creating new Twilio Runtime function

We have now created a runtime function with an SMS template. If you want, you can go ahead and modify the Function Name field to be something that is more reflective of this project. I’ll update mine to Dog Bot.

In the flow we described above, it sounds like the whole flow is initiated in the event of an incoming text message. Under Configuration, click the Event dropdown and select Incoming Messages and click the Save button. For the path, you can make it whatever you want — I will use woofbot.

Dog Bot initial configuration

Right now, our function flow is expressing: “On the event of an incoming message, run this code that replies to the person saying Hello World.”

After saving, we can text the Twilio phone number to validate this:

Great! Let’s move on to sending a picture of a dog in our message. On line three we can replace twiml.message("Hello World") with twiml.message().media(“https://direct_link_to_image.com/image.png”); . This will attach a media object with the link provided to our twiml.message() object.

We can test this by generating a call to the woofbot API. First, we need to figure out what breeds the API is supporting by visiting this URL:

Breeds list woofbot API endpoint

Based on this list, we can generate an API call to grab a picture of any these breeds through the following format: https://api.woofbot.io/v1/breeds/{breed}/image where {breed} is the breed you’re interested in.

I want a corgi picture, so I’ll visit https://api.woofbot.io/v1/breeds/corgi/image . After visiting, we will have a url field that contains the direct link to a corgi image:

woofbot.io Generate Corgi image endpoint

Copy the URL of the picture and we can paste it into our serverless function code:

After saving this change, we should now be able to text our Twilio phone number and receive a dog picture.

Hooray! We have made a program that sends out a dog picture on request! Our current solution is okay, but how can we make this program more dynamic, as our initial flow stated? Let’s take a look.