No Description

lambda_function.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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 requests
  7. import csv
  8. import logging
  9. import ask_sdk_core.utils as ask_utils
  10. from ask_sdk_core.skill_builder import SkillBuilder
  11. from ask_sdk_core.dispatch_components import AbstractRequestHandler
  12. from ask_sdk_core.dispatch_components import AbstractExceptionHandler
  13. from ask_sdk_core.handler_input import HandlerInput
  14. from ask_sdk_model import Response
  15. logger = logging.getLogger(__name__)
  16. logger.setLevel(logging.INFO)
  17. global ordernum
  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 = "Welcome to Linguini."
  27. return (
  28. handler_input.response_builder
  29. .speak(speak_output)
  30. .ask(speak_output)
  31. .response
  32. )
  33. #_________________________Alejandro Rodriguez's functions______________________________
  34. class MenuIntentHandler(AbstractRequestHandler):
  35. """Handler for Menu Intent."""
  36. def can_handle(self, handler_input):
  37. return ask_utils.is_intent_name("MenuIntent")(handler_input)
  38. def handle(self, handler_input):
  39. url = 'http://136.145.231.48:5000/retrieveMenu'
  40. menuitems = requests.get(url).json()
  41. categories = ""
  42. Maxsize = len(menuitems['bebidas']) + len(menuitems['comidas'])
  43. counter = 0
  44. for BigCategory in menuitems:
  45. for category in menuitems[BigCategory]:
  46. if counter == (Maxsize - 1):
  47. categories += "and " + category + "."
  48. else:
  49. categories += category + ", "
  50. counter = counter + 1
  51. speak_output = "The menu categories are: " + categories
  52. return (
  53. handler_input.response_builder
  54. .speak(speak_output)
  55. .ask(speak_output)
  56. .response
  57. )
  58. class PizzaIntentHandler(AbstractRequestHandler):
  59. """Handler for Pizza Intent."""
  60. def can_handle(self, handler_input):
  61. # type: (HandlerInput) -> bool
  62. return ask_utils.is_intent_name("PizzaIntent")(handler_input)
  63. def handle(self, handler_input):
  64. # type: (HandlerInput) -> Response
  65. url = 'http://136.145.231.48:5000/retrieveMenu'
  66. menuitems = requests.get(url).json()
  67. categories = ""
  68. Maxsize = len(menuitems['comidas']['Pizza'])
  69. counter = 0
  70. for item in menuitems['comidas']['Pizza']:
  71. if counter == (Maxsize - 1):
  72. categories += "and " + menuitems['comidas']['Pizza'][item]['nombre'] + "."
  73. else:
  74. categories += menuitems['comidas']['Pizza'][item]['nombre'] + ", "
  75. counter = counter + 1
  76. speak_output = "The pizzas categories are: " + categories
  77. return (
  78. handler_input.response_builder
  79. .speak(speak_output)
  80. .ask(speak_output)
  81. .response
  82. )
  83. class PastaIntentHandler(AbstractRequestHandler):
  84. """Handler for Pasta Intent."""
  85. def can_handle(self, handler_input):
  86. # type: (HandlerInput) -> bool
  87. return ask_utils.is_intent_name("PastaIntent")(handler_input)
  88. def handle(self, handler_input):
  89. # type: (HandlerInput) -> Response
  90. url = 'http://136.145.231.48:5000/retrieveMenu'
  91. menuitems = requests.get(url).json()
  92. categories = ""
  93. Maxsize = len(menuitems['comidas']['Pasta'])
  94. counter = 0
  95. for item in menuitems['comidas']['Pasta']:
  96. if counter == (Maxsize - 1):
  97. categories += "and " + menuitems['comidas']['Pasta'][item]['nombre'] + "."
  98. else:
  99. categories += menuitems['comidas']['Pasta'][item]['nombre'] + ", "
  100. counter = counter + 1
  101. speak_output = "The pastas categories are: " + categories
  102. return (
  103. handler_input.response_builder
  104. .speak(speak_output)
  105. .ask(speak_output)
  106. .response
  107. )
  108. class HamburgerIntentHandler(AbstractRequestHandler):
  109. """Handler for Pasta Intent."""
  110. def can_handle(self, handler_input):
  111. # type: (HandlerInput) -> bool
  112. return ask_utils.is_intent_name("HamburgerIntent")(handler_input)
  113. def handle(self, handler_input):
  114. # type: (HandlerInput) -> Response
  115. url = 'http://136.145.231.48:5000/retrieveMenu'
  116. menuitems = requests.get(url).json()
  117. categories = ""
  118. Maxsize = len(menuitems['comidas']['Hamburguesa'])
  119. counter = 0
  120. for item in menuitems['comidas']['Hamburguesa']:
  121. if counter == (Maxsize - 1):
  122. categories += "and " + menuitems['comidas']['Hamburguesa'][item]['nombre'] + "."
  123. else:
  124. categories += menuitems['comidas']['Hamburguesa'][item]['nombre'] + ", "
  125. counter = counter + 1
  126. speak_output = "The Hamburger categories are: " + categories
  127. return (
  128. handler_input.response_builder
  129. .speak(speak_output)
  130. .ask(speak_output)
  131. .response
  132. )
  133. class DrinksIntentHandler(AbstractRequestHandler):
  134. """Handler for Pasta Intent."""
  135. def can_handle(self, handler_input):
  136. # type: (HandlerInput) -> bool
  137. return ask_utils.is_intent_name("DrinkIntent")(handler_input)
  138. def handle(self, handler_input):
  139. # type: (HandlerInput) -> Response
  140. url = 'http://136.145.231.48:5000/retrieveMenu'
  141. menuitems = requests.get(url).json()
  142. categories = ""
  143. Maxsize = len(menuitems['bebidas'][''])
  144. counter = 0
  145. for item in menuitems['comidas']['Hamburguesa']:
  146. if counter == (Maxsize - 1):
  147. categories += "and " + menuitems['comidas']['Hamburguesa'][item]['nombre'] + "."
  148. else:
  149. categories += menuitems['comidas']['Hamburguesa'][item]['nombre'] + ", "
  150. counter = counter + 1
  151. speak_output = "The Hamburger categories are: " + categories
  152. return (
  153. handler_input.response_builder
  154. .speak(speak_output)
  155. .ask(speak_output)
  156. .response
  157. )
  158. #________________________________________________________________
  159. #Esta proxima seccion de codigo fue hecha por Pablo Loyola
  160. class LinguiniOrderFoodIntentHandler(AbstractRequestHandler):
  161. """Handler for Linguini Order Food Intent."""
  162. global ordernum
  163. ordernum = ordernum + 1
  164. global food_dict
  165. global order
  166. def can_handle(self, handler_input):
  167. # type: (HandlerInput) -> bool
  168. return ask_utils.is_intent_name("LinguiniOrderFoodIntent")(handler_input)
  169. def handle(self, handler_input):
  170. # type: (HandlerInput) -> Response
  171. slots = handler_input.request_envelope.request.intent.slots
  172. food_type = slots["food_type"].value
  173. food_category = slots["food_category"].value
  174. speak_output = f"One {food_type} {food_category} added to your order. What else would you like to add?"
  175. food = f"{food_type} {food_category}"
  176. if food == "gardenia pasta":
  177. orderstr = 'orden' + str(ordernum)
  178. order[orderstr] = 2
  179. else:
  180. orderstr = 'orden' + str(ordernum)
  181. order[ordernum] = 1
  182. if food in order_names:
  183. order_names[food] += 1
  184. else:
  185. order_names[food] = 1
  186. handler_input.response_builder.speak(speak_output).ask("What else would you like to add?")
  187. return (handler_input.response_builder.response)
  188. class LinguiniOrderDrinkIntentHandler(AbstractRequestHandler):
  189. """Handler for Linguini Order Drink Intent."""
  190. global ordernum
  191. ordernum = ordernum + 1
  192. global drink_dict
  193. global order
  194. global order_names
  195. def can_handle(self, handler_input):
  196. # type: (HandlerInput) -> bool
  197. return ask_utils.is_intent_name("LinguiniOrderDrinkIntent")(handler_input)
  198. def handle(self, handler_input):
  199. # type: (HandlerInput) -> Response
  200. slots = handler_input.request_envelope.request.intent.slots
  201. drink_type = slots["drink_type"].value
  202. speak_output = f"One {drink_type} added to your order. What else would you like to add?"
  203. if drink_type == "water":
  204. orderstr = 'orden' + str(ordernum)
  205. order[orderstr] = 10
  206. else:
  207. orderstr = 'orden' + str(ordernum)
  208. order[orderstr] = 9
  209. if drink_type in order_names:
  210. order_names[drink_type] += 1
  211. else:
  212. order_names[drink_type] = 1
  213. handler_input.response_builder.speak(speak_output).ask("What else would you like to add?")
  214. return (handler_input.response_builder.response)
  215. class HelpIntentHandler(AbstractRequestHandler):
  216. """Handler for Help Intent."""
  217. def can_handle(self, handler_input):
  218. # type: (HandlerInput) -> bool
  219. return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input)
  220. def handle(self, handler_input):
  221. # type: (HandlerInput) -> Response
  222. speak_output = "You can say hello to me! How can I help?"
  223. return (
  224. handler_input.response_builder
  225. .speak(speak_output)
  226. .ask(speak_output)
  227. .response
  228. )
  229. class CancelIntentHandler(AbstractRequestHandler):
  230. """Handler for Cancel Intent."""
  231. global order
  232. def can_handle(self, handler_input):
  233. # type: (HandlerInput) -> bool
  234. return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input))
  235. def handle(self, handler_input):
  236. # type: (HandlerInput) -> Response
  237. speak_output = "Your order has been canceled."
  238. order.clear()
  239. return (
  240. handler_input.response_builder
  241. .speak(speak_output)
  242. .ask("reprompt")
  243. .response
  244. )
  245. class LinguiniOrderNothingIntentHandler(AbstractRequestHandler):
  246. """Handler for Stop Intent."""
  247. def can_handle(self, handler_input):
  248. # type: (HandlerInput) -> bool
  249. return (ask_utils.is_intent_name("LinguiniOrderNothingIntent")(handler_input))
  250. def handle(self, handler_input):
  251. # type: (HandlerInput) -> Response
  252. speak_output = "Alright! Your order is complete. Would you like to review, finish, or cancel your order"
  253. return (
  254. handler_input.response_builder
  255. .speak(speak_output)
  256. .ask(speak_output)
  257. .response
  258. )
  259. class LinguiniOrderReviewIntentHandler(AbstractRequestHandler):
  260. global order
  261. """Handler for Hello World Intent."""
  262. def can_handle(self, handler_input):
  263. # type: (HandlerInput) -> bool
  264. return ask_utils.is_intent_name("LinguiniOrderReviewIntent")(handler_input)
  265. def handle(self, handler_input):
  266. # type: (HandlerInput) -> Response
  267. speak_output = "You have "
  268. for i in order_names:
  269. speak_output += f"{order_names[i]} {i}, "
  270. speak_output = speak_output[:-2]
  271. speak_output += ". If everything seems okay, say finish to submit order or say cancel to cancel and restart order."
  272. return (
  273. handler_input.response_builder
  274. .speak(speak_output)
  275. .ask("add a reprompt if you want to keep the session open for the user to respond")
  276. .response
  277. )
  278. class LinguiniOrderFinishIntentHandler(AbstractRequestHandler):
  279. global order
  280. global order_names
  281. """Handler for Hello World Intent."""
  282. def can_handle(self, handler_input):
  283. # type: (HandlerInput) -> bool
  284. return ask_utils.is_intent_name("LinguiniOrderFinishIntent")(handler_input)
  285. def handle(self, handler_input):
  286. # type: (HandlerInput) -> Response
  287. #Send order to Restaurant lmao
  288. full_order = [{'nombre': 'Aranpompano','celular': '(555)-555-5555', 'ordenCompleta': order, 'peticiones': {}}]
  289. #full_order = [{'nombre': 'Scott Pilgrim','celular': '(555)-555-5555', 'ordenCompleta': {'orden1':1, 'orden2': 10}, 'peticiones': {}}]
  290. try:
  291. r = requests.post('http://136.145.231.48:5000/papelonDeComida', json=full_order)
  292. except:
  293. r = None
  294. if r == None:
  295. speak_output = "Sorry, I couldn't connect to the restaurant. Please try again later."
  296. elif(r.status_code == 200):
  297. speak_output = f'Alright! {r.text}'
  298. else:
  299. speak_output = "Uh oh! I couldn't place your order, please try again later."
  300. #REPLACE THIS WHEN API IS IMPLEMENTED
  301. order.clear()
  302. order_names.clear()
  303. #REPLACE THIS WHEN API IS IMPLEMENTED
  304. return (
  305. handler_input.response_builder
  306. .speak(speak_output)
  307. # .ask("add a reprompt if you want to keep the session open for the user to respond")
  308. .response
  309. )
  310. #________________________________________________________________
  311. class HelpIntentHandler(AbstractRequestHandler):
  312. """Handler for Help Intent."""
  313. def can_handle(self, handler_input):
  314. # type: (HandlerInput) -> bool
  315. return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input)
  316. def handle(self, handler_input):
  317. # type: (HandlerInput) -> Response
  318. speak_output = "Las categorias son: pizzas, pastas, ensaladas, postres y por ultimo las bebidas. Cual desea saber mas?"
  319. return (
  320. handler_input.response_builder
  321. .speak(speak_output)
  322. .ask(speak_output)
  323. .response
  324. )
  325. class CancelOrStopIntentHandler(AbstractRequestHandler):
  326. """Single handler for Cancel and Stop Intent."""
  327. def can_handle(self, handler_input):
  328. # type: (HandlerInput) -> bool
  329. return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or
  330. ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input))
  331. def handle(self, handler_input):
  332. # type: (HandlerInput) -> Response
  333. speak_output = "Tenga buen dia!"
  334. return (
  335. handler_input.response_builder
  336. .speak(speak_output)
  337. .response
  338. )
  339. class SessionEndedRequestHandler(AbstractRequestHandler):
  340. """Handler for Session End."""
  341. def can_handle(self, handler_input):
  342. # type: (HandlerInput) -> bool
  343. return ask_utils.is_request_type("SessionEndedRequest")(handler_input)
  344. def handle(self, handler_input):
  345. # type: (HandlerInput) -> Response
  346. # Any cleanup logic goes here.
  347. return handler_input.response_builder.response
  348. class IntentReflectorHandler(AbstractRequestHandler):
  349. """The intent reflector is used for interaction model testing and debugging.
  350. It will simply repeat the intent the user said. You can create custom handlers
  351. for your intents by defining them above, then also adding them to the request
  352. handler chain below.
  353. """
  354. def can_handle(self, handler_input):
  355. # type: (HandlerInput) -> bool
  356. return ask_utils.is_request_type("IntentRequest")(handler_input)
  357. def handle(self, handler_input):
  358. # type: (HandlerInput) -> Response
  359. intent_name = ask_utils.get_intent_name(handler_input)
  360. speak_output = "You just triggered " + intent_name + "."
  361. return (
  362. handler_input.response_builder
  363. .speak(speak_output)
  364. # .ask("add a reprompt if you want to keep the session open for the user to respond")
  365. .response
  366. )
  367. class CatchAllExceptionHandler(AbstractExceptionHandler):
  368. """Generic error handling to capture any syntax or routing errors. If you receive an error
  369. stating the request handler chain is not found, you have not implemented a handler for
  370. the intent being invoked or included it in the skill builder below.
  371. """
  372. def can_handle(self, handler_input, exception):
  373. # type: (HandlerInput, Exception) -> bool
  374. return True
  375. def handle(self, handler_input, exception):
  376. # type: (HandlerInput, Exception) -> Response
  377. logger.error(exception, exc_info=True)
  378. speak_output = "Sorry, I had trouble doing what you asked, please try again. "
  379. return (
  380. handler_input.response_builder
  381. .speak(speak_output)
  382. .ask(speak_output)
  383. .response
  384. )
  385. # The SkillBuilder object acts as the entry point for your skill, routing all request and response
  386. # payloads to the handlers above. Make sure any new handlers or interceptors you've
  387. # defined are included below. The order matters - they're processed top to bottom.
  388. sb = SkillBuilder()
  389. sb.add_request_handler(LaunchRequestHandler())
  390. sb.add_request_handler(DrinksIntentHandler())
  391. sb.add_request_handler(MenuIntentHandler())
  392. sb.add_request_handler(PastaIntentHandler())
  393. sb.add_request_handler(PizzaIntentHandler())
  394. sb.add_request_handler(HamburgerIntentHandler())
  395. sb.add_request_handler(LinguiniOrderFoodIntentHandler())
  396. sb.add_request_handler(LinguiniOrderDrinkIntentHandler())
  397. sb.add_request_handler(LinguiniOrderNothingIntentHandler())
  398. sb.add_request_handler(LinguiniOrderReviewIntentHandler())
  399. sb.add_request_handler(LinguiniOrderFinishIntentHandler())
  400. sb.add_request_handler(HelpIntentHandler())
  401. sb.add_request_handler(CancelOrStopIntentHandler())
  402. sb.add_request_handler(SessionEndedRequestHandler())
  403. sb.add_request_handler(IntentReflectorHandler()) # THIS ONE HAS TO GO LAST
  404. sb.add_exception_handler(CatchAllExceptionHandler())
  405. lambda_handler = sb.lambda_handler()