|

|  How to Integrate Google Dialogflow with WhatsApp

How to Integrate Google Dialogflow with WhatsApp

January 24, 2025

Discover how to effortlessly connect Google Dialogflow and WhatsApp to enhance your bot's capabilities and improve customer interactions in a few simple steps.

How to Connect Google Dialogflow to WhatsApp: a Simple Guide

 

Set Up a Dialogflow Agent

 

  • Go to the [Dialogflow Console](https://dialogflow.cloud.google.com/).
  •  

  • Click on "Create Agent" and fill in the required information such as Agent name, Default language, and Default time zone.
  •  

  • Click "Create" to finalize the creation of the Dialogflow agent.

 

Create Intents in Dialogflow

 

  • In Dialogflow, go to "Intents" on the left sidebar and click "Create Intent".
  •  

  • Define the name of the intent and add training phrases that users might say to trigger the intent.
  •  

  • In the "Responses" section, define what the agent should respond with when the intent is matched.

 

Create a Google Cloud Project and Enable APIs

 

  • Visit the [Google Cloud Console](https://console.cloud.google.com/).
  •  

  • Create a new project.
  •  

  • Navigate to "APIs & Services" and enable the "Dialogflow API".
  •  

  • Enable the "Cloud Functions API" if you plan on using Fulfillment with Cloud Functions.

 

Set Up WhatsApp with Twilio

 

  • Sign up for a [Twilio Account](https://www.twilio.com/) and complete the verification process.
  •  

  • Navigate to the Twilio Console and purchase a Twilio phone number with WhatsApp capabilities.
  •  

  • Configure your Twilio number to integrate with Dialogflow for message routing.

 

Create a Webhook to Connect Twilio with Dialogflow

 

  • Set up an endpoint using a server-side language like Node.js, Python, or PHP, which will act as a bridge between Twilio and Dialogflow. Here's a simple Node.js example:

 


const express = require('express');
const bodyParser = require('body-parser');
const { WebhookClient } = require('dialogflow-fulfillment');

const app = express().use(bodyParser.json());

app.post('/webhook', (req, res) => {
  const agent = new WebhookClient({ request: req, response: res });

  function welcome(agent) {
    agent.add('Welcome to my WhatsApp Dialogflow integration!');
  }

  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);

  agent.handleRequest(intentMap);
});

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

 

  • Deploy your webhook to a server or use a service like Google Cloud Functions or AWS Lambda.
  •  

  • Make sure your webhook is accessible over the internet with a secure HTTPS endpoint.

 

Connect Webhook to Twilio

 

  • Return to your Twilio Console, navigate to "WhatsApp" and then "Sandbox" if you are using the test environment.
  •  

  • Set the "WHEN A MESSAGE COMES IN" URL to the address of your deployed webhook.
  •  

 

Test the Integration

 

  • Send a test message from WhatsApp to your Twilio number.
  •  

  • Verify the message is logged in your webhook and the response from Dialogflow is correctly passed back to the user through WhatsApp.

 

Monitoring and Scaling

 

  • Use logging and monitoring tools like Google Cloud Operations Suite to keep track of your webhook performance.
  •  

  • Consider setting up a load balancer and scaling policies if you anticipate high levels of traffic.

 

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

How to Use Google Dialogflow with WhatsApp: Usecases

 

Customer Support Automation

 

  • Integrate Google Dialogflow with WhatsApp to automate customer support queries, providing instant responses to frequently asked questions without human intervention.
  •  

  • Leverage Dialogflow's natural language understanding to comprehend and respond to customer inquiries meaningfully and accurately.

 


// Sample code snippet to integrate Dialogflow with WhatsApp

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');

exports.dialogflowWhatsApp = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });

  function welcome(agent) {
    agent.add(`Welcome to my WhatsApp bot! How can I assist you today?`);
  }

  function fallback(agent) {
    agent.add(`I'm sorry, I didn't understand that. Can you rephrase?`);
  }

  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);

  agent.handleRequest(intentMap);
});

 

Order Status Updates

 

  • Use Google Dialogflow to retrieve order information from the backend systems and provide real-time updates to customers on WhatsApp regarding their order status and expected delivery times.
  •  

  • Notify customers instantly upon changes in order status, thereby enhancing customer satisfaction and reducing the workload on customer service representatives.

 


# Example code to send WhatsApp message through Twilio API

from twilio.rest import Client

def send_whatsapp_message(order_status):
    client = Client("TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN")
    message = client.messages.create(
        from_='whatsapp:+14155238886',
        body=f'Your order status is: {order_status}',
        to='whatsapp:+1234567890'
    )
    print(message.sid)

 

Product Recommendations

 

  • Enable personalized product recommendations on WhatsApp by using Dialogflow to analyze customer preferences and transaction history.
  •  

  • Enhance sales and customer engagement by providing suggestions and promotions tailored to individual customer needs.

 


{
  "intent": "Product Recommendation",
  "trainingPhrases": [
    "Suggest some products",
    "What should I buy next?",
    "Any recommendations?"
  ],
  "responses": [
    "Based on your recent purchases, we suggest these items: ...",
    "Here are some products you might like..."
  ]
}

 

 

Appointment Scheduling

 

  • Integrate Google Dialogflow and WhatsApp to automate the appointment scheduling process, allowing users to book, reschedule, or cancel appointments through an intuitive chat interface.
  •  

  • Use Dialogflow's conversational intelligence to manage and understand diverse user requests, ensuring accurate appointment management.

 


// Example of a webhook to handle appointment booking with Dialogflow

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');

exports.dialogflowAppointment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });

  function bookAppointment(agent) {
    const date = agent.parameters.date;
    agent.add(`Your appointment is booked for ${date}.`);
  }

  function rescheduleAppointment(agent) {
    const newDate = agent.parameters.new_date;
    agent.add(`Your appointment has been rescheduled to ${newDate}.`);
  }

  function cancelAppointment(agent) {
    agent.add(`Your appointment has been canceled.`);
  }

  let intentMap = new Map();
  intentMap.set('Book Appointment Intent', bookAppointment);
  intentMap.set('Reschedule Appointment Intent', rescheduleAppointment);
  intentMap.set('Cancel Appointment Intent', cancelAppointment);

  agent.handleRequest(intentMap);
});

 

Feedback Collection

 

  • Leverage the integration to collect customer feedback efficiently after services or purchases, using WhatsApp messages initiated through Dialogflow.
  •  

  • Gain valuable insights into customer satisfaction and areas for improvement by automating survey responses through engaging and conversational methods.

 


# Python script to send feedback request via WhatsApp using Twilio

from twilio.rest import Client

def send_feedback_request():
    client = Client("TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN")
    message = client.messages.create(
        from_='whatsapp:+14155238886',
        body='We would love to hear your feedback on our service. Please reply with your thoughts!',
        to='whatsapp:+1234567890'
    )
    print(message.sid)

 

Multi-language Support

 

  • Utilize Dialogflow's multi-language capabilities to interact with customers in their preferred language over WhatsApp, enhancing global user experience.
  •  

  • Configure language-specific intents and responses to provide accurate and culturally relevant interactions for diverse customer bases.

 


{
  "intent": "Language Selection",
  "trainingPhrases": [
    "I prefer English",
    "Let's talk in Spanish",
    "Can we switch to French?"
  ],
  "responses": [
    "Sure, we can continue in English.",
    "Claro, podemos continuar en Español.",
    "Bien sûr, nous pouvons continuer en Français."
  ]
}

 

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Order Friend Dev Kit

Open-source AI wearable
Build using the power of recall

Order Now

Troubleshooting Google Dialogflow and WhatsApp Integration

Why is my Dialogflow chatbot not responding on WhatsApp?

 

Check Webhook Functionality

 

  • Ensure your webhook URL is accessible from the public internet. Dialogflow needs this to send responses back to WhatsApp.
  • Verify that your server's SSL certificate is up-to-date and recognized by browsers to avoid handshake errors.

 

