SlideShare a Scribd company logo
1 of 8
Download to read offline
Integrating DialogFlow (API.ai) into
Qiscus SDK Chat Application
Just recently on October 10th, Google announced a change in name of API.AI into DialogFlow. There
are a couple of new features following this change. Regardless of what has been changed, in this
post we are going to share a simple way of how to integrate your agents that is created using
DialogFlow into any Qiscus SDK chat application.
As DialogFlow doesn't have a famous 'one-click integration' feature for Qiscus (yet), we need to
make a workaround to do so. Fortunately, DialogFlow provides some integration ways through its
SDK options, here in the image, you can see several programming languages that you can use for
your agent integration.
Image of DialogFlow SDK for integration
For our simplicity purpose, we are going to use our last article on how to create a simple chat
application using QiscusSDK and how to integrate a simple echo bot into it as prior requirement to
this post. You can find the codes here. Since it uses Python as the webhook, in this article we are
going to use DialogFlow SDK for Python as well called apiai (this might changes later as the effect
of name change).
Another thing to note is that we assume you already have an agent or two created in DialogFlow, if
not please refer to the basic tuts to create one.
1. Add DialogFlow SDK Python Package
Alright, let's get started! First thing first, let's add DialogFlow SDK python package (apiai) into our
project, come on open setup.py file, and add it,
from setuptools import setup, find_packages
setup(
name='simplebot',
version='1.0',
long_description=__doc__,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'apiai',
'flask',
'requests'
],
)
and let's import that package into our simplebot/views.py file then instantiate new object
from this package,
import apiai
import json
import requests
from flask import render_template, request
from simplebot import app
app_id = "YOUR_APP_ID"
secret_key = "YOUR_SECRET_KEY"
sender_email = "YOUR_BOT_EMAIL"
bot_name = "YOUR_BOT_NAME"
qiscus_sdk_url = "https://{}.qiscus.com".format(app_id)
client_access_token = "YOUR_DIALOGFLOW_CLIENT_ACCESS_TOKEN"
ai = apiai.ApiAI(client_access_token)
...
.
Notice in the code above, we need client_access_token to initiate new object from the
package. So please make sure you already got this token from your agent DialogFlow console
dashboard and assign it to the client_access_token, you may want to see this image to locate
where it is.
image of console
2. Incoming Message and Agent Response
After you got this package set, let's implement it in our index() function. First we will need to get
query from Qiscus chat app to be passed to the DialogFlow agent before we send it to get the
response from agent.
...
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
payload = request.get_json().get('payload')
room_id = payload.get("room").get("id")
message = payload.get("message").get("text")
# let's prepare the incoming message (query) we want
to send to dialogflow agent
conv = ai.text_request()
conv.session_id =
"ADD_YOUR_UNIQUE_SESSION_ID(ANY_SESSION_ID_WOULD_WORK)"
conv.query = message
# and let's get the response from dialogflow agent
response = conv.getresponse()
response_json =
json.loads(response.read().decode('utf-8'))
response_messages =
response_json.get("result").get("fulfillment").get("messages")
post_url =
"{}/api/v2/rest/post_comment".format(qiscus_sdk_url)
headers = {"QISCUS_SDK_SECRET": secret_key}
data = {
"sender_email": sender_email,
"room_id": room_id,
"message": message,
"type": "text",
"payload": {}
}
req = requests.post(post_url, headers=headers,
params=data)
...
What we need to do next is just to send back any response we got from agent to the Qiscus chat
app. This can be anything: plain text or any additional payload. So, before we return it back, we need
to know the structure of payload that is returned by our agent at DialogFlow, please have a look at
JSON code below, this JSON code is the payload that is returned from our agent in DialogFlow.
{
"id": "354eaf3c-c40e-42e4-acf6-fc2ef0e71799",
"timestamp": "2017-10-26T08:11:58.239Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "yo",
"action": "hi",
"actionIncomplete": false,
"parameters": {},
"contexts": [],
"metadata": {
"intentId": "fe8dbb22-43bf-4cb4-b634-48c3a2af98ae",
"webhookUsed": "false",
"webhookForSlotFillingUsed": "false",
"intentName": "hi"
},
"fulfillment": {
"speech": "Hi! How are you doing?",
"messages": [
{
"type": 0,
"id": "948f5dad-550c-4fa1-93ba-3819d8e42fbb",
"speech": "Hi! How are you doing?"
}
]
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success"
},
"sessionId": "d70073ae-0cdb-4bc4-b7d9-d8d0b16b98af"
}
From JSON code above, there is a fulfillment field. It has additional children fields that are
actual responses from our agent which we are interested in.
Also read: "Making your Apps “Chatable”"
Notice the messages field? its value is a list. So we may assume our agent could return one or
more messages when we make a request to DialogFlow. This could be another text or additional
custom payload, such as payload for button or card. However, to simplify this process, let's handle
text message only.
Ok, let's modify our index() function in views.py file again.
...
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
payload = request.get_json().get('payload')
room_id = payload.get("room").get("id")
message = payload.get("message").get("text")
# let's prepare the incoming message (query) we want
to send to dialogflow agent
conv = ai.text_request()
conv.session_id =
"ADD_YOUR_UNIQUE_SESSION_ID(ANY_SESSION_ID_WOULD_WORK)"
conv.query = message
# and let's get the response from dialogflow agent
response = conv.getresponse()
response_json =
json.loads(response.read().decode('utf-8'))
response_messages =
response_json.get("result").get("fulfillment").get("messages")
post_url =
"{}/api/v2/rest/post_comment".format(qiscus_sdk_url)
headers = {"QISCUS_SDK_SECRET": secret_key}
for msg in response_messages:
data = {
"sender_email": sender_email,
"room_id": room_id,
"message": msg.get("speech"),
"type": "text",
"payload": {}
}
try:
requests.post(post_url, headers=headers,
params=data)
except requests.exceptions.RequestException as e:
print(e)
return "Something went wrong!", 401
return "OK", 200
else:
return render_template('index.html', appId=app_d,
senderEmail=sender_email)
...
save and let's run our webhook, and you may open http://locahost:5000 in your browser.
$ make run
3. Webhook
Since we've been developing this integration locally, Qiscus SDK won't recognise our webhook even
though we are trying to add our local webhook address to the Qiscus SDK. So to help making our
webhook open to the internet, we are going to use ngrok and add the generated temporary
subdomain addresses into our Qiscus SDK, please refer to this for ngrok.
After you do that, please try to have a chat again through generated subdomain address in your
browser. Voila, you got a reply from your agent in DialogFlow!
Accompanying codes can be found at https://github.com/qiscus/qiscus-dialogflow. You can also
experience directly at https://qiscusdialog.herokuapp.com/.
Closing
To sum up, this article is only focusing on how we integrate our agent that is created in DialogFlow
which returns plain text only. In order to leverage your agent capability, you may want to add
additional custom payload as additional fulfillment response. For example you may want to return
message that contains image and buttons from DialogFlow. You can refer to Qiscus docs for any type
of comments that is supported by Qiscus as well as how to add custom payload in DialogFlow for
more information.

