``` const express = require(‘express’); const app = express(); app.use(express.json()); app.post(‘/callback/message’, messageHandler); app.listen(12345, () => console.log(‘Server listening on port 12345!’); ```

Personalized Dialogflow Agent
Dialogflow application is a Google framework that provides NLP / NLU (Natural Language Processing / Natural Language Understanding). Dialogflow enables you to create an Intelligent Agent and to manage what the Agent understands and how it responds.
For each Agent, you can define multiple end-user’s intentions called Intents. When an end-user writes something, Dialogflow matches the expression to the best Intent of your agent. Combined intents can handle a complex conversation.
When the Intent is detected, Dialogflow decides how to respond. You can set up multiple predefined responses called Actions.
Let’s create a specific Agent that we will use later in our application via API. If you are familiar with Dialogflow, you can just download Fashion.zip with all Intents already created. If you import the zip file into your Dialogflow account, you get an agent with the following configurations:
- Dialogflow Agent for fashion industry
- Entities: Popular Category, Product and Product Size
- Intents with a single appropriate Action: Default Fallback, Fashion Trends, Price Check and Product Availability
Tip: To learn how to create a real WhatsApp chatbot, see Building an Application with the tyntec API for WhatsApp.
If you want to try personalizing the agent yourself, see Dialogflow Tutorial.
Note: It is possible to use any programming language. We used JavaScript with Node.js with Express Server for the following example.
Prerequisites
- Dialogflow API authentication
To set up your credentials, go to https://dialogflow.com/docs/reference/v2-auth-setup - Node.js installed
Important: Ensure that Express Server, Axios, and Dialogflow client from npm was installed automatically with “npm install”
Note: You can check the complete code here: https://github.com/tyntec/tyntec-whatsapp-dialogflow-demo
Set up the Personalized Agent in API
Expose an HTTP Endpoint
To receive WhatsApp messages, expose an HTTP endpoint implementing POST method. Set this endpoint as a webhook URL in your tyntec Account (see Building an Application with the tyntec API for WhatsApp, section Webhook URL)
Connect Multiple Questions with Sessions
The Dialogflow chatbot is capable of holding a conversation context across several messages using sessions. The session connects multiple questions together.
Example
Ask about a product in the first question, about a color in the second question, and about a price in the third question. Dialogflow bot answers with a product with a specific color and price.
``` const dialogflow = require(‘dialogflow’); const messageHandler = async (req, res) => { const sessionClient = new dialogflow.SessionsClient(); const sessionPath = sessionClient.sessionPath(‘your-project-id’, req.body.from); ```
``` const request = { session: sessionPath, queryInput: { text: { text: req.body.content.text, languageCode: 'en-US', }, }, }; const result = await sessionClient.detectIntent(request); ```
As you can see in detectIntent detailed documentation (DetectIntent Documentation), the result of this query is a JSON with many different fields. One of the fields is an “action”. The field contains the name of the action (created in Dialogflow in the previous part of this tutorial).
``` switch (result[0].queryResult.action) { case 'fashion.trends': response = trendsHandler(result[0]); break; … } ```
TrendsHandler is the function that creates a specific WhatsApp message that reacts to Fashion Trends intent. If the intent was not fulfilled yet, it means that the goal hasn’t been reached and the conversation continues, probably because the user needs to add some more info. We do that using our own sendWhatsappTextMessage function:
\``` const { products } = require('./mocks'); const trendsHandler = response => { await whatsappClient.sendWhatsappTextMessage({ from: <our_number>, to: <recipient_number>, text: response.queryResult.fulfillmentText }); ... ```
When the intent is fulfilled, the conversation is over and we reached the goal. In this case, the user successfully asked the chatbot to send them information about specific products.
This was a short example of how to do that. There was also a face database mockup in our example. You have to get your real product from your own database, of course:
``` … if (response.queryResult.allRequiredParamsPresent) { const pictures = products .filter(product => product.category === response.queryResult.parameters.fields.Category.stringValue) .map(product => ({ caption: product.name, type: 'image', url: product.picture, })), for (const picture of pictures) { await whatsappClient.sendWhatsappImage({ from: req.body.to, to: req.body.from, media: picture, }); } } ```
Note: For communication with WhatsApp API, you will require a tyntec account API key.
For more information about tyntec account and API key, see Building an Application with the tyntec API for WhatsApp.
Specify which channel you want to use, in this case “whatsapp”:
``` const axios = require('axios'); const config = require('../config.json'); const sendWhatsappTextMessage = async params => { const request = { to: params.to, channels: ['whatsapp'], whatsapp: { from: params.from, contentType: 'text', text: params.text, }, }; return axios.post(`your_base_url/messages`, request, { headers: { apikey: your_tyntec_api_key } }); } ```
Tip: Feel free to use our example and even change it or incorporate it into your own application. You can find it here: Dialogflow demo
Note: Setting up WhatsApp Business API is not part of this tutorial. For integrating the personalized Agent into WhatsApp Business API, see Building an Application with the tyntec API for WhatsApp.