Created
December 18, 2017 22:40
-
-
Save TheSkorm/b66f1a60dae7cd7e85c86329554af55a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit. | |
| The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well | |
| as testing instructions are located at http://amzn.to/1LzFrj6 | |
| For additional samples, visit the Alexa Skills Kit Getting Started guide at | |
| http://amzn.to/1LGWsLG | |
| """ | |
| import urllib, urllib2 | |
| import json, datetime | |
| devid = "1000583" | |
| devkey = "" | |
| def nownomicro(): | |
| ''' Returns current time, without microseconds, as required by PTV API.''' | |
| return datetime.datetime.utcnow().replace(microsecond=0) | |
| def now8601(): | |
| ''' Returns current time, without microseconds, as required by PTV API, in 8601 format.''' | |
| return nownomicro().isoformat() | |
| def callAPI(api, args={}): | |
| ''' Makes the specified API call, handling signature computation and developer id.''' | |
| import hmac, hashlib | |
| ptvbase="http://timetableapi.ptv.vic.gov.au" | |
| preamble = "/v2/" | |
| args['devid'] = devid | |
| call = preamble + api + "?" + urllib.urlencode(args) | |
| sig=hmac.new(devkey, call, hashlib.sha1).hexdigest().upper() | |
| url=ptvbase + call + "&signature=" + sig | |
| print(url) | |
| response = urllib2.urlopen(url) | |
| return json.load(response) | |
| def healthCheck(): | |
| ''' Verifies that devID and key are correct so future calls will succeed. | |
| "A check on the timely availability, connectivity and reachability of the services that deliver security, caching and data to web clients. A health status report is returned." | |
| ''' | |
| # eg: healthCheck() | |
| h = callAPI("healthcheck", { "timestamp": now8601() } ) | |
| if not h['securityTokenOK'] or not h['databaseOK'] : | |
| raise Exception('Failed healthchck') | |
| return h | |
| def stopsNearby(latitude, longitude): | |
| '''Stops Nearby returns up to 30 stops nearest to a specified coordinate."''' | |
| # stopsNearby(-38, 145) | |
| return callAPI("nearme/latitude/%d/longitude/%d" % (latitude, longitude)) | |
| def transportPOIsByMap(poi, lat1, long1, lat2, long2, griddepth, limit): | |
| '''"Transport POIs by Map returns a set of locations consisting of stops and/or myki ticket outlets | |
| (collectively known as points of interest - i.e. POIs) within a region demarcated on a map through | |
| a set of latitude and longitude coordinates. | |
| POI codes: | |
| 0 Train (metropolitan) | |
| 1 Tram | |
| 2 Bus (metropolitan and regional, but not V/Line) | |
| 3 V/Line regional train and coach | |
| 4 NightRider | |
| 100 Ticket outlet | |
| "''' | |
| # transportPOIsByMap(2,-37,145,-37.5,145.5,3,10) | |
| return callAPI("poi/%s/lat1/%d/long1/%d/lat2/%d/long2/%d/griddepth/%d/limit/%d" % | |
| (str(poi), lat1, long1, lat2, long2, griddepth, limit)) | |
| def search(query): | |
| '''"The Search API returns all stops and lines that match the input search text."''' | |
| # search("Hoddle St") | |
| return callAPI("search/" + urllib.quote(str(query))) | |
| #TODO: convert incoming dates to datetimes, using dateutil.parser | |
| def broadNextDepartures(mode, stop, limit, for_utc=nownomicro()): | |
| '''"Broad Next Departures returns the next departure times at a prescribed stop irrespective of the line and direction of the service. For example, if the stop is Camberwell Station, Broad Next Departures will return the times for all three lines (Belgrave, Lilydale and Alamein) running in both directions (towards the city and away from the city)." | |
| Note: since the result is wrapped in a 'values' object, we return the contents of that object. | |
| ''' | |
| # This and all functions that have a 'mode' argument also allow strings: train,tram,bus,vline,nightrider | |
| # broadNextDepartures(0,1104,2) | |
| # Note: for_utc is undocumented. | |
| return callAPI("mode/%d/stop/%d/departures/by-destination/limit/%d" % (modeFromString(mode), stop, limit), | |
| {"for_utc": for_utc.isoformat() })['values'] | |
| def specificNextDepartures(mode, line, stop, directionid, limit, for_utc=nownomicro()): | |
| '''"Specific Next Departures returns the times for the next departures at a prescribed stop for a specific mode, line and direction. For example, if the stop is Camberwell Station, Specific Next Departures returns only the times for one line running in one direction (for example, the Belgrave line running towards the city)."''' | |
| # specificNextDepartures(1,1881,2026,24,1) | |
| return callAPI("mode/%d/line/%d/stop/%d/directionid/%d/departures/all/limit/%d" % | |
| (modeFromString(mode), line, stop, directionid, limit)) | |
| #{"for_utc": for_utc.isoformat() }) | |
| def stoppingPattern(mode,run,stop,for_utc=nownomicro()): | |
| ''' "The Stopping Pattern API returns the stopping pattern for a specific run (i.e. transport service) from a prescribed | |
| stop at a prescribed time. The stopping pattern is comprised of timetable values ordered by stopping order."''' | |
| # stoppingPattern(0,4780,1104) | |
| # /v2/mode/%@/run/%@/stop/%@/stopping-pattern?for_utc=%@&devid=%@&signature=%@ | |
| return callAPI("mode/%d/run/%d/stop/%d/stopping-pattern" % (modeFromString(mode), run, stop), | |
| {"for_utc": for_utc.isoformat()}) | |
| def stopsOnALine(mode,line): | |
| '''"The Stops on a Line API returns a list of all the stops for a requested line, ordered by location name. | |
| ''' | |
| # stopsOnALine(4,'1818') | |
| return callAPI("mode/%d/line/%d/stops-for-line" % (modeFromString(mode), line)) | |
| ### End official part. Now higher level functions. | |
| def modeFromString (modestr): | |
| # Allows you to pass string modes to the API rather than their 0,1,2,3 etc. | |
| #Mode: 0 Train (metropolitan) | |
| # 1 Tram | |
| # 2 Bus (metropolitan and regional, but not V/Line) | |
| # 3 V/Line train and coach | |
| # 4 NightRider | |
| if type(modestr) == type(0): | |
| return modestr | |
| return ['train','tram','bus','vline','nightrider'].index(modestr) | |
| def melbourneTime(isostr): | |
| from dateutil import parser, tz | |
| d = parser.parse(isostr) | |
| d.replace(tzinfo=tz.gettz('UTC')) # Not sure if needed | |
| return d.astimezone(tz.gettz('Australia/Melbourne')) | |
| def findThing(name, stoporline, transport_type=''): | |
| out = [] | |
| for x in search(name): | |
| if x['type'] != stoporline: | |
| continue | |
| r = x['result'] | |
| if transport_type not in ('', r['transport_type']): | |
| continue | |
| r.pop('distance',None) | |
| out += [r] | |
| return out | |
| def findLine(name, transport_type=''): | |
| return findThing(name, 'line', transport_type) | |
| def findStop(name, transport_type=''): | |
| return findThing(name, 'stop', transport_type) | |
| # --------------- Helpers that build all of the responses ---------------------- | |
| def build_speechlet_response(title, output, should_end_session): | |
| return { | |
| 'outputSpeech': { | |
| 'type': 'PlainText', | |
| 'text': output | |
| }, | |
| 'card': { | |
| 'type': 'Simple', | |
| 'title': title, | |
| 'content': output | |
| }, | |
| 'shouldEndSession': should_end_session | |
| } | |
| def build_response(session_attributes, speechlet_response): | |
| return { | |
| 'version': '1.0', | |
| 'sessionAttributes': session_attributes, | |
| 'response': speechlet_response | |
| } | |
| # --------------- Functions that control the skill's behavior ------------------ | |
| 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 to Melbourne Timetable" | |
| speech_output = "Ask me for the next train leaving Richmond" | |
| # 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 = "Ask me for the next train leaving Richmond" | |
| should_end_session = False | |
| return build_response(session_attributes, build_speechlet_response( | |
| card_title, speech_output, should_end_session)) | |
| def handle_session_end_request(): | |
| card_title = "Session Ended" | |
| speech_output = "Good bye" | |
| # 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 help_intent(intent, session): | |
| session_attributes = {} | |
| should_end_session = False | |
| card_title = "Melbourne Timetable Help" | |
| speech_output = "Try saying. When is the next train leaving Richmond." | |
| return build_response(session_attributes, build_speechlet_response( | |
| card_title, speech_output, should_end_session)) | |
| def getNext5(intent, session): | |
| """ Sets the color in the session and prepares the speech to reply to the | |
| user. | |
| """ | |
| card_title = "Get next 5 services" | |
| session_attributes = {} | |
| should_end_session = True | |
| print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$") | |
| print(intent) | |
| if 'Stop' in intent['slots']: | |
| if 'value' not in intent['slots']['Stop']: | |
| speech_output = "I'm not sure what station you want. " \ | |
| "Please try again." | |
| return build_response(session_attributes, build_speechlet_response( | |
| card_title, speech_output, should_end_session)) | |
| Stop = intent['slots']['Stop']['value'] | |
| search_results = search(Stop) | |
| search_results = [x for x in search_results if x['type'] == 'stop'] | |
| search_results = [x for x in search_results if x['result']['route_type'] == 0] | |
| if len(search_results) > 0: | |
| speech_output = "From " + search_results[0]['result']['location_name'] +". \n" | |
| card_title = "Get next trains from " + Stop | |
| next_departing = broadNextDepartures(0,search_results[0]['result']['stop_id'] , 3) | |
| i = 0 | |
| for depart in next_departing: | |
| if (depart['time_realtime_utc']): | |
| time = depart['time_realtime_utc'] | |
| elif (depart['time_timetable_utc']): | |
| time = depart['time_timetable_utc'] | |
| else: | |
| continue | |
| print(time) | |
| destination = depart['run']['destination_name'] | |
| time = datetime.datetime.strptime( time, "%Y-%m-%dT%H:%M:%SZ" ) | |
| delta = time - datetime.datetime.now() | |
| if delta.total_seconds() < 0: | |
| continue | |
| print(delta) | |
| print(delta.total_seconds()) | |
| minutes = int(delta.total_seconds() / 60) | |
| if minutes == 1: | |
| speech_output += "Train to " + destination + " arriving in " + str(minutes) + " minute. \n" | |
| else: | |
| speech_output += "Train to " + destination + " arriving in " + str(minutes) + " minutes. \n" | |
| print(speech_output) | |
| i += 1 | |
| if i >4: | |
| break | |
| else: | |
| speech_output = "I don't know about that station yet." | |
| else: | |
| speech_output = "I'm not sure what station you want. " \ | |
| "Please try again." | |
| return build_response(session_attributes, build_speechlet_response( | |
| card_title, speech_output, should_end_session)) | |
| # --------------- Events ------------------ | |
| def on_session_started(session_started_request, session): | |
| """ Called when the session starts """ | |
| print("on_session_started requestId=" + session_started_request['requestId'] | |
| + ", sessionId=" + session['sessionId']) | |
| def on_launch(launch_request, session): | |
| """ Called when the user launches the skill without specifying what they | |
| want | |
| """ | |
| print("on_launch requestId=" + launch_request['requestId'] + | |
| ", sessionId=" + session['sessionId']) | |
| # Dispatch to your skill's launch | |
| return get_welcome_response() | |
| def on_intent(intent_request, session): | |
| """ Called when the user specifies an intent for this skill """ | |
| print("on_intent requestId=" + intent_request['requestId'] + | |
| ", sessionId=" + session['sessionId']) | |
| intent = intent_request['intent'] | |
| intent_name = intent_request['intent']['name'] | |
| # Dispatch to your skill's intent handlers | |
| if intent_name == "getnext": | |
| return getNext5(intent, session) | |
| elif intent_name == "AMAZON.HelpIntent": | |
| return help_intent(intent, session) | |
| elif intent_name == "AMAZON.StopIntent": | |
| return build_response({}, build_speechlet_response( | |
| "Melbourne Timetable", "Goodbye", True)) | |
| else: | |
| raise ValueError("Invalid intent") | |
| def on_session_ended(session_ended_request, session): | |
| """ Called when the user ends the session. | |
| Is not called when the skill returns should_end_session=true | |
| """ | |
| print("on_session_ended requestId=" + session_ended_request['requestId'] + | |
| ", sessionId=" + session['sessionId']) | |
| # add cleanup logic here | |
| # --------------- Main handler ------------------ | |
| def lambda_handler(event, context): | |
| """ Route the incoming request based on type (LaunchRequest, IntentRequest, | |
| etc.) The JSON body of the request is provided in the event parameter. | |
| """ | |
| print(event) | |
| print("event.session.application.applicationId=" + | |
| event['session']['application']['applicationId']) | |
| """ | |
| Uncomment this if statement and populate with your skill's application ID to | |
| prevent someone else from configuring a skill that sends requests to this | |
| function. | |
| """ | |
| # if (event['session']['application']['applicationId'] != | |
| # "amzn1.echo-sdk-ams.app.[unique-value-here]"): | |
| # raise ValueError("Invalid Application ID") | |
| if event['session']['new']: | |
| on_session_started({'requestId': event['request']['requestId']}, | |
| event['session']) | |
| if event['request']['type'] == "LaunchRequest": | |
| return on_launch(event['request'], event['session']) | |
| elif event['request']['type'] == "IntentRequest": | |
| return on_intent(event['request'], event['session']) | |
| elif event['request']['type'] == "SessionEndedRequest": | |
| return on_session_ended(event['request'], event['session']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment