This example code is from the how to build a location-aware WhatsApp application Twilio webinar and the Building with the Twilio API for WhatsApp. It demonstrates how to build a WhatsApp bot that reacts to different inputs, including location. It can send messages that include text, images, files and locations.
This bot responds to a number of commands:
- contact: sends a VCard with Phil's contact details
- picture: sends a picture of Alex, the Twilio developer evangelism team mascot
- If you send your location, it looks up restaurants from the Foursquare API and sends you an image, description and location of a nearby restaurant
- If you send anything else it will respond with a default message
To run this bot yourself you will need:
- A Twilio account (sign up for a free Twilio account here)
- Node.js
- A WhatsApp account
- A Foursquare developer account
Then, clone the repository:
git clone https://github.com/philnash/whatsapp-bot-capabilities.git
cd whatsapp-bot-capabilities
Install the dependencies:
npm install
Copy the .env.example
file to .env
:
cp .env.example .env
Get your Twilio Account Sid and Auth Token from your Twilio console and enter them in .env
.
Create a Foursquare application and get your Foursquare API client ID and secret from the Foursquare developers portal and enter them in .env
.
Go to your Twilio account and follow the prompts to set up the Twilio Sandbox for WhatsApp
You can run the bot locally, which will use ngrok to tunnel through to your account. Start the application with:
npm start -- --ngrok
Then take the URL for the /whatsapp
function (which should look like https://RANDOM_SUBDOMAIN.ngrok.io/whatsapp
) and paste it into the Twilio WhatsApp Sandbox configuration.
Then send your bot a message.
To deploy the function, you can run:
npm run deploy
When the script is finished you will see a URL that looks like https://whatsapp-bot-webinar-XXXX-dev.twil.io/whatsapp
. Take that URL and paste it into the Twilio WhatsApp Sandbox configuration.
Then send your bot a message.
- Twilio API for WhatsApp docs
- WhatsApp guide for getting opt-in from your users
- Build a WhatsApp chatbot with Ruby, Sinatra and Twilio
- Build a location-aware WhatsApp weather bot with Ruby, Sinatra and Twilio
- Using Location Data in WhatsApp to find nearby healthy restaurants using Twilio and JavaScript
- Using WhatsApp with the Twilio Conversations API
- Using WhatsApp with Twilio Autopilot