DEV Community

Devashish Datt Mamgain
Devashish Datt Mamgain

Posted on

How to Create a Dialogflow Chatbot using Flask ( Python Framework)

Chatbots are software tools created to interact with humans through chat. The first chatbots were able to create simple conversations based on a complex system of rules. Using Python and Dialogflow frameworks, you would be able to build intelligent chatbots.

In this post, we will learn how to add a Dialogflow chatbot to Python frameworks such as Flask or Django.

Pre-requisites:

You will need a Dialogflow account, a Kommunicate account for deploying the chatbot. Also, you will need Python and Flask framework installed on your system. To need more info about the Flask framework, please refer to this link.

We will be using Flask in this tutorial. If you are looking to add Dialogflow chatbot to the Django framework, you can see this tutorial.

Steps to Add Dialogflow Chatbot to Flask

Create an agent

Login to the Dialogflow console. An agent is just a chatbot. You can train the agent with training phrases and corresponding responses to handle expected conversation scenarios with your end-users.

Click the dropdown near the Agent settings, then click Create new agent, provide an agent name (For example – Python-Demo), then click CREATE.

dialogflow chatbot python - creating an agent

Create an intent

An intent categorizes end-users intention for one conversation turn. For each agent, you can define many intents. When an end-user writes or says something, referred to as an end-user expression, Dialogflow matches the end-user expression to the best intent in your agent.

Click the CREATE INTENT button and provide an intent name (for example, python-demo) and save.

dialogflow chatbot python - create an intent

Add training phrases

These are example phrases for what end-users might say. When an end-user expression resembles one of these phrases, Dialogflow matches the intent.

Click the intent created (python-demo) and add the user phrases in the Training phrases section.

dialogflow chatbot python - add training phrases

🚀  Here's a video for you on creating a Dialogflow chatbot and learning more about agents, intents, and entities:

https://youtu.be/42p-nuzGnEI

Enable fulfillment

After adding an intent, you don’t need to add agent responses in the Responses section. Since we are using Flask for the same, you need to enable webhook for this intent. The webhook will help us transfer data and responses between Dialogflow and Flask. Dialogflow provides webhook services via Dialogflow Fulfillment.

Fulfillment is a code deployed through a web service to provide data to a user. You can enable webhook calls for all those intent that required some backend processing, database query, or third-party API integration.

Under the Fulfillment section, click Enable webhook for this intent and save the intent.

dialogflow chatbot python - enable fulfillment

Dialogflow fulfillment has two options – Webhook and Inline Editor. The inline editor is also a webhook but hosted by Google cloud functions. We are going to use the webhook.

Go to the “Fulfillment” section & enable Webhook.

dialogflow python chatbot - enable fulfillment

Using Python with Flask & enable webhook server

The webhook requires a URL, and it should be an HTTPS protocol. The webhook URL will receive a POST request from Dialogflow every time an intent triggers the webhook.

We are using Python programming language and Flask framework to create the webhook.

Create a file (for example - app.py). Import all the necessary libraries (ex: os, JSON, send_from_directory, request) needed for Python. Please check if you have Flask on your system. If not, install it using pip, and here’s the documentation for the same.

import flask
import json
import os
from flask import send_from_directory, request

To handle all the agent webhook requests, we need to define and add a route/webhook method with a POST request. A POST request will be sent to this URL /webhook. It executes all the methods inside the method.

Also, a fulfillment text is added to return that when it triggers the training phrase from Dialogflow.

If you need to add more conditions & responses, you can define them inside the webhook method.

# Flask app should start in global layout
app = flask.Flask(__name__)

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/favicon.png')

@app.route('/')
@app.route('/home')
def home():
    return "Hello World"

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(force=True)
    print(req)

    return {
        'fulfillmentText': 'Hello from the bot world'
    }

if __name__ == "__main__":
    app.secret_key = 'ItIsASecret'
    app.debug = True
    app.run()

After setting up the Python process, let's use Ngrok to create a public URL for the webhook and listen to port 3000 (in this example). For Dialogflow fulfillment, you will need an HTTPS secured server since the local server (localhost) will not work. You can also use a server and point a domain with HTTPS to that server.

You will get a URL like https://f3e3a29d7ae9.ngrok.io/webhook where the webhook is the POST route for Dialogflow we mentioned in the Python file.

Copy the URL you created (In this example - https://f3e3a29d7ae9.ngrok.io/webhook) and paste it into the Dialogflow fulfillment URL field.

Once the Dialogflow setup is done, you can easily add it to your website or apps using Kommunicate & test the Python chatbot working.

dialogflow chatbot python - The chat UI

Wrapping Up

Top comments (0)