forked from dialogflow/fulfillment-weather-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
225 lines (174 loc) · 7.7 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# -*- coding:utf8 -*-
# !/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This is a sample for a weather fulfillment webhook for an Dialogflow agent
This is meant to be used with the sample weather agent for Dialogflow, located at
https://console.dialogflow.com/api-client/#/agent//prebuiltAgents/Weather
This sample uses the WWO Weather Forecast API and requires an WWO API key
Get a WWO API key here: https://developer.worldweatheronline.com/api/
"""
import json
from flask import Flask, request, make_response, jsonify
from forecast import Forecast, validate_params
app = Flask(__name__)
log = app.logger
@app.route('/', methods=['POST'])
def webhook():
"""This method handles the http requests for the Dialogflow webhook
This is meant to be used in conjunction with the weather Dialogflow agent
"""
req = request.get_json(silent=True, force=True)
try:
action = req.get('queryResult').get('action')
except AttributeError:
return 'json error'
if action == 'weather':
res = weather(req)
elif action == 'weather.activity':
res = weather_activity(req)
elif action == 'weather.condition':
res = weather_condition(req)
elif action == 'weather.outfit':
res = weather_outfit(req)
elif action == 'weather.temperature':
res = weather_temperature(req)
else:
log.error('Unexpected action.')
print('Action: ' + action)
print('Response: ' + res)
return make_response(jsonify({'fulfillmentText': res}))
def weather(req):
"""Returns a string containing text with a response to the user
with the weather forecast or a prompt for more information
Takes the city for the forecast and (optional) dates
uses the template responses found in weather_responses.py as templates
"""
parameters = req['queryResult']['parameters']
print('Dialogflow Parameters:')
print(json.dumps(parameters, indent=4))
# validate request parameters, return an error if there are issues
error, forecast_params = validate_params(parameters)
if error:
return error
# create a forecast object which retrieves the forecast from a external API
try:
forecast = Forecast(forecast_params)
# return an error if there is an error getting the forecast
except (ValueError, IOError) as error:
return error
# If the user requests a datetime period (a date/time range), get the
# response
if forecast.datetime_start and forecast.datetime_end:
response = forecast.get_datetime_period_response()
# If the user requests a specific datetime, get the response
elif forecast.datetime_start:
response = forecast.get_datetime_response()
# If the user doesn't request a date in the request get current conditions
else:
response = forecast.get_current_response()
return response
def weather_activity(req):
"""Returns a string containing text with a response to the user
with a indication if the activity provided is appropriate for the
current weather or a prompt for more information
Takes a city, activity and (optional) dates
uses the template responses found in weather_responses.py as templates
and the activities listed in weather_entities.py
"""
# validate request parameters, return an error if there are issues
error, forecast_params = validate_params(req['queryResult']['parameters'])
if error:
return error
# Check to make sure there is a activity, if not return an error
if not forecast_params['activity']:
return 'What activity were you thinking of doing?'
# create a forecast object which retrieves the forecast from a external API
try:
forecast = Forecast(forecast_params)
# return an error if there is an error getting the forecast
except (ValueError, IOError) as error:
return error
# get the response
return forecast.get_activity_response()
def weather_condition(req):
"""Returns a string containing a human-readable response to the user
with the probability of the provided weather condition occurring
or a prompt for more information
Takes a city, condition and (optional) dates
uses the template responses found in weather_responses.py as templates
and the conditions listed in weather_entities.py
"""
# validate request parameters, return an error if there are issues
error, forecast_params = validate_params(req['queryResult']['parameters'])
if error:
return error
# Check to make sure there is a activity, if not return an error
if not forecast_params['condition']:
return 'What weather condition would you like to check?'
# create a forecast object which retrieves the forecast from a external API
try:
forecast = Forecast(forecast_params)
# return an error if there is an error getting the forecast
except (ValueError, IOError) as error:
return error
# get the response
return forecast.get_condition_response()
def weather_outfit(req):
"""Returns a string containing text with a response to the user
with a indication if the outfit provided is appropriate for the
current weather or a prompt for more information
Takes a city, outfit and (optional) dates
uses the template responses found in weather_responses.py as templates
and the outfits listed in weather_entities.py
"""
# validate request parameters, return an error if there are issues
error, forecast_params = validate_params(req['queryResult']['parameters'])
if error:
return error
# Validate that there are the required parameters to retrieve a forecast
if not forecast_params['outfit']:
return 'What are you planning on wearing?'
# create a forecast object which retrieves the forecast from a external API
try:
forecast = Forecast(forecast_params)
# return an error if there is an error getting the forecast
except (ValueError, IOError) as error:
return error
return forecast.get_outfit_response()
def weather_temperature(req):
"""Returns a string containing text with a response to the user
with a indication if temperature provided is consisting with the
current weather or a prompt for more information
Takes a city, temperature and (optional) dates. Temperature ranges for
hot, cold, chilly and warm can be configured in config.py
uses the template responses found in weather_responses.py as templates
"""
parameters = req['queryResult']['parameters']
# validate request parameters, return an error if there are issues
error, forecast_params = validate_params(parameters)
if error:
return error
# If the user didn't specify a temperature, get the weather for them
if not forecast_params['temperature']:
return weather(req)
# create a forecast object which retrieves the forecast from a external API
try:
forecast = Forecast(forecast_params)
# return an error if there is an error getting the forecast
except (ValueError, IOError) as error:
return error
return forecast.get_temperature_response()
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')