---
title: Django與Google Dialogflow的串接
tags: Django, python, Dialogflow
---
# Django與Google Dialogflow的串接
> [TOC]
>
> Reference Website:
> 1. [Flask與Dialogflow串接之教學](https://pusher.com/tutorials/chatbot-flask-dialogflow)
---
## Dialogflow套件安裝
* 進入Django project的虛擬環境,並安裝dialogflow套件。
```
$ pip install dialogflow
```
* Dialogflow套件含以下內容
```
cachetools==3.1.1
certifi==2019.6.16
chardet==3.0.4
dialogflow==0.6.0
Django==2.2.2
google-api-core==1.14.2
google-auth==1.6.3
googleapis-common-protos==1.6.0
grpcio==1.23.0
idna==2.8
mysqlclient==1.4.2.post1
protobuf==3.9.1
pyasn1==0.4.7
pyasn1-modules==0.2.6
pytz==2019.1
requests==2.22.0
rsa==4.0
six==1.12.0
sqlparse==0.3.0
urllib3==1.25.3
```
## Step1: 到Google建立Dialogflow代理機器人
* Create new agent `Django_StatBot`
* Language: Chinese (Traditional) zh-tw
> 取得 Project ID:`django-statbot-shtmnf`


## Step2: 取得`Django_StatBot`的Google Dialogflow API使用權
1. Go to [ Google Cloud Platform](https://console.cloud.google.com/home/dashboard).
2. Select our bot project name - `Django_StatBot`

3. Next, go to API和服務(APIs & Services) then Credentials(憑證)

4. Under Create credentials, click on Service account key
* Select Dialogflow integrations under Service account.
* Then select JSON under key type.

* Download !
> Now, copy the downloaded JSON file (Django-StatBot-ae3aee62a5a1.json) to the root folder of the project - movie_bot.
## Step3: 與Django網站串接
1. Create new app `home`
2. Setting
* `stat01/stat01/settings.py`
```python=
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home',
]
```
* `stat01/stat01/urls.py`
```python=
from django.contrib import admin
from django.urls import path
from home import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name="home"), ####首頁
]
```
* `stat01/home/views.py`
```python=
from django.shortcuts import render
# Create your views here.
from home.models import Message
import dialogflow
from google.api_core.exceptions import InvalidArgument
import os
import uuid
DIALOGFLOW_PROJECT_ID = 'django-statbot-shtmnf'
DIALOGFLOW_LANGUAGE_CODE = 'zh-TW'
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/WebSite/stat01/home/Django-StatBot-ae3aee62a5a1.json"
SESSION_ID = uuid.uuid1()
# Create your views here.
def home(request):
# --- 新增 --- #
session_client = dialogflow.SessionsClient()
session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
if 'user_input' in request.POST: ##
text_to_be_analyzed = request.POST.get('user_input')
text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
query_input = dialogflow.types.QueryInput(text=text_input)
try:
response = session_client.detect_intent(session=session, query_input=query_input)
m = Message.objects.create(user_input_text=response.query_result.query_text, detected_intent = response.query_result.intent.display_name, detected_intent_confidence = response.query_result.intent_detection_confidence, chatbot_output_text = response.query_result.fulfillment_text)
m.save()
messages = Message.objects.order_by('timestamp')
context = {'user_input_text':response.query_result.query_text, 'detected_intent': response.query_result.intent.display_name, 'detected_intent_confidence': response.query_result.intent_detection_confidence,'chatbot_output_text ': response.query_result.fulfillment_text}
m_lastone = Message.objects.last()
print("---")
print("Query text:", response.query_result.query_text)
print("Detected intent:", response.query_result.intent.display_name)
print("Detected intent confidence:", response.query_result.intent_detection_confidence)
print("Fulfillment text:", response.query_result.fulfillment_text)
return render(request, 'index.html', {'m_lastone': m_lastone})
except InvalidArgument:
raise
# --- --- #
return render(request, 'index.html', locals())
```
* 把`Django-StatBot-ae3aee62a5a1.json`放進`stat01/home/`內
* Database Setting
* `stat01/home/models.py`
```python=
from django.db import models
# Create your models here.
class Message(models.Model):
user_input_text = models.CharField(max_length=100)
detected_intent = models.CharField(max_length=255)
detected_intent_confidence = models.CharField(max_length=255)
chatbot_output_text = models.CharField(max_length=255)
timestamp = models.DateTimeField(auto_now_add=True)
```
* `stat01/home/admin.py`
```python=
from django.contrib import admin
# Register your models here.
from .models import Message
class MessageAdmin(admin.ModelAdmin):
list_display = ('user_input_text', 'detected_intent', 'detected_intent_confidence')
admin.site.register(Message, MessageAdmin)
```
* templates
* `stat01/templates/index.html`
```htmlmixed=
{% extends 'base/base.html' %}
{% block title %}index{% endblock %}
{% load staticfiles %}
{% block link %}
<link rel="stylesheet" href="{% static 'css/CssLayout.1.css' %}" type="text/css" media="screen" />
{% endblock %}
{% block content %}
<div class="row">
<div class="column side">
<h1>Content</h1>
</div>
<div class="column middle">
<h1>Main Content</h1>
</div>
<div class="column side">
<h1>Content</h1>
</div>
</div>
<form action="/" method="post" id="myForm">
{% csrf_token %}
<input type="text" name="user_input" value="" />
<button type="button" onclick="submit()" class="btn btn-warning">OK</button>
</form>
{% include "short.html" %}
{% endblock %}
<!-- https://blog.csdn.net/zhu_free/article/details/48137375 -->
```
* `short.html`
```htmlmixed=
<p>Query text: </p>
<p style="color:orange;">{{ m_lastone.user_input_text }}</p>
<p>Detected intent: </p>
<p style="color:red;">{{ m_lastone.detected_intent }}</p>
<p>Detected intent confidence: </p>
<p>{{ m_lastone.detected_intent_confidence }}</p>
<p>Fulfillment text: </p>
<p style="color:blue;">{{ m_lastone.chatbot_output_text }}</p>
<p>Submit timestamp: </p>
<p>{{ m_lastone.timestamp }}</p>
<hr>
```
* `stat01/templates/base/base.html`
```htmlmixed=
<!DOCTYPE html>
<html lang="zh-Hant-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}{% endblock %}</title>
{% block link %}{% endblock %}
{% load staticfiles %}
<link href="{% static "_css/bootstrap.min.css" %}" rel="stylesheet" type="text/css" />
<link href="{% static "_css/stat.css" %}" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<style>
{% block style %}{% endblock %}
</style>
</head>
<body>
<div class="container-fluid">
{% block content %}
{% endblock %}
</div>
</body>
</html>
```
## 更新
```
python manage.py makemigrations
python manage.py migrate
```