Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2017
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.28 KB | None | 0 0
  1. from __future__ import print_function
  2. import urllib2
  3. import json
  4. from operator import itemgetter
  5. from decimal import Decimal
  6.  
  7. material_query = 'XXXYOUR_SERVICE_CALL&$format=json'
  8. customer_query = 'XXXYOUR_OTHER_SERVICE_CALL&$format=json'
  9.  
  10. # --------------- Helpers that build all of the responses ----------------------
  11.  
  12. def build_speechlet_response(title, output, reprompt_text, should_end_session):
  13.     return {
  14.         'outputSpeech': {
  15.             'type': 'PlainText',
  16.             'text': output
  17.         },
  18.         'card': {
  19.             'type': 'Simple',
  20.             'title': "SessionSpeechlet - " + title,
  21.             'content': "SessionSpeechlet - " + output
  22.         },
  23.         'reprompt': {
  24.             'outputSpeech': {
  25.                 'type': 'PlainText',
  26.                 'text': reprompt_text
  27.             }
  28.         },
  29.         'shouldEndSession': should_end_session
  30.     }
  31.  
  32.  
  33. def build_response(session_attributes, speechlet_response):
  34.     return {
  35.         'version': '1.0',
  36.         'sessionAttributes': session_attributes,
  37.         'response': speechlet_response
  38.     }
  39.  
  40.  
  41. # --------------- Functions that control the skill's behavior ------------------
  42.  
  43. def get_welcome_response():
  44.     session_attributes = {}
  45.     card_title = "Welcome"
  46.     speech_output = "Welcome to the Mindset Dashboard. " \
  47.                     "Ask a question about your business, such as " \
  48.                     "'What are my best Materials?' Or, 'Which customers "\
  49.                     "are buying the most product?'"
  50.                    
  51.     # If the user either does not reply to the welcome message or says something
  52.     # that is not understood, they will be prompted again with this text.
  53.     reprompt_text = "Ask about your business data, especially customers and materials."                
  54.     should_end_session = False
  55.  
  56.     return build_response(session_attributes, build_speechlet_response(
  57.         card_title, speech_output, reprompt_text, should_end_session))
  58.  
  59.  
  60. def get_dashboard(intent, query_name, session):
  61.     session_attributes = {}
  62.     reprompt_text = None
  63.  
  64.     opener = urllib2.build_opener()
  65.  
  66.     opener.addheaders = [('Authorization', 'Basic DONT_USE_MINE_USE_YOUR_OWN'),
  67.                          ('Connection', 'keep-alive'),
  68.                          ('X-Requested-With', 'XMLHttpRequest'),
  69.                          ('Accept', 'application/json')]
  70.  
  71.     if query_name == 'materials':
  72.         result = opener.open(material_query).read()
  73.     else:
  74.         result = opener.open(customer_query).read()
  75.        
  76.     result_json =json.loads(result)
  77.  
  78.     """Here's where we handle the response to the request.
  79.       NOTE: this will DEFINITELY not work for your request. The
  80.       particular format of the Mindset Analytics App OData service
  81.       drives this code.
  82.    
  83.    key = ''
  84.    value = ''
  85.    unsorted_dict = {}
  86.    for index, item in enumerate(result_json['d']['results']):
  87.        if index % 2 == 0:
  88.            key = item['Data']
  89.        else:
  90.            try:
  91.                value = Decimal(item['Data'].replace(',',''))
  92.            except:
  93.                value = 0.0
  94.  
  95.        if key and value:
  96.            unsorted_dict[key] = value
  97.            key = ''
  98.            value = ''
  99.  
  100.    sorted_full_result = sorted(unsorted_dict, key=unsorted_dict.get, reverse=True)
  101.    sorted_result = sorted_full_result[:4]  
  102.    """
  103.  
  104.     #Build the response
  105.     if len(sorted_result) > 0:
  106.         should_end_session = True
  107.        
  108.         if query_name == 'materials':
  109.             speech_output = 'The top 4 best-selling materials at your plant are: '
  110.         else:
  111.             speech_output = 'The top 4 customers by volume purchased are: '
  112.            
  113.         for index, result in enumerate(sorted_result):
  114.             if index < 3:
  115.                 speech_output += result + ', '
  116.             else:
  117.                 speech_output += 'and ' + result + '.'
  118.                
  119.     speech_output = speech_output.replace('"', '').replace('&', 'and')
  120.  
  121.     return build_response(session_attributes, build_speechlet_response(
  122.         intent['name'], speech_output, reprompt_text, should_end_session))
  123.  
  124.  
  125. # --------------- Events ------------------
  126.  
  127. def on_launch(launch_request, session):
  128.     return get_welcome_response()
  129.  
  130.  
  131. def on_intent(intent_request, session):
  132.     intent = intent_request['intent']
  133.     intent_name = intent_request['intent']['name']
  134.     query_name = intent['slots']['Query']['value']
  135.  
  136.     # Dispatch to your skill's intent handlers
  137.     if intent_name == "GetDashboard":
  138.         return get_dashboard(intent, query_name, session)
  139.     elif intent_name == "AMAZON.HelpIntent":
  140.         return get_welcome_response()
  141.     elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent":
  142.         return handle_session_end_request()
  143.     else:
  144.         raise ValueError("Invalid intent")
  145.  
  146.  
  147. # --------------- Main handler ------------------
  148.  
  149. def lambda_handler(event, context):
  150.     if event['request']['type'] == "LaunchRequest":
  151.         return on_launch(event['request'], event['session'])
  152.     elif event['request']['type'] == "IntentRequest":
  153.         return on_intent(event['request'], event['session'])
  154.     elif event['request']['type'] == "SessionEndedRequest":
  155.         return on_session_ended(event['request'], event['session'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement