├── LICENSE ├── README.md └── samples └── chemistry_flash_cards ├── README.md ├── speech_assests ├── intent_schema.json ├── sample_utterances.txt └── slot_values.txt └── src └── main.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Alexa Skills Kit Samples 2 | 3 | ## Alexa Skills Kit Documentation 4 | The documentation for the Alexa Skills Kit is available on the [Amazon Apps and Services Developer Portal](https://developer.amazon.com/appsandservices/solutions/alexa/alexa-skills-kit/). 5 | 6 | ## Contents 7 | The included samples represent how to use python AWS Lambda functions as Alexa Skills. 8 | The following samples are included (ordered by complexity, see the Using Alexa Skills Kit Samples 9 | link below for more details): 10 | 11 | - [Chemistry Flash Cards](samples/chemistry_flash_cards) : a simple skill that plays falsh cards questions 12 | 13 | 14 | ## Usage 15 | Navigate to the README.md in each sub directory in the samples folder and follow the instructions for getting the sample up and running. 16 | 17 | ## Resources 18 | Here are a few direct links to our documentation: 19 | 20 | - [Using the Alexa Skills Kit Samples (Python)](https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/using-the-alexa-skills-kit-samples) 21 | - [Getting Started](https://developer.amazon.com/appsandservices/solutions/alexa/alexa-skills-kit/getting-started-guide) 22 | - [Invocation Name Guidelines](https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/choosing-the-invocation-name-for-an-alexa-skill) 23 | - [Developing an Alexa Skill as an AWS Lambda Function](https://developer.amazon.com/appsandservices/solutions/alexa/alexa-skills-kit/docs/developing-an-alexa-skill-as-a-lambda-function) 24 | -------------------------------------------------------------------------------- /samples/chemistry_flash_cards/README.md: -------------------------------------------------------------------------------- 1 | # Sample AWS Lambda function for Alexa 2 | A simple [AWS Lambda](http://aws.amazon.com/lambda) function that demonstrates how to write a skill for the Amazon Echo using the Alexa SDK. 3 | 4 | ## Concepts 5 | This simple sample has no external dependencies or session management, and shows the most basic example of how to create a Lambda function for handling Alexa Skill requests. 6 | 7 | ## Setup 8 | To run this example skill you need to do two things. The first is to deploy the example code in lambda, and the second is to configure the Alexa skill to use Lambda. 9 | 10 | ### AWS Lambda Setup 11 | 1. Go to the AWS Console and click on the Lambda link. Note: ensure you are in us-east or you won't be able to use Alexa with Lambda. 12 | 2. Click on the Create a Lambda Function or Get Started Now button. 13 | 3. Skip the blueprint 14 | 4. Name the Lambda Function "Chemistry-Flash-Cards-Example-Skill". 15 | 5. Select the runtime as Python 2.7 16 | 6. Go to the the src directory, select all files and then create a zip file, make sure the zip file does not contain the src directory itself, otherwise Lambda function will not work. 17 | 7. Select Code entry type as "Upload a .ZIP file" and then upload the .zip file to the Lambda 18 | 8. Keep the Handler as main.handler (this refers to the main python file in the zip). 19 | 9. Create a basic execution role and click create. 20 | 10. Leave the Advanced settings as the defaults. 21 | 11. Click "Next" and review the settings then click "Create Function" 22 | 12. Click the "Event Sources" tab and select "Add event source" 23 | 13. Set the Event Source type as Alexa Skills kit and Enable it now. Click Submit. 24 | 14. Copy the ARN from the top right to be used later in the Alexa Skill Setup. 25 | 26 | ### Alexa Skill Setup 27 | 1. Go to the [Alexa Console](https://developer.amazon.com/edw/home.html) and click Add a New Skill. 28 | 2. Set "ChemistryFlashCards" as the skill name and "chemistry flash cards" as the invocation name, this is what is used to activate your skill. For example you would say: "Alexa, Ask space geek for a space fact." 29 | 3. Select the Lambda ARN for the skill Endpoint and paste the ARN copied from above. Click Next. 30 | 4. Copy the Intent Schema from the included intent_schema.json. 31 | 5. Add Custom Slot Type "LIST_OF_ANSWERS" and copy from the included slot_values.txt 32 | 5. Copy the Sample Utterances from the included sample_utterances.txt. Click Next. 33 | 6. [optional] go back to the skill Information tab and copy the appId. Paste the appId into the main.py file for the variable APP_ID, 34 | then update the lambda source zip file with this change and upload to lambda again, this step makes sure the lambda function only serves request from authorized source. 35 | 7. You are now able to start testing your sample skill! You should be able to go to the [Echo webpage](http://echo.amazon.com/#skills) and see your skill enabled. 36 | 8. In order to test it, try to say some of the Sample Utterances from the Examples section below. 37 | 9. Your skill is now saved and once you are finished testing you can continue to publish your skill. 38 | -------------------------------------------------------------------------------- /samples/chemistry_flash_cards/speech_assests/intent_schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "intents": [ 3 | { 4 | "intent": "AnswerIntent", 5 | "slots": [ 6 | { 7 | "name": "Answer", 8 | "type": "LIST_OF_ANSWERS" 9 | } 10 | ] 11 | }, 12 | { 13 | "intent": "AnswerOnlyIntent", 14 | "slots": [ 15 | { 16 | "name": "Answer", 17 | "type": "LIST_OF_ANSWERS" 18 | } 19 | ] 20 | }, 21 | { 22 | "intent": "AMAZON.StartOverIntent" 23 | }, 24 | { 25 | "intent": "AMAZON.RepeatIntent" 26 | }, 27 | { 28 | "intent": "AMAZON.HelpIntent" 29 | }, 30 | { 31 | "intent": "AMAZON.YesIntent" 32 | }, 33 | { 34 | "intent": "AMAZON.NoIntent" 35 | }, 36 | { 37 | "intent": "AMAZON.StopIntent" 38 | }, 39 | { 40 | "intent": "AMAZON.CancelIntent" 41 | } 42 | ] 43 | } 44 | -------------------------------------------------------------------------------- /samples/chemistry_flash_cards/speech_assests/sample_utterances.txt: -------------------------------------------------------------------------------- 1 | AnswerIntent the answer is {Answer} 2 | AnswerIntent my answer is {Answer} 3 | AnswerIntent is it {Answer} 4 | AnswerIntent {Answer} is my answer 5 | AnswerOnlyIntent {Answer} 6 | 7 | 8 | AMAZON.StartOverIntent start game 9 | AMAZON.StartOverIntent new game 10 | AMAZON.StartOverIntent start 11 | AMAZON.StartOverIntent start new game 12 | AMAZON.StartOverIntent start a game 13 | AMAZON.StartOverIntent start a new game 14 | 15 | AMAZON.HelpIntent help 16 | AMAZON.HelpIntent help me 17 | AMAZON.HelpIntent what can I ask 18 | AMAZON.HelpIntent what can I do 19 | -------------------------------------------------------------------------------- /samples/chemistry_flash_cards/speech_assests/slot_values.txt: -------------------------------------------------------------------------------- 1 | Actinium Aluminum Americium Antimony Argon Arsenic Astatine Barium Berkelium Beryllium Bismuth Bohrium Boron Bromine Cadmium Calcium Californium Carbon Cerium Cesium Chlorine Chromium Cobalt Copper Curium Darmstadtium Dubnium Dysprosium Einsteinium Erbium Europium Fermium Fluorine Francium Gadolinium Gallium Germanium Gold Hafnium Hassium Helium Holmium Hydrogen Indium Iodine Iridium Iron Krypton Lanthanum Lawrencium Lead Lithium Lutetium Magnesium Manganese Meitnerium Mendelevium Mercury Molybdenum Neodymium Neon Neptunium Nickel Niobium Nitrogen Nobelium Osmium Oxygen Palladium Phosphorus Platinum Plutonium Polonium Potassium Praseodymium Promethium Protactinium Radium Radon Rhenium Rhodium Roentgenium Rubidium Ruthenium Rutherfordium Samarium Scandium Seaborgium Selenium Silicon Silver Sodium Strontium Sulfur Tantalum Technetium Tellurium Terbium Thallium Thorium Thulium Tin Titanium Tungsten Ununbium Ununhexium Ununoctium Ununpentium Ununquadium Ununseptium Ununtrium Ununium Uranium Vanadium Xenon Ytterbium Yttrium Zinc Zirconium -------------------------------------------------------------------------------- /samples/chemistry_flash_cards/src/main.py: -------------------------------------------------------------------------------- 1 | """Chemisty Flash Cards. 2 | 3 | This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit. 4 | The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well 5 | as testing instructions are located at http://amzn.to/1LzFrj6 6 | 7 | For additional samples, visit the Alexa Skills Kit Getting Started guide at 8 | http://amzn.to/1LGWsLG 9 | """ 10 | 11 | from __future__ import print_function 12 | import math 13 | import random 14 | import string 15 | 16 | 17 | # ------- Skill specific business logic ------- 18 | GAME_LENGTH = 5 19 | SKILL_NAME = "Chemistry Flash Cards" 20 | 21 | # When editing your questions pay attention to your punctuation. 22 | # Make sure you use question marks or periods. 23 | # Make sure the first answer is the correct one. 24 | 25 | # If there are multiple valid answers, provide all of them in the answers array. 26 | # {"Name an element with 8 valence electrons.": ["Neon", "Argon", "Krypton", "Xenon", "Radon"]}, 27 | QUESTIONS = [ 28 | {"What is A C?": ["actinium"]}, 29 | {"What is A L?": ["aluminum"]}, 30 | {"What is A M?": ["americium"]}, 31 | {"What is S B?": ["antimony"]}, 32 | {"What is A R?": ["argon"]}, 33 | {"What is A S?": ["arsenic"]}, 34 | {"What is A T?": ["astatine"]}, 35 | {"What is B A?": ["barium"]}, 36 | {"What is B K?": ["berkelium"]}, 37 | {"What is B E?": ["beryllium"]}, 38 | {"What is B I?": ["bismuth"]}, 39 | {"What is B H?": ["bohrium"]}, 40 | {"What is B?": ["boron"]}, 41 | {"What is B R ?": ["bromine"]}, 42 | {"What is C D ?": ["cadmium"]}, 43 | {"What is C A ?": ["calcium"]}, 44 | {"What is C F ?": ["californium"]}, 45 | {"What is C ?": ["carbon"]}, 46 | {"What is C E ?": ["cerium"]}, 47 | {"What is C S ?": ["cesium"]}, 48 | {"What is C L ?": ["chlorine"]}, 49 | {"What is C R ?": ["chromium"]}, 50 | {"What is C O ?": ["cobalt"]}, 51 | {"What is C U ?": ["copper"]}, 52 | {"What is C M?": ["curium"]}, 53 | ] 54 | 55 | 56 | def lambda_handler(event, context): 57 | """ 58 | Route the incoming request based on type (LaunchRequest, IntentRequest, etc). 59 | The JSON body of the request is provided in the event parameter. 60 | """ 61 | print("event.session.application.applicationId=" + 62 | event['session']['application']['applicationId']) 63 | 64 | """ 65 | Uncomment this if statement and populate with your skill's application ID 66 | to prevent someone else from configuring a skill that sends requests 67 | to this function. 68 | """ 69 | # if (event['session']['application']['applicationId'] != 70 | # "amzn1.echo-sdk-ams.app.[unique-value-here]"): 71 | # raise ValueError("Invalid Application ID") 72 | 73 | if event['session']['new']: 74 | on_session_started({'requestId': event['request']['requestId']}, 75 | event['session']) 76 | 77 | if event['request']['type'] == "LaunchRequest": 78 | return on_launch(event['request'], event['session']) 79 | elif event['request']['type'] == "IntentRequest": 80 | return on_intent(event['request'], event['session']) 81 | elif event['request']['type'] == "SessionEndedRequest": 82 | return on_session_ended(event['request'], event['session']) 83 | 84 | 85 | def on_session_started(session_started_request, session): 86 | """Called when the session starts.""" 87 | print("on_session_started requestId=" + 88 | session_started_request['requestId'] + ", sessionId=" + 89 | session['sessionId']) 90 | 91 | 92 | def on_launch(launch_request, session): 93 | """Called when the user launches the skill without specifying what they want.""" 94 | print("on_launch requestId=" + launch_request['requestId'] + 95 | ", sessionId=" + session['sessionId']) 96 | # Dispatch to your skill's launch 97 | return get_welcome_response() 98 | 99 | 100 | def on_intent(intent_request, session): 101 | """Called when the user specifies an intent for this skill.""" 102 | print("on_intent requestId=" + intent_request['requestId'] + 103 | ", sessionId=" + session['sessionId']) 104 | 105 | intent = intent_request['intent'] 106 | intent_name = intent_request['intent']['name'] 107 | 108 | # handle yes/no intent after the user has been prompted 109 | if session.get('attributes', {}).get('user_prompted_to_continue'): 110 | del session['attributes']['user_prompted_to_continue'] 111 | if intent_name == 'AMAZON.NoIntent': 112 | return handle_finish_session_request(intent, session) 113 | elif intent_name == "AMAZON.YesIntent": 114 | return handle_repeat_request(intent, session) 115 | 116 | # Dispatch to your skill's intent handlers 117 | if intent_name == "AnswerIntent": 118 | return handle_answer_request(intent, session) 119 | elif intent_name == "AnswerOnlyIntent": 120 | return handle_answer_request(intent, session) 121 | elif intent_name == "AMAZON.YesIntent": 122 | return handle_answer_request(intent, session) 123 | elif intent_name == "AMAZON.NoIntent": 124 | return handle_answer_request(intent, session) 125 | elif intent_name == "AMAZON.StartOverIntent": 126 | return get_welcome_response() 127 | elif intent_name == "AMAZON.RepeatIntent": 128 | return handle_repeat_request(intent, session) 129 | elif intent_name == "AMAZON.HelpIntent": 130 | return handle_get_help_request(intent, session) 131 | elif intent_name == "AMAZON.StopIntent": 132 | return handle_finish_session_request(intent, session) 133 | elif intent_name == "AMAZON.CancelIntent": 134 | return handle_finish_session_request(intent, session) 135 | else: 136 | raise ValueError("Invalid intent") 137 | 138 | 139 | def on_session_ended(session_ended_request, session): 140 | """ 141 | Called when the user ends the session. 142 | Is not called when the skill returns should_end_session=true 143 | """ 144 | print("on_session_ended requestId=" + session_ended_request['requestId'] + 145 | ", sessionId=" + session['sessionId']) 146 | # add cleanup logic here 147 | 148 | # --------------- Functions that control the skill's behavior ------------- 149 | 150 | 151 | def get_welcome_response(): 152 | """If we wanted to initialize the session to have some attributes we could add those here.""" 153 | intro = ("Let's play {}. ".format(SKILL_NAME) + 154 | "I will ask you {} questions. ".format(GAME_LENGTH) + 155 | "Try to get as many right as you can. Just say the answer. Let's begin. ") 156 | should_end_session = False 157 | game_questions = populate_game_questions() 158 | starting_index = 0 159 | 160 | spoken_question = QUESTIONS[game_questions[starting_index]].keys()[0] 161 | 162 | speech_output = intro + spoken_question 163 | attributes = {"speech_output": speech_output, 164 | "reprompt_text": spoken_question, 165 | "current_questions_index": starting_index, 166 | "questions": game_questions, 167 | "score": 0, 168 | "correct_answers": QUESTIONS[game_questions[starting_index]].values()[0] 169 | } 170 | 171 | return build_response(attributes, build_speechlet_response( 172 | SKILL_NAME, speech_output, spoken_question, should_end_session)) 173 | 174 | 175 | def populate_game_questions(): 176 | game_questions = [] 177 | index_list = [] 178 | index = len(QUESTIONS) 179 | 180 | if GAME_LENGTH > index: 181 | raise ValueError("Invalid Game Length") 182 | 183 | for i in range(0, index): 184 | index_list.append(i) 185 | 186 | # Pick GAME_LENGTH random questions from the list to ask the user, 187 | # make sure there are no repeats 188 | for j in range(0, GAME_LENGTH): 189 | rand = int(math.floor(random.random() * index)) 190 | index -= 1 191 | 192 | temp = index_list[index] 193 | index_list[index] = index_list[rand] 194 | index_list[rand] = temp 195 | game_questions.append(index_list[index]) 196 | 197 | return game_questions 198 | 199 | 200 | def handle_answer_request(intent, session): 201 | attributes = {} 202 | should_end_session = False 203 | answer = intent['slots'].get('Answer', {}).get('value') 204 | user_gave_up = intent['name'] 205 | 206 | if 'attributes' in session.keys() and 'questions' not in session['attributes'].keys(): 207 | # If the user responded with an answer but there is no game 208 | # in progress ask the user if they want to start a new game. 209 | # Set a flag to track that we've prompted the user. 210 | attributes['user_prompted_to_continue'] = True 211 | speech_output = "There is no game in progress. " \ 212 | "Do you want to start a new game?" 213 | reprompt_text = speech_output 214 | return build_response(attributes, build_speechlet_response(SKILL_NAME, 215 | speech_output, reprompt_text, should_end_session)) 216 | elif not answer and user_gave_up == "DontKnowIntent": 217 | # If the user provided answer isn't a number > 0 and < ANSWER_COUNT, 218 | # return an error message to the user. Remember to guide the user 219 | # into providing correct values. 220 | reprompt = session['attributes']['speech_output'] 221 | speech_output = "Your answer must be a known element " + reprompt 222 | return build_response( 223 | session['attributes'], 224 | build_speechlet_response( 225 | SKILL_NAME, speech_output, reprompt_text, should_end_session 226 | )) 227 | else: 228 | game_questions = session['attributes']['questions'] 229 | current_score = session['attributes']['score'] 230 | current_questions_index = session['attributes']['current_questions_index'] 231 | correct_answers = session['attributes']['correct_answers'] 232 | 233 | speech_output_analysis = None 234 | if answer and answer.lower() in map(string.lower, correct_answers): 235 | current_score += 1 236 | speech_output_analysis = "correct. " 237 | else: 238 | if user_gave_up != "DontKnowIntent": 239 | speech_output_analysis = "wrong. " 240 | speech_output_analysis = (speech_output_analysis + 241 | "The correct answer is " + 242 | correct_answers[0] + ".") 243 | 244 | # if current_questions_index is 4, we've reached 5 questions 245 | # (zero-indexed) and can exit the game session 246 | if current_questions_index == GAME_LENGTH - 1: 247 | speech_output = "" if intent['name'] == "DontKnowIntent" else "That answer is " 248 | speech_output = (speech_output + speech_output_analysis + 249 | "You got {} out of {} correct. ".format(current_score, GAME_LENGTH) + 250 | "Thank you for playing {} with Alexa!".format(SKILL_NAME)) 251 | reprompt_text = None 252 | should_end_session = True 253 | return build_response( 254 | session['attributes'], 255 | build_speechlet_response( 256 | SKILL_NAME, speech_output, reprompt_text, should_end_session 257 | )) 258 | else: 259 | current_questions_index += 1 260 | spoken_question = QUESTIONS[game_questions[current_questions_index]].keys()[0] 261 | reprompt_text = spoken_question 262 | 263 | speech_output = "" if user_gave_up == "DontKnowIntent" else "That answer is " 264 | speech_output = (speech_output + speech_output_analysis + 265 | "Your score is " + 266 | str(current_score) + '. ' + reprompt_text) 267 | attributes = {"speech_output": speech_output, 268 | "reprompt_text": reprompt_text, 269 | "current_questions_index": current_questions_index, 270 | "questions": game_questions, 271 | "score": current_score, 272 | "correct_answers": QUESTIONS[game_questions[current_questions_index]].values()[0] # noqa 273 | } 274 | 275 | return build_response(attributes, 276 | build_speechlet_response(SKILL_NAME, speech_output, reprompt_text, 277 | should_end_session)) 278 | 279 | 280 | def handle_repeat_request(intent, session): 281 | """ 282 | Repeat the previous speech_output and reprompt_text from the session['attributes']. 283 | If available, else start a new game session. 284 | """ 285 | if 'attributes' not in session or 'speech_output' not in session['attributes']: 286 | return get_welcome_response() 287 | else: 288 | attributes = session['attributes'] 289 | speech_output = attributes['speech_output'] 290 | reprompt_text = attributes['reprompt_text'] 291 | should_end_session = False 292 | return build_response( 293 | attributes, 294 | build_speechlet_response_without_card(speech_output, reprompt_text, should_end_session) 295 | ) 296 | 297 | 298 | def handle_get_help_request(intent, session): 299 | attributes = {} 300 | speech_output = ("You can begin a game by saying start a new game, or, " 301 | "you can say exit... What can I help you with?") 302 | reprompt_text = "What can I help you with?" 303 | should_end_session = False 304 | return build_response( 305 | attributes, 306 | build_speechlet_response(SKILL_NAME, speech_output, reprompt_text, should_end_session) 307 | ) 308 | 309 | 310 | def handle_finish_session_request(intent, session): 311 | """End the session with a message if the user wants to quit the game.""" 312 | attributes = session['attributes'] 313 | reprompt_text = None 314 | speech_output = "Thanks for playing {}!".format(SKILL_NAME) 315 | should_end_session = True 316 | return build_response( 317 | attributes, 318 | build_speechlet_response_without_card(speech_output, reprompt_text, should_end_session) 319 | ) 320 | 321 | 322 | def is_answer_slot_valid(intent): 323 | if 'Answer' in intent['slots'].keys() and 'value' in intent['slots']['Answer'].keys(): 324 | return True 325 | else: 326 | return False 327 | 328 | 329 | # --------------- Helpers that build all of the responses ----------------- 330 | 331 | def build_speechlet_response(title, output, reprompt_text, should_end_session): 332 | return { 333 | 'outputSpeech': { 334 | 'type': 'PlainText', 335 | 'text': output 336 | }, 337 | 'card': { 338 | 'type': 'Simple', 339 | 'title': title, 340 | 'content': output 341 | }, 342 | 'reprompt': { 343 | 'outputSpeech': { 344 | 'type': 'PlainText', 345 | 'text': reprompt_text 346 | } 347 | }, 348 | 'shouldEndSession': should_end_session 349 | } 350 | 351 | 352 | def build_speechlet_response_without_card(output, reprompt_text, should_end_session): 353 | return { 354 | 'outputSpeech': { 355 | 'type': 'PlainText', 356 | 'text': output 357 | }, 358 | 'reprompt': { 359 | 'outputSpeech': { 360 | 'type': 'PlainText', 361 | 'text': reprompt_text 362 | } 363 | }, 364 | 'shouldEndSession': should_end_session 365 | } 366 | 367 | 368 | def build_response(attributes, speechlet_response): 369 | return { 370 | 'version': '1.0', 371 | 'sessionAttributes': attributes, 372 | 'response': speechlet_response 373 | } 374 | --------------------------------------------------------------------------------