More Related Content

What's hot

RESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP FrameworkRESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP FrameworkBo-Yi Wu
 
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & more
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & morePower your apps with Gmail, Google Drive, Calendar, Sheets, Slides & more
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & morewesley chun
 
Parse: A Mobile Backend as a Service (MBaaS)
Parse: A Mobile Backend as a Service (MBaaS)Parse: A Mobile Backend as a Service (MBaaS)
Parse: A Mobile Backend as a Service (MBaaS)Ville Seppänen
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTim Cull
 
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기lanslote
 
The Big Picture and How to Get Started
The Big Picture and How to Get StartedThe Big Picture and How to Get Started
The Big Picture and How to Get Startedguest1af57e
 
Apache Aries Blog Sample
Apache Aries Blog SampleApache Aries Blog Sample
Apache Aries Blog SampleSkills Matter
 
The RESTful Soa Datagrid with Oracle
The RESTful Soa Datagrid with OracleThe RESTful Soa Datagrid with Oracle
The RESTful Soa Datagrid with OracleEmiliano Pecis
 
Generating cross platform .NET based azure IoTdevice
Generating cross platform .NET based azure IoTdeviceGenerating cross platform .NET based azure IoTdevice
Generating cross platform .NET based azure IoTdeviceAlon Fliess
 
Building Android apps with Parse
Building Android apps with ParseBuilding Android apps with Parse
Building Android apps with ParseDroidConTLV
 
DF12 - Process Orchestration using Streaming API and Heroku
DF12 - Process Orchestration using Streaming API and HerokuDF12 - Process Orchestration using Streaming API and Heroku
DF12 - Process Orchestration using Streaming API and Herokuafawcett
 
TDC2016SP - Trilha Android
TDC2016SP - Trilha AndroidTDC2016SP - Trilha Android
TDC2016SP - Trilha Androidtdc-globalcode
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Rob Windsor
 
