Skip to content

Commit ccb4604

Browse files
committed
add webhook python script for dialogflow
1 parent b513f2c commit ccb4604

File tree

3 files changed

+107
-0
lines changed

3 files changed

+107
-0
lines changed
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Install Dependencies : pip install -r requirements.txt
2+
3+
run webhook script : python webhook.py
4+
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Flask==0.10.1
2+
future==0.16.0
3+
PyMySQL
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
# -*- coding:utf8 -*-
2+
# !/usr/bin/env python
3+
# Copyright 2017 Google Inc. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
from __future__ import print_function
18+
from future.standard_library import install_aliases
19+
install_aliases()
20+
21+
from urllib.parse import urlparse, urlencode
22+
from urllib.request import urlopen, Request
23+
from urllib.error import HTTPError
24+
25+
import json
26+
import os
27+
import pymysql
28+
29+
from flask import Flask
30+
from flask import request
31+
from flask import make_response
32+
33+
# Flask app should start in global layout
34+
app = Flask(__name__)
35+
36+
# 어떤 URL이 우리가 작성한 함수를 실행시키는지 알려줌. HTTP POST request에만 응답할 것을 명시함
37+
@app.route('/', methods=['POST'])
38+
def webhook():
39+
# incoming JSON data를 python dictionary 로 변환
40+
req = request.get_json(silent=True, force=True)
41+
42+
print("Request:")
43+
print(json.dumps(req, indent=4))
44+
45+
# webhook 실행할 결과 (user definded fuction)
46+
res = makeWebhookResult(req)
47+
48+
# python object 를 json 문자열로 변환
49+
res = json.dumps(res, indent=4)
50+
# print(res)
51+
# return avleues to a proper HTTP response object & header 추가
52+
r = make_response(res)
53+
r.headers['Content-Type'] = 'application/json'
54+
return r
55+
56+
def makeWebhookResult(req):
57+
if req.get("result").get("action") == "sayHello":
58+
speech = "webhook test result ok"
59+
else:
60+
try:
61+
conn = pymysql.connect(host='localhost', user='tutorial', password='tutorial', db='tutorial', charset='utf8')
62+
apartmentname = req.get("result").get("parameters").get("apartmentname")
63+
with conn.cursor() as curs:
64+
curs.execute("""select avg(price) as aprice from tutorial where name=%s""", ( str(apartmentname)))
65+
print(curs.rowcount)
66+
print(curs._last_executed)
67+
rows = curs.fetchall()
68+
if curs.rowcount == 0:
69+
speech = "최근 실거래가 정보가 없습니다"
70+
elif curs.rowcount == 1:
71+
for row in rows:
72+
aprice = row[0]
73+
speech = "최근 " + apartmentname + "아파트 실거래가는 "+ str(int(aprice)) + "만원 입니다"
74+
else:
75+
speech = "최근 실거래가 정보가 없습니다"
76+
except pymysql.InternalError as error:
77+
code, message = error.args
78+
print(code)
79+
print( message)
80+
except Exception as e:
81+
print('Make WebHook Result Error:' + str(e))
82+
83+
print("Response:")
84+
print(speech)
85+
86+
return {
87+
"speech": speech,
88+
"displayText": speech,
89+
# "data": data,
90+
# "contextOut": [],
91+
"source": "dialogflow-webhook-sample"
92+
}
93+
94+
95+
if __name__ == '__main__':
96+
port = int(os.getenv('PORT', 5000))
97+
98+
print("Starting app on port %d" % port)
99+
100+
app.run(debug=False, port=port, host='0.0.0.0')

0 commit comments

Comments
 (0)