Food Glorious Food! Using Location Data in WhatsApp to find nearby healthy restaurants using Twilio and JavaScript.
The life of a Developer Evangelist can be very unhealthy. I travel to many different countries and end up ordering fast food to my hotel room far more frequently than I would like. This year, I’m trying to take control of my diet, particularly when on the road. However, I also suffer from decision paralysis. Looking at a long list of restaurants and filtering through them to find restaurants with healthy options can often be tedious and frustrating.
The amazing thing about being a developer is that I can build tools to solve my problems. Today I’m going to show you how I created a bot to find the closest restaurants serving healthy food, no matter where in the world I am! Follow along to build your own.
The Twilio API for WhatsApp makes gathering location data from users easy, enabling us to respond appropriately. Therefore, we’ll use WhatsApp as the channel for our bot.
What We'll Need
- A Twilio Account (Get one here for Free)
- A Travel API with restaurant information (I’m using the Zomato API)\
Setting Up Our Function
In this project, we’ll use Twilio Functions as they runJavaScript code directly on Twilio. They are also one of the easiest ways to have code respond to an incoming message.
Head on over to the Twilio Functions page and create a new function using the "blank function" template. Give the function a name and set its path to /food
. Make a note of the whole URL as we will use it later. Be sure to Save the function. By pressing the Save
button at the bottom of the page
We are going to use axios to make HTTP requests to the Travel API. To add this to our environment, navigate to the Configure section on the left-hand side of the Twilio Console and add axios
to our dependencies. I built this using axios version 0.19.1.
We can also add any environment variables we need here such as the API credentials for Zomato. I’ll be adding an environmental variable called ZOMATO_API_KEY
that I’ll be using in my code.
Getting Location Data from WhatsApp
WhatsApp enables users to share their location data with ease. When Twilio receives the location data in a WhatsApp message, it will make a request to our Twilio Function. It surfaces the location data as request parameters with latitude, longitude and an address if available.
To get started with the Twilio API for WhatsApp, you will need to set up a Twilio Sandbox number. After you have completed setup, make sure you have used your personal sandbox keyword to join your sandbox conversation from your WhatsApp App.
Once set up, configure the "When a message comes in" field to make a POST request to the URL we noted earlier in the Twilio Function.
Navigate back to the Twilio Function and get ready to write some code!