google drive and the google drive sdk
google drive and the google drive sdkgoogle drive and the google drive sdk
google drive and the google drive sdkfirenze-gtug
 
Html5 tutorial
Html5 tutorialHtml5 tutorial
Html5 tutorialmadhavforu
 
SharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote AuthenticationSharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote AuthenticationAdil Ansari
 
Search APIs & Universal Links
Search APIs & Universal LinksSearch APIs & Universal Links
Search APIs & Universal LinksYusuke Kita
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklum Ukraine
 
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.Eric Shupps
 

What's hot (20)

RESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP FrameworkRESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP Framework
 
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & more
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & morePower your apps with Gmail, Google Drive, Calendar, Sheets, Slides & more
Power your apps with Gmail, Google Drive, Calendar, Sheets, Slides & more
 
Parse: A Mobile Backend as a Service (MBaaS)
Parse: A Mobile Backend as a Service (MBaaS)Parse: A Mobile Backend as a Service (MBaaS)
Parse: A Mobile Backend as a Service (MBaaS)
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applications
 
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
 
The Big Picture and How to Get Started
The Big Picture and How to Get StartedThe Big Picture and How to Get Started
The Big Picture and How to Get Started
 
Apache Aries Blog Sample
Apache Aries Blog SampleApache Aries Blog Sample
Apache Aries Blog Sample
 
The RESTful Soa Datagrid with Oracle
The RESTful Soa Datagrid with OracleThe RESTful Soa Datagrid with Oracle
The RESTful Soa Datagrid with Oracle
 
Generating cross platform .NET based azure IoTdevice
Generating cross platform .NET based azure IoTdeviceGenerating cross platform .NET based azure IoTdevice
Generating cross platform .NET based azure IoTdevice
 
Building Android apps with Parse
Building Android apps with ParseBuilding Android apps with Parse
Building Android apps with Parse
 
Parse Advanced
Parse AdvancedParse Advanced
Parse Advanced
 
DF12 - Process Orchestration using Streaming API and Heroku
DF12 - Process Orchestration using Streaming API and HerokuDF12 - Process Orchestration using Streaming API and Heroku
DF12 - Process Orchestration using Streaming API and Heroku
 
TDC2016SP - Trilha Android
TDC2016SP - Trilha AndroidTDC2016SP - Trilha Android
TDC2016SP - Trilha Android
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
 
google drive and the google drive sdk
google drive and the google drive sdkgoogle drive and the google drive sdk
google drive and the google drive sdk
 
Html5 tutorial
Html5 tutorialHtml5 tutorial
Html5 tutorial
 
SharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote AuthenticationSharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote Authentication
 
Search APIs & Universal Links
Search APIs & Universal LinksSearch APIs & Universal Links
Search APIs & Universal Links
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
 
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
 

Similar to Integrating dialog flow (api.ai) into qiscus sdk chat application

AI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You TypedAI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You TypedMarvin Heng
 
Exploring MORE Google (Cloud) APIs with Python
Exploring MORE Google (Cloud) APIs with PythonExploring MORE Google (Cloud) APIs with Python
Exploring MORE Google (Cloud) APIs with Pythonwesley chun
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorialKaty Slemon
 
Cloud Endpoints _Polymer_ Material design by Martin Görner
Cloud Endpoints_Polymer_Material design by Martin GörnerCloud Endpoints_Polymer_Material design by Martin Görner
Cloud Endpoints _Polymer_ Material design by Martin GörnerEuropean Innovation Academy
 
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resourcesJavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resourcesCorley S.r.l.
 
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech TalkContract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech TalkRed Hat Developers
 
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013Kiril Iliev
 
Into The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sInto The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sOrtus Solutions, Corp
 
[2019 south bay meetup] Building more contextual message with Block Kit
[2019 south bay meetup] Building more contextual message with Block Kit[2019 south bay meetup] Building more contextual message with Block Kit
[2019 south bay meetup] Building more contextual message with Block KitTomomi Imura
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinGavin Pickin
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in detailsMax Klymyshyn
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchKaty Slemon
 
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on AndroidMobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on AndroidAlberto Ruibal
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code維佋 唐
 
Let's play with adf 3.0
Let's play with adf 3.0Let's play with adf 3.0
Let's play with adf 3.0Eugenio Romano
 
How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...Appear
 
Micro app-framework - NodeLive Boston
Micro app-framework - NodeLive BostonMicro app-framework - NodeLive Boston
Micro app-framework - NodeLive BostonMichael Dawson
 