Review Fulfillment Code

 

  • Check the fulfillment script's logic for handling WhatsApp channel data. Consider adding logging to track processing.
  • Inspect your code for required WhatsApp-specific message formatting.

 

const sendWhatsappResponse = (responseText) => {
  let message = {
      to: 'whatsapp:<RECIPIENT_PHONE>',
      body: responseText
  };
  // Logic to send message
}

 

Examine WhatsApp Settings

 

  • Ensure that your WhatsApp business account is correctly linked to the Dialogflow agent.
  • Consult the platform integration settings on WhatsApp API to verify tokens and environment variables.

 

How to connect Google Dialogflow to WhatsApp Business API?

 

Set Up a Webhook

 

  • Create a cloud function on Google Cloud Platform to integrate Dialogflow with WhatsApp. This function will act as a webhook and handle incoming messages.
  •  

  • Enable Dialogflow API and deploy the function to respond to HTTP requests.

 

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def dialogflow_webhook():
    req = request.get_json(silent=True, force=True)
    return jsonify(fulfillmentText=req['queryResult']['fulfillmentText'])

if __name__ == '__main__':
    app.run()

 

Configure WhatsApp Business API

 

  • Set up the WhatsApp Business API client and register your phone number. Once set up, you'll receive messages at an endpoint URL, which you should point to your deployed Dialogflow webhook.
  •  

  • Create a script that listens for messages from the WhatsApp endpoint and forwards them to your Dialogflow webhook.

 

Link Dialogflow to WhatsApp

 

  • Utilize a service like Twilio or MessageBird to bridge WhatsApp Business API and Dialogflow by routing WhatsApp messages through the webhook URL.
  •  

  • Ensure both inbound and outbound message capabilities are configured correctly in your chosen service.

 

What is the best way to handle WhatsApp message templates in Dialogflow?

 

Managing WhatsApp Message Templates in Dialogflow

 

  • Define Templates in WhatsApp: Before using them in Dialogflow, ensure that your message templates are approved by WhatsApp. This approval is crucial to ensure smooth communication.
  •  

  • Leverage Dialogflow's Fulfillment: Use Dialogflow's fulfillment to send template messages by integrating with a service like Twilio or Vonage, which supports WhatsApp. You can trigger template messages through webhook calls from your intents.
  •  

  • Implement Webhook for Template Messaging: Design your webhook to handle template parameters dynamically. This allows you to customize messages based on user inputs collected in Dialogflow.

 

exports.sendWhatsAppTemplate = (req, res) => {
  const templateParams = { phone: req.body.phone, message: req.body.message };
  sendMessageViaTwilio(templateParams).then((response) => {
    res.json({ fulfillmentText: "Message sent successfully!" });
  }).catch((error) => {
    res.json({ fulfillmentText: "Failed to send message." });
  });
};

 

  • Use Rich Features: Utilize placeholders in templates to provide dynamic content. Define and pass these parameters from Dialogflow to the webhook in JSON format.
  •  

  • Monitor and Iterate: Constantly monitor the effectiveness of your templates and interactions, refining them for clarity and engagement based on user feedback and interaction analysis.

 

Don’t let questions slow you down—experience true productivity with the AI Necklace. With Omi, you can have the power of AI wherever you go—summarize ideas, get reminders, and prep for your next project effortlessly.

Order Now

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi Dev Kit 2

Endless customization

OMI DEV KIT 2

$69.99

Make your life more fun with your AI wearable clone. It gives you thoughts, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

Your Omi will seamlessly sync with your existing omi persona, giving you a full clone of yourself – with limitless potential for use cases:

  • Real-time conversation transcription and processing;
  • Develop your own use cases for fun and productivity;
  • Hundreds of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

thought to action

team@basedhardware.com

company

careers

events

invest

privacy

products

omi

omi dev kit

personas

resources

apps

bounties

affiliate

docs

github

help