説明なし

lambda_function.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. # -*- coding: utf-8 -*-
  2. # This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK for Python.
  3. # Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management,
  4. # session persistence, api calls, and more.
  5. # This sample is built using the handler classes approach in skill builder.
  6. import logging
  7. import requests
  8. import ask_sdk_core.utils as ask_utils
  9. #from ask_sdk_s3.adapter import S3Adapter
  10. #s3_adapter = S3Adapter(bucket_name=os.environ["S3_PERSISTENCE_BUCKET"])
  11. from ask_sdk_core.skill_builder import SkillBuilder
  12. from ask_sdk_core.dispatch_components import AbstractRequestHandler
  13. from ask_sdk_core.dispatch_components import AbstractExceptionHandler
  14. from ask_sdk_core.handler_input import HandlerInput
  15. from ask_sdk_model import Response
  16. logger = logging.getLogger(__name__)
  17. logger.setLevel(logging.INFO)
  18. ordernum = 0
  19. class LaunchRequestHandler(AbstractRequestHandler):
  20. """Handler for Skill Launch."""
  21. def can_handle(self, handler_input):
  22. # type: (HandlerInput) -> bool
  23. return ask_utils.is_request_type("LaunchRequest")(handler_input)
  24. def handle(self, handler_input):
  25. # type: (HandlerInput) -> Response
  26. speak_output = "What would you like to order?"
  27. return (
  28. handler_input.response_builder
  29. .speak(speak_output)
  30. .ask(speak_output)
  31. .response
  32. )
  33. class HelloWorldIntentHandler(AbstractRequestHandler):
  34. """Handler for Hello World Intent."""
  35. def can_handle(self, handler_input):
  36. # type: (HandlerInput) -> bool
  37. return ask_utils.is_intent_name("HelloWorldIntent")(handler_input)
  38. def handle(self, handler_input):
  39. # type: (HandlerInput) -> Response
  40. speak_output = "Hello World!"
  41. return (
  42. handler_input.response_builder
  43. .speak(speak_output)
  44. # .ask("add a reprompt if you want to keep the session open for the user to respond")
  45. .response
  46. )
  47. class LinguiniOrderFoodIntentHandler(AbstractRequestHandler):
  48. """Handler for Linguini Order Food Intent."""
  49. global ordernum
  50. ordernum = ordernum + 1
  51. global food_dict
  52. global order
  53. def can_handle(self, handler_input):
  54. # type: (HandlerInput) -> bool
  55. return ask_utils.is_intent_name("LinguiniOrderFoodIntent")(handler_input)
  56. def handle(self, handler_input):
  57. # type: (HandlerInput) -> Response
  58. slots = handler_input.request_envelope.request.intent.slots
  59. food_type = slots["food_type"].value
  60. food_category = slots["food_category"].value
  61. speak_output = f"One {food_type} {food_category} added to your order. What else would you like to add?"
  62. food = f"{food_type} {food_category}"
  63. if food == "gardenia pasta":
  64. orderstr = 'orden' + str(ordernum)
  65. order[orderstr] = 2
  66. else:
  67. orderstr = 'orden' + str(ordernum)
  68. order[ordernum] = 1
  69. if food in order_names:
  70. order_names[food] += 1
  71. else:
  72. order_names[food] = 1
  73. handler_input.response_builder.speak(speak_output).ask("What else would you like to add?")
  74. return (handler_input.response_builder.response)
  75. class LinguiniOrderDrinkIntentHandler(AbstractRequestHandler):
  76. """Handler for Linguini Order Drink Intent."""
  77. global ordernum
  78. ordernum = ordernum + 1
  79. global drink_dict
  80. global order
  81. global order_names
  82. def can_handle(self, handler_input):
  83. # type: (HandlerInput) -> bool
  84. return ask_utils.is_intent_name("LinguiniOrderDrinkIntent")(handler_input)
  85. def handle(self, handler_input):
  86. # type: (HandlerInput) -> Response
  87. slots = handler_input.request_envelope.request.intent.slots
  88. drink_type = slots["drink_type"].value
  89. speak_output = f"One {drink_type} added to your order. What else would you like to add?"
  90. if drink_type == "water":
  91. orderstr = 'orden' + str(ordernum)
  92. order[orderstr] = 10
  93. else:
  94. orderstr = 'orden' + str(ordernum)
  95. order[orderstr] = 9
  96. if drink_type in order_names:
  97. order_names[drink_type] += 1
  98. else:
  99. order_names[drink_type] = 1
  100. handler_input.response_builder.speak(speak_output).ask("What else would you like to add?")
  101. return (handler_input.response_builder.response)
  102. class HelpIntentHandler(AbstractRequestHandler):
  103. """Handler for Help Intent."""
  104. def can_handle(self, handler_input):
  105. # type: (HandlerInput) -> bool
  106. return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input)
  107. def handle(self, handler_input):
  108. # type: (HandlerInput) -> Response
  109. speak_output = "You can say hello to me! How can I help?"
  110. return (
  111. handler_input.response_builder
  112. .speak(speak_output)
  113. .ask(speak_output)
  114. .response
  115. )
  116. class CancelIntentHandler(AbstractRequestHandler):
  117. """Handler for Cancel Intent."""
  118. global order
  119. global order_names
  120. def can_handle(self, handler_input):
  121. # type: (HandlerInput) -> bool
  122. return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input))
  123. def handle(self, handler_input):
  124. # type: (HandlerInput) -> Response
  125. speak_output = "Your order has been canceled."
  126. order.clear()
  127. order_names.clear()
  128. return (
  129. handler_input.response_builder
  130. .speak(speak_output)
  131. .ask("reprompt")
  132. .response
  133. )
  134. class StopIntentHandler(AbstractRequestHandler):
  135. """Handler for Stop Intent."""
  136. def can_handle(self, handler_input):
  137. # type: (HandlerInput) -> bool
  138. return (ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input))
  139. def handle(self, handler_input):
  140. # type: (HandlerInput) -> Response
  141. speak_output = "Alright! Your order is complete. Would you like to review, finish, or cancel your order?"
  142. return (
  143. handler_input.response_builder
  144. .speak(speak_output)
  145. .ask(speak_output)
  146. .response
  147. )
  148. class LinguiniOrderNothingIntentHandler(AbstractRequestHandler):
  149. """Handler for Stop Intent."""
  150. def can_handle(self, handler_input):
  151. # type: (HandlerInput) -> bool
  152. return (ask_utils.is_intent_name("LinguiniOrderNothingIntent")(handler_input))
  153. def handle(self, handler_input):
  154. # type: (HandlerInput) -> Response
  155. speak_output = "Alright! Your order is complete. Would you like to review, finish, or cancel your order"
  156. return (
  157. handler_input.response_builder
  158. .speak(speak_output)
  159. .ask(speak_output)
  160. .response
  161. )
  162. class LinguiniOrderReviewIntentHandler(AbstractRequestHandler):
  163. global order
  164. """Handler for Hello World Intent."""
  165. def can_handle(self, handler_input):
  166. # type: (HandlerInput) -> bool
  167. return ask_utils.is_intent_name("LinguiniOrderReviewIntent")(handler_input)
  168. def handle(self, handler_input):
  169. # type: (HandlerInput) -> Response
  170. speak_output = "You have "
  171. for i in order_names:
  172. speak_output += f"{order_names[i]} {i}, "
  173. speak_output = speak_output[:-2]
  174. speak_output += ". If everything seems okay, say finish to submit order or say cancel to cancel and restart order."
  175. return (
  176. handler_input.response_builder
  177. .speak(speak_output)
  178. .ask("add a reprompt if you want to keep the session open for the user to respond")
  179. .response
  180. )
  181. class LinguiniOrderFinishIntentHandler(AbstractRequestHandler):
  182. global order
  183. global order_names
  184. """Handler for Hello World Intent."""
  185. def can_handle(self, handler_input):
  186. # type: (HandlerInput) -> bool
  187. return ask_utils.is_intent_name("LinguiniOrderFinishIntent")(handler_input)
  188. def handle(self, handler_input):
  189. # type: (HandlerInput) -> Response
  190. #Send order to Restaurant lmao
  191. full_order = [{'nombre': 'Aranpompano','celular': '(555)-555-5555', 'ordenCompleta': order, 'peticiones': {}}]
  192. #full_order = [{'nombre': 'Scott Pilgrim','celular': '(555)-555-5555', 'ordenCompleta': {'orden1':1, 'orden2': 10}, 'peticiones': {}}]
  193. try:
  194. r = requests.post('http://136.145.231.48:5000/papelonDeComida', json=full_order)
  195. except:
  196. r = None
  197. if r == None:
  198. speak_output = "Sorry, I couldn't connect to the restaurant. Please try again later."
  199. elif(r.status_code == 200):
  200. speak_output = f'Alright! {r.text}'
  201. else:
  202. speak_output = "Uh oh! I couldn't place your order, please try again later."
  203. #REPLACE THIS WHEN API IS IMPLEMENTED
  204. order.clear()
  205. order_names.clear()
  206. #REPLACE THIS WHEN API IS IMPLEMENTED
  207. return (
  208. handler_input.response_builder
  209. .speak(speak_output)
  210. # .ask("add a reprompt if you want to keep the session open for the user to respond")
  211. .response
  212. )
  213. class SessionEndedRequestHandler(AbstractRequestHandler):
  214. """Handler for Session End."""
  215. def can_handle(self, handler_input):
  216. # type: (HandlerInput) -> bool
  217. return ask_utils.is_request_type("SessionEndedRequest")(handler_input)
  218. def handle(self, handler_input):
  219. # type: (HandlerInput) -> Response
  220. # Any cleanup logic goes here.
  221. return handler_input.response_builder.response
  222. class IntentReflectorHandler(AbstractRequestHandler):
  223. """The intent reflector is used for interaction model testing and debugging.
  224. It will simply repeat the intent the user said. You can create custom handlers
  225. for your intents by defining them above, then also adding them to the request
  226. handler chain below.
  227. """
  228. def can_handle(self, handler_input):
  229. # type: (HandlerInput) -> bool
  230. return ask_utils.is_request_type("IntentRequest")(handler_input)
  231. def handle(self, handler_input):
  232. # type: (HandlerInput) -> Response
  233. intent_name = ask_utils.get_intent_name(handler_input)
  234. speak_output = "You just triggered " + intent_name + "."
  235. return (
  236. handler_input.response_builder
  237. .speak(speak_output)
  238. # .ask("add a reprompt if you want to keep the session open for the user to respond")
  239. .response
  240. )
  241. class CatchAllExceptionHandler(AbstractExceptionHandler):
  242. """Generic error handling to capture any syntax or routing errors. If you receive an error
  243. stating the request handler chain is not found, you have not implemented a handler for
  244. the intent being invoked or included it in the skill builder below.
  245. """
  246. def can_handle(self, handler_input, exception):
  247. # type: (HandlerInput, Exception) -> bool
  248. return True
  249. def handle(self, handler_input, exception):
  250. # type: (HandlerInput, Exception) -> Response
  251. logger.error(exception, exc_info=True)
  252. speak_output = "Sorry, I had trouble doing what you asked. Please try again."
  253. return (
  254. handler_input.response_builder
  255. .speak(speak_output)
  256. .ask(speak_output)
  257. .response
  258. )
  259. # The SkillBuilder object acts as the entry point for your skill, routing all request and response
  260. # payloads to the handlers above. Make sure any new handlers or interceptors you've
  261. # defined are included below. The order matters - they're processed top to bottom.
  262. sb = SkillBuilder()
  263. try:
  264. resp = requests.get('http://136.145.231.48:5000/retrieveMenu')
  265. if resp.status_code == 200:
  266. menu_full = resp.json()
  267. food_dict = menu_full['comidas']
  268. pasta_dict = comida['Pasta']
  269. drink_dict = menu_full['bebidas']
  270. else:
  271. menu_full = {}
  272. food_dict = {}
  273. pasta_dict = {}
  274. drink_dict = {}
  275. except:
  276. menu_full = {}
  277. food_dict = {}
  278. pasta_dict = {}
  279. drink_dict = {}
  280. order = {}
  281. order_names = {}
  282. sb.add_request_handler(LaunchRequestHandler())
  283. #sb.add_request_handler(HelloWorldIntentHandler())
  284. #sb.add_request_handler(HelpIntentHandler())
  285. sb.add_request_handler(LinguiniOrderFoodIntentHandler())
  286. sb.add_request_handler(LinguiniOrderDrinkIntentHandler())
  287. sb.add_request_handler(LinguiniOrderNothingIntentHandler())
  288. sb.add_request_handler(CancelIntentHandler())
  289. sb.add_request_handler(StopIntentHandler())
  290. sb.add_request_handler(LinguiniOrderReviewIntentHandler())
  291. sb.add_request_handler(LinguiniOrderFinishIntentHandler())
  292. sb.add_request_handler(SessionEndedRequestHandler())
  293. sb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers
  294. sb.add_exception_handler(CatchAllExceptionHandler())
  295. lambda_handler = sb.lambda_handler()