Similar to Integrating dialog flow (api.ai) into qiscus sdk chat application (20)

AI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You TypedAI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You Typed
 
Exploring MORE Google (Cloud) APIs with Python
Exploring MORE Google (Cloud) APIs with PythonExploring MORE Google (Cloud) APIs with Python
Exploring MORE Google (Cloud) APIs with Python
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorial
 
Cloud Endpoints _Polymer_ Material design by Martin Görner
Cloud Endpoints_Polymer_Material design by Martin GörnerCloud Endpoints_Polymer_Material design by Martin Görner
Cloud Endpoints _Polymer_ Material design by Martin Görner
 
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resourcesJavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
 
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech TalkContract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
 
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
 
Into The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api'sInto The Box | Alexa and ColdBox Api's
Into The Box | Alexa and ColdBox Api's
 
[2019 south bay meetup] Building more contextual message with Block Kit
[2019 south bay meetup] Building more contextual message with Block Kit[2019 south bay meetup] Building more contextual message with Block Kit
[2019 south bay meetup] Building more contextual message with Block Kit
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratch
 
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on AndroidMobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
2012: ql.io and Node.js
2012: ql.io and Node.js2012: ql.io and Node.js
2012: ql.io and Node.js
 
Let's play with adf 3.0
Let's play with adf 3.0Let's play with adf 3.0
Let's play with adf 3.0
 
How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...
 
Micro app-framework - NodeLive Boston
Micro app-framework - NodeLive BostonMicro app-framework - NodeLive Boston
Micro app-framework - NodeLive Boston
 
Micro app-framework
Micro app-frameworkMicro app-framework
Micro app-framework
 
Life on Clouds: a forensics overview
Life on Clouds: a forensics overviewLife on Clouds: a forensics overview
Life on Clouds: a forensics overview
 

Recently uploaded

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 

