This repository was archived by the owner on May 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathlambda_function.py
More file actions
400 lines (309 loc) · 15.2 KB
/
lambda_function.py
File metadata and controls
400 lines (309 loc) · 15.2 KB
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# -*- coding: utf-8 -*-
# City Guide: A sample Alexa Skill Lambda function
# This function shows how you can manage data in objects and arrays,
# choose a random recommendation,
# call an external API and speak the result,
# handle YES/NO intents with session attributes,
# and return text data on a card.
import logging
import random
import gettext
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_core.dispatch_components import (
AbstractRequestHandler, AbstractExceptionHandler,
AbstractRequestInterceptor)
from ask_sdk_core.utils import is_intent_name, is_request_type
from ask_sdk_model import Response
from ask_sdk_model.ui import SimpleCard
from alexa import data, util
# Skill Builder object
sb = SkillBuilder()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Request Handler classes
class LaunchRequestHandler(AbstractRequestHandler):
"""Handler for skill launch."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_request_type("LaunchRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In LaunchRequestHandler")
_ = handler_input.attributes_manager.request_attributes["_"]
# logger.info(_("This is an untranslated message"))
speech = _(data.WELCOME)
speech += " " + _(data.HELP)
handler_input.response_builder.speak(speech)
handler_input.response_builder.ask(_(
data.GENERIC_REPROMPT))
return handler_input.response_builder.response
class AboutIntentHandler(AbstractRequestHandler):
"""Handler for about intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_intent_name("AboutIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In AboutIntentHandler")
_ = handler_input.attributes_manager.request_attributes["_"]
handler_input.response_builder.speak(_(data.ABOUT))
return handler_input.response_builder.response
class CoffeeIntentHandler(AbstractRequestHandler):
"""Handler for coffee intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_intent_name("CoffeeIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In CoffeeIntentHandler")
attribute_manager = handler_input.attributes_manager
session_attr = attribute_manager.session_attributes
restaurant = random.choice(util.get_restaurants_by_meal(
data.CITY_DATA, "coffee"))
session_attr["restaurant"] = restaurant["name"]
speech = ("For a great coffee shop, I recommend {}. Would you "
"like to hear more?").format(restaurant["name"])
handler_input.response_builder.speak(speech).ask(speech)
return handler_input.response_builder.response
class BreakfastIntentHandler(AbstractRequestHandler):
"""Handler for breakfast intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_intent_name("BreakfastIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In BreakfastIntentHandler")
attribute_manager = handler_input.attributes_manager
session_attr = attribute_manager.session_attributes
restaurant = random.choice(util.get_restaurants_by_meal(
data.CITY_DATA, "breakfast"))
session_attr["restaurant"] = restaurant["name"]
speech = ("For breakfast, try this. {}. Would you "
"like to hear more?").format(restaurant["name"])
handler_input.response_builder.speak(speech).ask(speech)
return handler_input.response_builder.response
class LunchIntentHandler(AbstractRequestHandler):
"""Handler for lunch intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_intent_name("LunchIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In LunchIntentHandler")
attribute_manager = handler_input.attributes_manager
session_attr = attribute_manager.session_attributes
restaurant = random.choice(util.get_restaurants_by_meal(
data.CITY_DATA, "lunch"))
session_attr["restaurant"] = restaurant["name"]
speech = ("Lunch time! Here is a good spot. {}. Would you "
"like to hear more?").format(restaurant["name"])
handler_input.response_builder.speak(speech).ask(speech)
return handler_input.response_builder.response
class DinnerIntentHandler(AbstractRequestHandler):
"""Handler for dinner intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_intent_name("DinnerIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In DinnerIntentHandler")
attribute_manager = handler_input.attributes_manager
session_attr = attribute_manager.session_attributes
restaurant = random.choice(util.get_restaurants_by_meal(
data.CITY_DATA, "dinner"))
session_attr["restaurant"] = restaurant["name"]
speech = ("Enjoy dinner at, {}. Would you "
"like to hear more?").format(restaurant["name"])
handler_input.response_builder.speak(speech).ask(speech)
return handler_input.response_builder.response
class YesMoreInfoIntentHandler(AbstractRequestHandler):
"""Handler for yes to get more info intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
session_attr = handler_input.attributes_manager.session_attributes
return (is_intent_name("AMAZON.YesIntent")(handler_input) and
"restaurant" in session_attr)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In YesMoreInfoIntentHandler")
attribute_manager = handler_input.attributes_manager
session_attr = attribute_manager.session_attributes
_ = attribute_manager.request_attributes["_"]
restaurant_name = session_attr["restaurant"]
restaurant_details = util.get_restaurants_by_name(
data.CITY_DATA, restaurant_name)
speech = ("{} is located at {}, the phone number is {}, and the "
"description is, {}. I have sent these details to the "
"Alexa App on your phone. Enjoy your meal! "
"<say-as interpret-as='interjection'>bon appetit</say-as>"
.format(restaurant_details["name"],
restaurant_details["address"],
restaurant_details["phone"],
restaurant_details["description"]))
card_info = "{}\n{}\n{}, {}, {}\nphone: {}\n".format(
restaurant_details["name"], restaurant_details["address"],
data.CITY_DATA["city"], data.CITY_DATA["state"],
data.CITY_DATA["postcode"], restaurant_details["phone"])
handler_input.response_builder.speak(speech).set_card(
SimpleCard(
title=_(data.SKILL_NAME),
content=card_info)).set_should_end_session(True)
return handler_input.response_builder.response
class NoMoreInfoIntentHandler(AbstractRequestHandler):
"""Handler for no to get no more info intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
session_attr = handler_input.attributes_manager.session_attributes
return (is_intent_name("AMAZON.NoIntent")(handler_input) and
"restaurant" in session_attr)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In NoMoreInfoIntentHandler")
speech = ("Ok. Enjoy your meal! "
"<say-as interpret-as='interjection'>bon appetit</say-as>")
handler_input.response_builder.speak(speech).set_should_end_session(
True)
return handler_input.response_builder.response
class AttractionIntentHandler(AbstractRequestHandler):
"""Handler for attraction intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_intent_name("AttractionIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In AttractionIntentHandler")
distance = util.get_resolved_value(
handler_input.request_envelope.request, "distance")
if distance is None:
distance = 200
attraction = random.choice(util.get_attractions_by_distance(
data.CITY_DATA, distance))
speech = "Try {}, which is {}. {}. Have fun!!".format(
attraction["name"],
"right downtown" if attraction["distance"] == "0"
else "{} miles away".format(attraction["distance"]),
attraction["description"])
handler_input.response_builder.speak(speech).set_should_end_session(
True)
return handler_input.response_builder.response
class GoOutIntentHandler(AbstractRequestHandler):
"""Handler for go out intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_intent_name("GoOutIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In GoOutIntentHandler")
local_time, current_temp, current_condition = util.get_weather(
data.CITY_DATA, data.MY_API)
speech = "It is {} and the weather in {} is {} and {}.".format(
local_time, data.CITY_DATA["city"], current_temp,
current_condition)
handler_input.response_builder.speak(speech)
return handler_input.response_builder.response
class SessionEndedRequestHandler(AbstractRequestHandler):
"""Handler for skill session end."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_request_type("SessionEndedRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In SessionEndedRequestHandler")
logger.info("Session ended with reason: {}".format(
handler_input.request_envelope.request.reason))
return handler_input.response_builder.response
class HelpIntentHandler(AbstractRequestHandler):
"""Handler for help intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_intent_name("AMAZON.HelpIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In HelpIntentHandler")
_ = handler_input.attributes_manager.request_attributes["_"]
handler_input.response_builder.speak(_(
data.HELP)).ask(_(data.HELP))
return handler_input.response_builder.response
class ExitIntentHandler(AbstractRequestHandler):
"""Single Handler for Cancel, Stop intents."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return (is_intent_name("AMAZON.CancelIntent")(handler_input) or
is_intent_name("AMAZON.StopIntent")(handler_input))
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In ExitIntentHandler")
_ = handler_input.attributes_manager.request_attributes["_"]
handler_input.response_builder.speak(_(
data.STOP)).set_should_end_session(True)
return handler_input.response_builder.response
class FallbackIntentHandler(AbstractRequestHandler):
"""Handler for handling fallback intent or Yes/No without
restaurant info intent.
2018-May-01: AMAZON.FallackIntent is only currently available in
en-US locale. This handler will not be triggered except in that
locale, so it can be safely deployed for any locale."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
session_attr = handler_input.attributes_manager.session_attributes
return (is_intent_name("AMAZON.FallbackIntent")(handler_input) or
("restaurant" not in session_attr and (
is_intent_name("AMAZON.YesIntent")(handler_input) or
is_intent_name("AMAZON.NoIntent")(handler_input))
))
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In FallbackIntentHandler")
_ = handler_input.attributes_manager.request_attributes["_"]
handler_input.response_builder.speak(_(
data.FALLBACK).format(data.SKILL_NAME)).ask(_(
data.FALLBACK).format(data.SKILL_NAME))
return handler_input.response_builder.response
# Exception Handler classes
class CatchAllExceptionHandler(AbstractExceptionHandler):
"""Catch All Exception handler.
This handler catches all kinds of exceptions and prints
the stack trace on AWS Cloudwatch with the request envelope."""
def can_handle(self, handler_input, exception):
# type: (HandlerInput, Exception) -> bool
return True
def handle(self, handler_input, exception):
# type: (HandlerInput, Exception) -> Response
logger.error(exception, exc_info=True)
logger.info("Original request was {}".format(
handler_input.request_envelope.request))
speech = "Sorry, there was some problem. Please try again!!"
handler_input.response_builder.speak(speech).ask(speech)
return handler_input.response_builder.response
class LocalizationInterceptor(AbstractRequestInterceptor):
"""Add function to request attributes, that can load locale specific data."""
def process(self, handler_input):
# type: (HandlerInput) -> None
locale = handler_input.request_envelope.request.locale
logger.info("Locale is {}".format(locale))
i18n = gettext.translation(
'base', localedir='locales', languages=[locale], fallback=True)
handler_input.attributes_manager.request_attributes[
"_"] = i18n.gettext
# Add all request handlers to the skill.
sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(AboutIntentHandler())
sb.add_request_handler(CoffeeIntentHandler())
sb.add_request_handler(BreakfastIntentHandler())
sb.add_request_handler(LunchIntentHandler())
sb.add_request_handler(DinnerIntentHandler())
sb.add_request_handler(YesMoreInfoIntentHandler())
sb.add_request_handler(NoMoreInfoIntentHandler())
sb.add_request_handler(AttractionIntentHandler())
sb.add_request_handler(GoOutIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(FallbackIntentHandler())
sb.add_request_handler(ExitIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
# Add exception handler to the skill.
sb.add_exception_handler(CatchAllExceptionHandler())
# Add locale interceptor to the skill.
sb.add_global_request_interceptor(LocalizationInterceptor())
# Expose the lambda handler to register in AWS Lambda.
lambda_handler = sb.lambda_handler()