Skip to content

Commit a4d1292

Browse files
galz10parthea
authored andcommitted
docs(samples): added webhook code snippet (#401)
* Samples: added webhook code snippet * added flask to requirments.txt * changed res to string * lint fix * lint fix * added space * Revised code * lint fix * Added comment Co-authored-by: Anthonios Partheniou <partheniou@google.com>
1 parent 84403c3 commit a4d1292

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

dialogflow/requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
google-cloud-dialogflow==2.8.1
2+
Flask==2.0.1

dialogflow/webhook.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Copyright 2021, Google LLC
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
#
6+
# http://www.apache.org/licenses/LICENSE-2.0
7+
#
8+
# Unless required by applicable law or agreed to in writing, software
9+
# distributed under the License is distributed on an "AS IS" BASIS,
10+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
# See the License for the specific language governing permissions and
12+
# limitations under the License.
13+
14+
# returns fullfillment response for dialogflow detect_intent call
15+
16+
# [START dialogflow_webhook]
17+
def handleWebhook(request):
18+
19+
req = request.get_json()
20+
21+
responseText = ""
22+
intent = req["queryResult"]["intent"]["displayName"]
23+
24+
if intent == "Default Welcome Intent":
25+
responseText = "Hello from a GCF Webhook"
26+
elif intent == "get-agent-name":
27+
responseText = "My name is Flowhook"
28+
else:
29+
responseText = f"There are no fulfillment responses defined for Intent {intent}"
30+
31+
# You can also use the google.cloud.dialogflowcx_v3.types.WebhookRequest protos instead of manually writing the json object
32+
res = {"fulfillmentMessages": [{"text": {"text": [responseText]}}]}
33+
34+
return res
35+
36+
37+
# [END dialogflow_webhook]

dialogflow/webhook_test.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import flask
2+
import pytest
3+
4+
from webhook import handleWebhook
5+
6+
# Create a fake 'app' for generating test request contexts.
7+
8+
request = {
9+
"queryResult": {
10+
"queryText": "hi",
11+
"intent": {
12+
"name": "projects/galstarter-316823/agent/intents/00c2877d-2440-447f-8dc1-045623a55bd4",
13+
"displayName": "Default Welcome Intent",
14+
},
15+
}
16+
}
17+
18+
19+
@pytest.fixture(scope="module")
20+
def app():
21+
return flask.Flask(__name__)
22+
23+
24+
def test_handleWebhook(app):
25+
with app.test_request_context(json=request):
26+
res = handleWebhook(flask.request)
27+
assert "Hello from a GCF Webhook" in str(res)

0 commit comments

Comments
 (0)