def intent_next_meeting(): """Initialize the session to have some attributes.""" url = '{}/events/?key={}'.format(settings.MEETUP_API_ROOT, settings.MEETUP_API_KEY) response = requests.get(url) try: response_json = response.json() except ValueError: speech = 'Oh, no! Invalid JSON response.' return build_response(build_speechlet_response(speech)) if not len(response_json): speech = 'There are currently no scheduled meetups coming up, but check back soon!' return build_response(build_speechlet_response(speech)) event = response_json[0] name = event['name'] when = datetime.fromtimestamp(event['time'] / 1000).strftime('%A, %B %d at %I:%M %p') desc = re.sub('<[^<]+?>', '', event['description']) speech = ( 'The next Python Saint Pete meeting is {}. The topic is {} with a description of ' '{}'.format(when, name, desc)) return build_response( build_speechlet_response(speech, card_title='PyStPete Meetup', card_content='\n'.join((when, name, desc))))
def get_question_response(intent, session): """ Finds the closes question, pulls the answer and reports back """ card_title = intent['name'] session_attributes = {} should_end_session = True speech_output = strings.FAILURE reprompt_text = strings.PROMPT_ASK logging.info(intent) if not 'question' in intent['slots']: speechlet_response = build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session) return build_response(session_attributes, speechlet_response) encoded_question = urllib2.quote(intent['slots']['question']['value']) logging.info(encoded_question) url = settings.ASK_QUESTION_ENDPOINT.format(question=encoded_question) logging.info('Getting: ' + url) resp = requests.get(url).json() logging.info(resp) try: site_question = resp['items'][0] except (IndexError, KeyError): speech_output = strings.NO_QUESTIONS speechlet_response = build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session) return build_response(session_attributes, speechlet_response) site_question_question_id = site_question['question_id'] site_question_title = site_question['title'] logging.warn(site_question_title) url = settings.GET_ANSWERS_ENDPOINT.format(question_id=site_question_question_id) resp = requests.get(url).json() try: site_answer = sorted(resp['items'][0]['answers'], key=lambda i: i['score'], reverse=True)[0] except (IndexError, KeyError) as e: speech_output = strings.NO_ANSWERS.format(question=encoded_question) speechlet_response = build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session) return build_response(session_attributes, speechlet_response) site_answer_answerer = site_answer['owner']['display_name'] site_answer_score = site_answer['score'] site_answer_body = strip_tags(site_answer['body']) speech_output = strings.REPORT.format( question=site_question_title, answerer=site_answer_answerer, votes=site_answer_score, answer=site_answer_body ) logging.info(speech_output) speechlet_response = build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session) return build_response(session_attributes, speechlet_response)
def intent_handler(self, intent, session): """ Collects values to generate an Alexa response by calling custom logic based on the intent name """ session_attributes = {} should_end_session = True reprompt_text = "i didn't get that please repeat" intent_name = intent['name'] if intent_name in self.intent_mappings: if 'slots' not in intent: slots = {} else: slots = intent['slots'] speech_output = self.intent_mappings[intent_name](slots) else: # this shouldn't occur unless we omit the implementation of some intent should_end_session = True speech_output = "hmm not sure how to deal with your request" speechlet_response = build_speechlet_response(intent['name'], speech_output, reprompt_text, should_end_session) return build_response(session_attributes, speechlet_response)
def get_session_end_response(): card_title = "Session Ended" speech_output = strings.GOODBYE # Setting this to true ends the session and exits the skill. should_end_session = True return build_response({}, build_speechlet_response( card_title, speech_output, None, should_end_session))
def google_disconnect(): """Helper function that disconnects from google before logging out.""" access_token = login_session.get('access_token') if not access_token: return helpers.build_response('User already logged out.', 401) target_url = ('https://accounts.google.com/o/oauth2/revoke?\ token=%s' % access_token) req = httplib2.Http() result = req.request(target_url, 'GET')[0] if result['status'] == '200': return helpers.build_response('User successfully logged out.', 200) else: return helpers.build_response('Failed to log out user.', 400)
def lambda_handler(event, context): """Route the incoming request based on the event.""" # Prevent unwanted access to this Lambda function. app_id = event['session']['application']['applicationId'] if settings.LAMBDA_ARN and app_id != settings.LAMBDA_ARN: speech = 'Permission denied!' build_response(build_speechlet_response(speech)) func_map = { 'LaunchRequest': on_launch, 'IntentRequest': on_intent, } request = event['request'] return func_map[request['type']](request, event['session'])
def add(): with open('locations.json') as json_file: locations = json.load(json_file) for location in locations['locationObjects']: table.put_item( Item={ 'id': location['id'], 'location': location['location'], 'value': location['value'] } ) return build_response({}, build_speechlet_response("Hello", "succesfully added items to DB", None, False))
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ session_attributes = {} card_title = "Welcome" speech_output = strings.WELCOME # If the user either does not reply to the welcome message or says something # that is not understood, they will be prompted again with this text. reprompt_text = strings.WELCOME_REPROMPT should_end_session = False speechlet_response = build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session) return build_response(session_attributes, speechlet_response)
def login(): """Handles the whole login process. The GET endpoint displays a page with the google sign in button. The POST endpoint exchanges the client-fetched token with client's credentials. """ if request.method == 'GET': # Generate unique session token and rendering login prompt state_token = ''.join( random.choice(string.ascii_uppercase + string.digits) for i in range(32)) # Keeping a copy for later comparison to ensure no forgery happens login_session['state'] = state_token return render_template('login.html', state=state_token, client_id=CLIENT_ID) else: # Testing the 1-time auth code the user got from Google to login user # Request was forged if request.args.get('state') != login_session['state']: return helpers.build_response('Unauthorized request source.', 401) # This one-time code will be exchanged for an access token from Google one_time_auth = request.data # Exchanging the one-time auth with user's Google credentials try: oauth_flow = flow_from_clientsecrets('client_secret.json', scope='') oauth_flow.redirect_uri = 'postmessage' creds = oauth_flow.step2_exchange(one_time_auth) except FlowExchangeError: return helpers.build_response('Token exchange error.', 401) # Testing exchanged credentials access_token = creds.access_token target_url = ( 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token' '=%s' % access_token) req = httplib2.Http() result = json.loads(req.request(target_url, 'GET')[1]) if result.get('error') is not None: return helpers.build_response(result.get('error'), 500) google_id = creds.id_token['sub'] if result['user_id'] != google_id: return helpers.build_response( result.get('User and token IDs are not matching.'), 401) if result['issued_to'] != CLIENT_ID: return helpers.build_response( result.get( 'Token\'s target client ID doesn\'t match this client.'), 401) # If we got here then the OAuth process is successful valid_access_token = login_session.get('access_token') valid_google_id = login_session.get('gplus_id') # Checking if user is already logged in if valid_access_token and google_id == valid_google_id: return helpers.build_response('User already logged in.', 200) login_session['access_token'] = creds.access_token login_session['gplus_id'] = google_id userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo' userinfo_res = requests.get(userinfo_url, params={ 'access_token': creds.access_token, 'alt': 'json' }) user_data = userinfo_res.json() login_session['email'] = user_data['email'] login_session['name'] = user_data['name'] login_session['pic'] = user_data['picture'] # Creating user if hasn't logged in before user_id = helpers.get_uid(user_data['email']) if not user_id: user_id = helpers.create_user(login_session) login_session['user_id'] = user_id flash('Welcome back, %s!' % login_session['name']) return redirect((url_for('home')))