Upgrade to Pro — share decks privately, control downloads, hide ads and more …

From Data to Destinations: A Hands-on Workshop with Google Places API and Twilio

From Data to Destinations: A Hands-on Workshop with Google Places API and Twilio

Join me for an immersive and hands-on workshop, "From Data to Destinations: A Hands-on Workshop with Google Places API and Twilio," where you'll embark on a journey to create a location-driven app that harnesses the power of both Google Places API and Twilio WhatsApp API.

During this interactive session, you'll dive into the world of location-based data and explore how to leverage the Google Places API to discover important places in your vicinity. From popular restaurants to nearby attractions, you'll learn how to retrieve and utilize location information to provide valuable recommendations to app users.

We'll take it a step further by integrating the Twilio WhatsApp API into our app. You'll discover how to collect location information from users through WhatsApp, enabling them to conveniently share their preferences and interests. By combining the communication capabilities of Twilio with the data-rich results from the Google Places API, you'll create an app that delivers personalized recommendations directly to users' WhatsApp accounts.

Throughout the workshop, I will guide you through development, providing insights, tips, and best practices. Whether you're a beginner or an experienced developer, this workshop offers a unique opportunity to enhance your skills and explore the exciting possibilities of merging location data and communication features.

Join the workshop and unlock the potential of creating interactive and engaging apps that connect users with the world around them. Don't miss out on this exciting adventure!

Note: Participants are expected to have a basic understanding of web development concepts and APIs. Please bring your own laptop with a modern web browser and a text editor of your choice.

Notes and comments
This workshop session accommodates any level of engineering expertise whether a beginner or an experienced engineer.

Desmond Obisi

July 25, 2023
Tweet

More Decks by Desmond Obisi

Other Decks in Programming

