How to Create a Dialogflow Chatbot using Flask ( Python Framework)
Tags: python, chatbo, flutter, flask
Published: 2023-02-22 08:22:03

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In this post, we will learn how to add a Dialogflow chatbot to Python frameworks such as Flask or Django. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3><strong>Pre-requisites:</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You will need a Dialogflow account, a <a href="https://www.kommunicate.io/">Kommunicate</a> account for deploying the chatbot. Also, you will need <a href="https://www.python.org/" target="_blank" rel="noreferrer noopener">Python</a> and Flask framework installed on your system. To need more info about the Flask framework, please refer to this <a href="https://flask.palletsprojects.com/en/1.1.x/quickstart/" target="_blank" rel="noreferrer noopener">link</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We will be using Flask in this tutorial. If you are looking to add Dialogflow chatbot to the Django framework, <a href="https://www.kommunicate.io/blog/dialogflow-chatbot-django-website/">you can see this tutorial</a>. </p>
<!-- /wp:paragraph -->



<!-- wp:heading -->
<h2>Steps to Add Dialogflow Chatbot to Flask</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3><strong>Create an agen</strong>t</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Login to the <a href="https://dialogflow.cloud.google.com/" target="_blank" rel="noreferrer noopener">Dialogflow console</a>. 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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Click the dropdown near the Agent settings, then click <strong>Create new agent</strong>, provide an agent name (For example – Python-Demo), then click <strong>CREATE</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":6174,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.kommunicate.io/blog/wp-content/uploads/2021/06/python-1.png" alt="dialogflow chatbot python - creating an agent" class="wp-image-6174"/></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3><strong>Create an intent</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Click the <strong>CREATE INTENT</strong> button and provide an intent name (for example, python-demo) and save.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":6175,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.kommunicate.io/blog/wp-content/uploads/2021/06/python-2.png" alt="dialogflow chatbot python - create an intent" class="wp-image-6175"/></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3><strong>Add training phrases</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>These are example phrases for what end-users might say. When an end-user expression resembles one of these phrases, Dialogflow matches the intent.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Click the intent created (python-demo) and add the user phrases in the <strong>Training phrases</strong> section.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":6176,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.kommunicate.io/blog/wp-content/uploads/2021/06/pythin-3.png" alt="dialogflow chatbot python - add training phrases " class="wp-image-6176"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>🚀&nbsp; Here's a video for you on creating a Dialogflow chatbot and learning more about agents, intents, and entities:</p>
<!-- /wp:paragraph -->

<!-- wp:embed {"url":"https://youtu.be/42p-nuzGnEI","type":"video","providerNameSlug":"youtube","responsive":true,"className":"wp-embed-aspect-16-9 wp-has-aspect-ratio"} -->
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
https://youtu.be/42p-nuzGnEI
</div></figure>
<!-- /wp:embed -->

<!-- wp:heading {"level":3} -->
<h3><strong>Enable fulfillment</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>After adding an intent, you don’t need to add agent responses in the <strong>Responses</strong> 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. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Under the&nbsp;<strong>Fulfillment</strong>&nbsp;section, click Enable webhook for this intent and save the intent.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":6179,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.kommunicate.io/blog/wp-content/uploads/2021/06/python-11.png" alt="dialogflow chatbot python - enable fulfillment" class="wp-image-6179"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Go to the&nbsp;<strong>“Fulfillment”</strong>&nbsp;section &amp; enable <strong>Webhook</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":6177,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.kommunicate.io/blog/wp-content/uploads/2021/06/python-4.png" alt="dialogflow python chatbot - enable fulfillment" class="wp-image-6177"/></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3><strong>Using Python with Flask &amp; enable webhook server</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We are using Python programming language and Flask framework to create the webhook. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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 <a href="https://flask.palletsprojects.com/en/1.1.x/installation/#install-flask" target="_blank" rel="noreferrer noopener">documentation </a>for the same.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import flask
import json
import os
from flask import send_from_directory, request</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Also, a fulfillment text is added to return that when it triggers the training phrase from Dialogflow.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you need to add more conditions &amp; responses, you can define them inside the webhook method.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code># 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=&#91;'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()</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>After setting up the Python process, let's use&nbsp;<a href="https://ngrok.com/" target="_blank" rel="noreferrer noopener">Ngrok</a>&nbsp;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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You will get a URL like&nbsp;https://f3e3a29d7ae9.ngrok.io/webhook&nbsp;where the&nbsp;<em>webhook</em>&nbsp;is the POST route for Dialogflow we mentioned in the Python file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Copy the URL you created (In this example - https://f3e3a29d7ae9.ngrok.io/webhook) and paste it into the Dialogflow fulfillment <strong>URL</strong> field.</p>
<!-- /wp:paragraph -->


<!-- wp:paragraph -->
<p>Once the Dialogflow setup is done, you can easily&nbsp;<a href="https://www.kommunicate.io/blog/integrate-bot-using-dialogflow-in-kommunicate/">add it to your website or apps using Kommunicate</a> &amp; test the Python chatbot working.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":6180,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.kommunicate.io/blog/wp-content/uploads/2021/06/python-7.png" alt="dialogflow chatbot python - The chat UI" class="wp-image-6180"/></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>Wrapping Up</h2>
<!-- /wp:heading -->