Recently uploaded (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 

Integrating dialog flow (api.ai) into qiscus sdk chat application

  • 1. Integrating DialogFlow (API.ai) into Qiscus SDK Chat Application Just recently on October 10th, Google announced a change in name of API.AI into DialogFlow. There are a couple of new features following this change. Regardless of what has been changed, in this post we are going to share a simple way of how to integrate your agents that is created using DialogFlow into any Qiscus SDK chat application. As DialogFlow doesn't have a famous 'one-click integration' feature for Qiscus (yet), we need to make a workaround to do so. Fortunately, DialogFlow provides some integration ways through its SDK options, here in the image, you can see several programming languages that you can use for your agent integration.
  • 2. Image of DialogFlow SDK for integration For our simplicity purpose, we are going to use our last article on how to create a simple chat application using QiscusSDK and how to integrate a simple echo bot into it as prior requirement to this post. You can find the codes here. Since it uses Python as the webhook, in this article we are going to use DialogFlow SDK for Python as well called apiai (this might changes later as the effect of name change). Another thing to note is that we assume you already have an agent or two created in DialogFlow, if not please refer to the basic tuts to create one. 1. Add DialogFlow SDK Python Package Alright, let's get started! First thing first, let's add DialogFlow SDK python package (apiai) into our project, come on open setup.py file, and add it, from setuptools import setup, find_packages setup( name='simplebot', version='1.0', long_description=__doc__, packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'apiai',
  • 3. 'flask', 'requests' ], ) and let's import that package into our simplebot/views.py file then instantiate new object from this package, import apiai import json import requests from flask import render_template, request from simplebot import app app_id = "YOUR_APP_ID" secret_key = "YOUR_SECRET_KEY" sender_email = "YOUR_BOT_EMAIL" bot_name = "YOUR_BOT_NAME" qiscus_sdk_url = "https://{}.qiscus.com".format(app_id) client_access_token = "YOUR_DIALOGFLOW_CLIENT_ACCESS_TOKEN" ai = apiai.ApiAI(client_access_token) ... . Notice in the code above, we need client_access_token to initiate new object from the package. So please make sure you already got this token from your agent DialogFlow console dashboard and assign it to the client_access_token, you may want to see this image to locate where it is.
  • 4. image of console 2. Incoming Message and Agent Response After you got this package set, let's implement it in our index() function. First we will need to get query from Qiscus chat app to be passed to the DialogFlow agent before we send it to get the response from agent. ... @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': payload = request.get_json().get('payload') room_id = payload.get("room").get("id") message = payload.get("message").get("text") # let's prepare the incoming message (query) we want to send to dialogflow agent conv = ai.text_request() conv.session_id = "ADD_YOUR_UNIQUE_SESSION_ID(ANY_SESSION_ID_WOULD_WORK)" conv.query = message # and let's get the response from dialogflow agent response = conv.getresponse() response_json = json.loads(response.read().decode('utf-8'))
  • 5. response_messages = response_json.get("result").get("fulfillment").get("messages") post_url = "{}/api/v2/rest/post_comment".format(qiscus_sdk_url) headers = {"QISCUS_SDK_SECRET": secret_key} data = { "sender_email": sender_email, "room_id": room_id, "message": message, "type": "text", "payload": {} } req = requests.post(post_url, headers=headers, params=data) ... What we need to do next is just to send back any response we got from agent to the Qiscus chat app. This can be anything: plain text or any additional payload. So, before we return it back, we need to know the structure of payload that is returned by our agent at DialogFlow, please have a look at JSON code below, this JSON code is the payload that is returned from our agent in DialogFlow. { "id": "354eaf3c-c40e-42e4-acf6-fc2ef0e71799", "timestamp": "2017-10-26T08:11:58.239Z", "lang": "en", "result": { "source": "agent", "resolvedQuery": "yo", "action": "hi", "actionIncomplete": false, "parameters": {}, "contexts": [], "metadata": { "intentId": "fe8dbb22-43bf-4cb4-b634-48c3a2af98ae", "webhookUsed": "false", "webhookForSlotFillingUsed": "false", "intentName": "hi" }, "fulfillment": { "speech": "Hi! How are you doing?", "messages": [ {
  • 6. "type": 0, "id": "948f5dad-550c-4fa1-93ba-3819d8e42fbb", "speech": "Hi! How are you doing?" } ] }, "score": 1 }, "status": { "code": 200, "errorType": "success" }, "sessionId": "d70073ae-0cdb-4bc4-b7d9-d8d0b16b98af" } From JSON code above, there is a fulfillment field. It has additional children fields that are actual responses from our agent which we are interested in. Also read: "Making your Apps “Chatable”" Notice the messages field? its value is a list. So we may assume our agent could return one or more messages when we make a request to DialogFlow. This could be another text or additional custom payload, such as payload for button or card. However, to simplify this process, let's handle text message only. Ok, let's modify our index() function in views.py file again. ... @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': payload = request.get_json().get('payload') room_id = payload.get("room").get("id") message = payload.get("message").get("text") # let's prepare the incoming message (query) we want to send to dialogflow agent conv = ai.text_request() conv.session_id = "ADD_YOUR_UNIQUE_SESSION_ID(ANY_SESSION_ID_WOULD_WORK)" conv.query = message # and let's get the response from dialogflow agent response = conv.getresponse() response_json =
  • 7. json.loads(response.read().decode('utf-8')) response_messages = response_json.get("result").get("fulfillment").get("messages") post_url = "{}/api/v2/rest/post_comment".format(qiscus_sdk_url) headers = {"QISCUS_SDK_SECRET": secret_key} for msg in response_messages: data = { "sender_email": sender_email, "room_id": room_id, "message": msg.get("speech"), "type": "text", "payload": {} } try: requests.post(post_url, headers=headers, params=data) except requests.exceptions.RequestException as e: print(e) return "Something went wrong!", 401 return "OK", 200 else: return render_template('index.html', appId=app_d, senderEmail=sender_email) ... save and let's run our webhook, and you may open http://locahost:5000 in your browser. $ make run
  • 8. 3. Webhook Since we've been developing this integration locally, Qiscus SDK won't recognise our webhook even though we are trying to add our local webhook address to the Qiscus SDK. So to help making our webhook open to the internet, we are going to use ngrok and add the generated temporary subdomain addresses into our Qiscus SDK, please refer to this for ngrok. After you do that, please try to have a chat again through generated subdomain address in your browser. Voila, you got a reply from your agent in DialogFlow! Accompanying codes can be found at https://github.com/qiscus/qiscus-dialogflow. You can also experience directly at https://qiscusdialog.herokuapp.com/. Closing To sum up, this article is only focusing on how we integrate our agent that is created in DialogFlow which returns plain text only. In order to leverage your agent capability, you may want to add additional custom payload as additional fulfillment response. For example you may want to return message that contains image and buttons from DialogFlow. You can refer to Qiscus docs for any type of comments that is supported by Qiscus as well as how to add custom payload in DialogFlow for more information.