Transcript

  1. About Me “I just want to build stuff” Desmond Obisi

    (he/him) Developer Experience Engineer @0X_anon_
  2. Welcome to 'From Data to Destinations: A Hands-on Workshop with

    Google Places API and Twilio!' In this interactive workshop, we'll explore how to harness the power of Google Places API and Twilio to create innovative and location-based applications. Join us as we dive into the world of data-driven experiences and learn how to integrate real-time location services and communication features. Intro To The Workshop
  3. Objectives During this interactive session, you'll dive into the world

    of location-based data and explore how to leverage the Google Places API to discover important places in your vicinity. From popular restaurants to nearby attractions, you'll learn how to retrieve and utilize location information to provide valuable recommendations to app users. We'll take it a step further by integrating the Twilio WhatsApp API into our app. You'll discover how to collect location information from users through WhatsApp, enabling them to conveniently share their preferences and interests. By combining the communication capabilities of Twilio with the data-rich results from the Google Places API, you'll create an app that delivers personalized recommendations directly to users' WhatsApp accounts.
  4. Technologies Twilio is a cloud communications platform that enables developers

    to build, scale, and customize communication applications. It provides a range of APIs that allow developers to integrate various communication channels, such as voice calls, text messaging (SMS), video, and email, into their applications and websites Google Places API is a service provided by Google that allows developers to access location-based data and information about places worldwide. It offers a range of functionalities that enable applications to search for places based on keywords or types, retrieve detailed information about specific places, access photos related to places, and provide real-time location suggestions. Twilio Google Places API
  5. Google Places Google Places API is a service provided by

    Google that allows developers to access a vast database of location-based information. It enables applications to retrieve data about places, businesses, points of interest, and geographic features around the world. Google Places API offers several essential functionalities. "Place Search" enables finding places based on keywords or types, while "Place Details" provides comprehensive information about a specific place. "Place Photos" allows access to images related to places, and "Place Autocomplete" offers real-time location suggestions as users type. What is Google Places API? Features and Capabilities To use Google Places API, developers need an API key obtained from the Google Developer Console. This key is used for authentication and tracking API usage. Setting up API access involves enabling the Places API and securing the API key for use in applications. Setting up API Access
  6. Twilio API The Twilio WhatsApp API serves as a powerful

    bridge, enabling applications to interact with WhatsApp's extensive user base. By integrating this API, developers can create innovative applications that programmatically send and receive messages through WhatsApp, revolutionizing their communication strategies. Twilio's WhatsApp API empowers developers with a rich set of messaging options like text messages, businesses can deliver visual content like images and documents. Furthermore, the ability to share location information opens doors for location-based services, allowing applications to provide real-time tracking, geo-targeted offers, and personalized recommendations to users, enhancing user experiences in diverse ways. What is Twilio Whatsapp API? Features and Capabilities WhatsApp's stringent policies demand responsible communication. Twilio WhatsApp API addresses this by mandating pre-approved message templates, ensuring businesses maintain high-quality interactions that align with WhatsApp's guidelines. Additionally, the API facilitates two-way communication, allowing applications to receive incoming messages, enabling personalized interactions and prompt responses. Compliance and Security
  7. Integrating Google Places API into Your Application • Setting up

    a development environment: A suitable development environment is crucial for building applications that leverage Google Places API. You can recommend popular development tools and platforms that work well with this API. • Making API requests using various HTTP methods (GET, POST): APIs use HTTP methods like GET and POST to interact with servers. In the context of Google Places API, you can explain how to make requests to retrieve place data using these methods. • Parsing API responses and extracting relevant data: API responses are typically provided in JSON format. You can explain how to parse this data and extract relevant information needed for the application. • Displaying location results on Whatsapp using Twilio API: We will demonstrate how to integrate the APIs to display location-based results effectively on Whatsapp bot using Twilio Whatsapp API.
  8. Enhancing Location-based Services with Twilio • Twilio APIs for SMS

    and MMS messaging, voice calls, and more: I have provided an overview of Twilio's APIs, emphasizing their functionalities and potential use cases. Examples include sending SMS notifications or making automated voice calls. • Integrating Twilio API to send location-based notifications and updates: We will go through the process of integrating Twilio API into the application to send location-based messages. I will showcase how this feature can provide users with timely and relevant updates. • Customizing and personalizing messages using dynamic data from Google Places API: I will illustrate how to use data from Google Places API to customize messages sent via Twilio. For instance, personalizing messages with specific place details or recommendations based on user preferences.
  9. We will be building with Node.js and Express! Setup is

    very simple - Create a new project folder, open it in your code editor. - Run this command `npm init` and follow the prompt to set up the Node.js project. - Create another folder in the root directory, call it functions and add index.js file to it. - Go to `https://twilio.com/try-twilio` and create an account. You will get your API keys and Whatsapp sandbox number. - Go to `https://console.cloud.google.com` and create a google cloud account. Create an app and generate the API for the service we want to use (Google Places API) using this guide We are not all set yet! Take a deep breeattthhh!!!
  10. - Run this command to generate a session secret: `node

    -e "console.log (crypto.randomBytes (32).toString ('hex'))"` - Create a new file name it `.env`. We will be storing some variables there. Yeah the one below. TWILIO_ACCOUNT_SID=your-twilio-account-sid TWILIO_AUTH_TOKEN=your-twilio-auth-token GOOGLE_CLOUD_API=your-google-place-api-key SESSION_SECRET=your-session-secret - We are all set now! Yeah I know it should be a secret but use my Google API Keys 🤫
  11. import express from 'express'; import bodyParser from 'body-parser'; import cors

    from 'cors'; import session from 'express-session'; import dotenv from 'dotenv'; import { sendMessage, searchPlaces, getLocation, getQuery } from './functions/index.js'; dotenv.config() const app = express(); /** middlewares */ app.use(express.json()); app.use(cors()); app.disable('x-powered-by'); // less hackers know about our stack app.use(bodyParser.urlencoded({ extended: false })); app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: true })); // Start the server app.listen(8000, () => { console.log('Server is running on port 8000'); });
  12. import twilio from 'twilio'; import axios from 'axios'; import dotenv

    from 'dotenv' dotenv.config() // Twilio credentials const accountSid = process.env.TWILIO_ACCOUNT_SID; const authToken = process.env.TWILIO_AUTH_TOKEN; // Set up Twilio client const twilioClient = twilio(accountSid, authToken); // Google Places API key const googlePlacesKey = process.env.GOOGLE_CLOUD_API; // Get location from message export function getLocation(message) { if (message.Longitude && message.Latitude) { return { lat: message.Latitude, long: message.Longitude }; } return null; } // Get query text from message export function getQuery(message) { return message.Body; }
  13. // Search Places API export async function searchPlaces(query, location) {

    const url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${location.lat},${location.long}&radius=3000&keyword=${query}&key= ${googlePlacesKey}` const response = await axios.get(url); const places = response.data.results; // console.log(url) // console.log(places) // return places.map(place => place.geometry.location); let results = [] places.forEach((place) => { results.push({ name: place.name, rating: place.rating, location: place.geometry.location }) }) return results } // Send WhatsApp message via Twilio export function sendMessage(body, recipient) { return twilioClient.messages.create({ body: body, from: recipient.To, to: recipient.From, }); }
  14. // Handle incoming messages app.post('/chat', async (req, res) => {

    req.session = req.session || {}; // Initialize if undefined let query; let location; // First message if (!req.session.state) { sendMessage('Hi there! Can you share your location?', req.body); req.session.state = 'LOCATION'; // Got location } else if (req.session.state === 'LOCATION') { location = getLocation(req.body); req.session.lat = location.lat req.session.long = location.long sendMessage('Thanks! What place are you looking for?', req.body); req.session.state = 'QUERY'; // Got query } else if (req.session.state === 'QUERY') { query = getQuery(req.body); const places = await searchPlaces(query, req.session); sendMessage(`Here are places near you for ${query}:`, req.body); places.forEach((place) => { sendMessage(`${place.name}, ${place.rating} rating \nhttps://www.google.com/maps?z=12&t=m&q=loc:${place.location.lat}+${place.location.lng}`, req.body); }); req.session.state = 'DONE'; // Reset } else if (req.session.state === 'DONE') { req.session.query = null; req.session.state = null; req.session.lat = null; req.session.long = null; sendMessage('Thanks for using our service! Send any message to start again.', req.body); } res.sendStatus(200); });
  15. We will be hosting this with ngrok! Setup is very

    simple too - Visit this web url `https://ngrok.com/download`. - Follow the prompt for your OS and download ngrok. - Login or Signup to get your auth token which you will use to finish the setup on your machine. - Run `ngrok http 8000`, it will return a https url of our hosted app (it’s a proxy ish, check ngrok docs to understand better) We are halfway there! Breeeathhhhh!!!
  16. We will be using Twilio sandbox for Whatsapp but you

    can test it on your phone. How?? - Go to the Sandbox settings to update the webhook url to `your-ngrok-url/chat`. - Add the Sandbox number to your Whatsapp. - Start by sending any message and have fun finding your destinations or places around you.