Exemple #1
0
def handler(event, context):
    event_results = event["res"]["result"]
    sport_type = event_results["args"][0]
    team_endpoint = feedparser.parse(
        'http://www.slubillikens.com/rss.dbml?db_oem_id=27200&media=results&RSS_SPORT_ID={}'
        .format(sport_type))
    print(team_endpoint)
    if team_endpoint.get('feed') and team_endpoint.get('entries'):
        game_information = team_endpoint['entries'][0]['title']

        outcome = game_information[-7]
        if outcome == 'L':
            game_response = game_information.replace('L', 'Lost')
        elif outcome == 'W':
            game_response = game_information.replace('W', 'Won')
        elif outcome == 'T':
            game_response = game_information.replace('T', 'Tied')
        else:
            qnalib.ssml_response(event, spoken_response(game_information))
            event['res'][
                'message'] = "I am Unable to retreive the results for the scores right now. Please visit slubillikens.com for results on all sporting events."
            return event

        qnalib.markdown_response(event, game_response)
        qnalib.ssml_response(event, spoken_response(game_information))
        qnalib.text_response(event, game_response)

    else:

        event['res'][
            'message'] = "I am Unable to retreive the results for the scores right now. Please visit slubillikens.com for results on all sporting events."

    return event
Exemple #2
0
def lambda_handler(event, context):

    event_results = event["res"]["result"]
    dietary_argument = event_results["args"][0]
    meal_argument = event_results["args"][1]

    try:
        allergen_argument = event_results["args"][2]
    except IndexError:
        allergen_argument = None

    print(meal_argument)
    print(allergen_argument)

    sodexo_endpoint = requests.get(
        "http://api-staging.sodexomyway.net/api/menus/13341001/14759/{}/{}".
        format(dietary_argument, allergen_argument))
    try:
        sodexo_endpoint.raise_for_status()
    except Exception as exc:
        event['res'][
            'message'] = "Unable to locate the information at this time, please try again"
        return (event)

    menu_items = sodexo_endpoint.json()
    print(json.dumps(event))

    meals = []
    for item in menu_items['data']['menuItems']:
        if item['Meal'].lower() == meal_argument.lower():
            meals.append(item['Name'])

    ssml = ""
    if allergen_argument:
        markdown = "| Grand Dining Hall {} Free {} Items |\n|------------|-------|".format(
            allergen_argument.capitalize(), meal_argument.capitalize())
    else:
        markdown = "| Grand Dining Hall {} {} Items |\n|------------|-------|".format(
            dietary_argument.capitalize(), meal_argument.capitalize())

    for i in meals:
        markdown += "\n| {}      |".format(i)
        ssml += " and {}".format(i)

    qnalib.markdown_response(event, markdown)

    if allergen_argument:
        allergen_response = written_allergen(meals, meal_argument,
                                             allergen_argument)
        qnalib.text_response(event, allergen_response)
        qnalib.ssml_response(event, allergen_response)

    else:
        written_response = written_restriction(meals, meal_argument,
                                               dietary_argument)
        qnalib.text_response(event, written_response)
        qnalib.ssml_response(event, written_response)

    return event
Exemple #3
0
def handler(event, context):
    driver = webdriver.Chrome(chrome_options=chrome_options)
    page_data = ""
    if event["res"]["result"]["args"][0]:
        driver.get(event["res"]["result"]["args"][0])
        page_data = driver.page_source
        bs_object = BeautifulSoup(page_data, 'html.parser')
        result = bs_object.find_all(lambda tag: tag.name == 'div' and tag.get(
            'class') == ['dining-halls-container'])
        restaurants = []
        for i in result:
            dining_div = i.find_all(
                "div", {"class": "dining-halls-block-left desktop-only"})
            for i in dining_div:
                dining_title = i.find("a",
                                      {"href": re.compile("/dining-near-me")})
                if dining_title:
                    dining_names = getattr(dining_title, 'contents', False)
                    if dining_names:
                        dining_name = dining_names[0]
                        if '@' in dining_name:
                            new_dining_name = dining_name.split('@')
                            restaurants.append(new_dining_name[0][:-1])
                        else:
                            restaurants.append(dining_name)

#Markdown response flow
    if restaurants:
        markdown = "| Restaurants Currently Open |\n|------------|-------|"
        for i in restaurants:
            markdown += "\n| {}      |".format(i)
    else:
        markdown = "There are currently no restaurants open right now."

#Text and SSML response flow
    if len(restaurants) == 0:
        response = "There are currently no restaurants open right now."
    elif len(restaurants) == 1:
        response_message = "The following restaurant is currently open: "
        response = response_message + "".join(str(x) for x in restaurants)
    else:
        restaurants.insert(-1, ' and ')
        response_message = "The following restaurants are currently open: "
        response = response_message + ", ".join(
            str(x) for x in restaurants[:-2]) + " ".join(
                str(x) for x in restaurants[-2:])

    qnalib.markdown_response(event, markdown)
    qnalib.text_response(event, response)
    qnalib.ssml_response(event, response)

    driver.close()
    return event
def handler(event, context):

    print(json.dumps(event))

    # - Extracting the stop name from the event args (This is set in the content designer, and must match case)
    stopName = event["res"]["result"]["args"][0]

    # - Query DynamoDB for the stop ID, which we will use to query the doublemap API.
    stopID = getStopIDfromName(stopName)

    # - Query the ETA service with the requested Stop.
    etas = getETAfromStopID(stopID)

    response = ''

    markdown = "|  |{}|\n|:------------|:-----------------:|-------:|\n|   Bus # |   Bus Route  |ETA |".format(
        stopName)

    # - Construct the ETA Message for each arrival returned by the API.
    for arrivals in etas:
        if arrivals['bus']:
            markdown += "\n|    {}      |  {}      | {}      |".format(
                getBusNamebyID(arrivals['bus']),
                getRouteNamebyID(arrivals['route']), arrivals['avg'])
            response = response + (
                "Bus {} traveling on route {} will arrive in approximately {} minutes. "
                .format(str(getBusNamebyID(arrivals['bus'])),
                        str(getRouteNamebyID(arrivals['route'])),
                        str(arrivals['avg'])))

    # - Set the response message in the event object, and return the event.

    if response:

        ssml = response
        text = response + "Bus scheduling information can be found here: https://bit.ly/319ECfO"
        qnalib.markdown_response(event, markdown)
        qnalib.text_response(event, text)
        qnalib.ssml_response(event, ssml)

    else:
        inactive_route_text = "No buses are currently scheduled for this stop. bus stop information can be found here: https://bit.ly/319ECfO "
        inactive_route_ssml = "No buses are currently scheduled for this stop."

        qnalib.markdown_response(event, inactive_route_text)
        qnalib.text_response(event, inactive_route_text)
        qnalib.ssml_response(event, inactive_route_ssml)

    return event
def handler(event, context):
    event_results = event["res"]["result"]
    sport_type = event_results["args"][0]
    team_endpoint = feedparser.parse(
        'http://www.slubillikens.com/rss.dbml?db_oem_id=27200&media=schedulesxml&RSS_SPORT_ID={}'
        .format(sport_type))
    print(team_endpoint)
    if team_endpoint.get('feed') and team_endpoint.get('entries'):
        return_message = date_conversion(team_endpoint)
        qnalib.markdown_response(event, return_message)
        qnalib.text_response(event, return_message)
        qnalib.ssml_response(event, return_message)

        return event

    else:
        event['res'][
            'message'] = "Cannot locate schedule at this time. Please visit slubillikens.com for full sports schedule information."
        return event
Exemple #6
0
def handler(event, context):
    schedule_endpoint = feedparser.parse(
        'http://www.slubillikens.com/rss.dbml?db_oem_id=27200&media=schedulesxml&RSS_SPORT_ID='
    )
    if schedule_endpoint.get('feed') and schedule_endpoint.get('entries'):
        response_list = []
        count = 0
        for i in schedule_endpoint['entries']:
            if i['homeaway'] == 'H' and len(response_list) < 5:
                game_information = date_conversion(i)
                response_list.append(game_information)

        spoken_response_list = response_list.copy()
        response_string = ''
        markdown = "| | Upcoming Home Games |\n|:------------|:-----------------:|:-------:|\n|   Team |   Opponent  |Date |"
        for i in response_list:
            print(type(i))
            markdown += "\n|    {}      |  {}      | {} {} {}     |".format(
                i['team_name'], i['opponent_name'], i['day'], str(i['date']),
                str(i['time']))
        for i in spoken_response_list:
            response_string += "The SLU {} team will play {} on {} {} at {} .".format(
                i['team_name'], i['opponent_name'], i['day'], str(i['date']),
                str(i['time']))

        qnalib.markdown_response(event, markdown)
        qnalib.text_response(event, response_string)
        qnalib.ssml_response(event, response_string)
        print(response_string)

        return event

    else:
        event['res'][
            'message'] = "Cannot locate schedule at this time. Please visit slubillikens.com for full sports schedule information."
        return event
def handler(event, context):
    global token

    event_results = event["res"]["result"]
    dietary_argument = event_results["args"][0]
    meal_argument = event_results["args"][1]

    try:
        allergen_argument = event_results["args"][2]
    except IndexError:
        allergen_argument = None

    #if token is expired fetch a new one
    if time.time() > token['expiration']:
        token = fetch_token(password)

    sodexo_endpoint = requests.get(
        "http://api-staging.sodexomyway.net/api/v1/menus/13341001/14759/{}/{}".
        format(dietary_argument, allergen_argument),
        headers={'Authorization': 'Bearer ' + token['tokenValue']})
    try:
        sodexo_endpoint.raise_for_status()
    except Exception as exc:
        event['res'][
            'message'] = "Unable to locate the information at this time, please try again"
        return (event)

    menu_items = sodexo_endpoint.json()
    print(json.dumps(event))

    meals = []
    for item in menu_items['data']['menuItems']:
        if item['Meal'].lower() == meal_argument.lower():
            meals.append(item['Name'])

    ssml = ""
    if allergen_argument:
        markdown = "| Grand Dining Hall {} Free {} Items |\n|------------|-------|".format(
            allergen_argument.capitalize(), meal_argument.capitalize())
    else:
        markdown = "| Grand Dining Hall {} {} Items |\n|------------|-------|".format(
            dietary_argument.capitalize(), meal_argument.capitalize())

    if meals:
        for i in meals:
            markdown += "\n| {}      |".format(i)
            ssml += " and {}".format(i)

        #response objects
        qnalib.markdown_response(event, markdown)
        if allergen_argument:
            allergen_response = written_allergen(meals, meal_argument,
                                                 allergen_argument)
            qnalib.text_response(event, allergen_response)
            qnalib.ssml_response(event, allergen_response)

        else:
            written_response = written_restriction(meals, meal_argument,
                                                   dietary_argument)
            qnalib.text_response(event, written_response)
            qnalib.ssml_response(event, written_response)

        return event
    else:
        event['res'][
            'message'] = "There are currently no meals that meet this criteria"
        return event
Exemple #8
0
def handler(event, context):
    print("start of new function ##########################################")
    print(json.dumps(event))
    response = ''
    event_results = event["res"]["result"]
    building_arg = event_results["args"][0]
    question_utterance = event["req"]["question"]
    initialmessage = ''
    my_date = date.today()
    central_object = timezone('US/Central')
    central_time = central_object.fromutc(dt.now())
    todaysDay = calendar.day_name[central_time.weekday()]
    dayOfWeek = searchUtteranceforDoW(question_utterance)

    
    if(dayOfWeek == None): 
        dayOfWeek = todaysDay
    elif(dayOfWeek == "Tomorrow"):
        dayOfWeek = calendar.day_name[(central_time + datetime.timedelta(days=1)).weekday()]
    

    
    # - Extracting the building name from the event args (This is set in the content designer, and must match case)
    buildingName = event["res"]["result"]["args"][0]
    
    # - Query DynamoDB for the stop ID, which we will use to query the doublemap API.
    buildingID = getBuildingIDfromName(buildingName)
    day_in_dt = day_to_dt_converter(todaysDay,dayOfWeek,central_time)
    scheduleID = getScheduleIDfromBuildingID(buildingID,day_in_dt)
    day_query = getDaysfromScheduleID(scheduleID,dayOfWeek)
    if isinstance(day_query, list):
        queried_day = day_query[0]
    else:
        queried_day = day_query
        


        
    
    if queried_day == "unavailable" and todaysDay == dayOfWeek:
        initialmessage = "I cant find the hours for the {} building today.\n".format(buildingName)
    elif queried_day == "unavailable":
        initialmessage = "I cant find the hours for the {} building on {}. \n".format(buildingName,dayOfWeek)
        
    elif(queried_day['isclosed'] and todaysDay == dayOfWeek):
        initialmessage = "Today the {} is closed\n ".format(buildingName)
        
    elif queried_day['isclosed']:
        initialmessage = "On {} the {} is closed\n ".format(str(expandDayfromShortName(queried_day['days'])), buildingName)
        
    elif todaysDay == dayOfWeek:
        initialmessage = "Today the {} is open from {} to {}\n".format(buildingName, dt.strptime(str(queried_day['open']), '%H:%M').strftime('%I:%M %p'), dt.strptime(str(queried_day['closed']), '%H:%M').strftime('%I:%M %p'))
    else:
        initialmessage = "On {} the {} is open from {} to {}\n".format(str(expandDayfromShortName(queried_day['days'])), buildingName, dt.strptime(str(queried_day['open']), '%H:%M').strftime('%I:%M %p'), dt.strptime(str(queried_day['closed']), '%H:%M').strftime('%I:%M %p'))
    
    
    # - Initialize the markdown values.
    markdown = ''
    if event["req"]["_type"] != "ALEXA" and event["req"]["_event"]["requestAttributes"] == None:
        weekday_dict = dict(zip(calendar.day_name,range(7)))
        todays_number = weekday_dict[dayOfWeek]
        for i in range(todays_number,todays_number + 7):
            dt_object = day_to_dt_converter(todaysDay,i,central_time)
            week_schedule_id = getScheduleIDfromBuildingID(buildingID,dt_object)
            dt_weekday = calendar.day_name[dt_object.weekday()]
            week_object = getDaysfromScheduleID(week_schedule_id,dt_weekday)
            if isinstance(week_object, list):
                if week_object and week_object[0]['isclosed']:
                    markdown +=    "\n|    {0}      |  Closed      | Closed      |".format(dt_weekday)
                else:
                    markdown +=    "\n|    {0}      |  {1} &nbsp; &nbsp; &nbsp; &nbsp;    | {2}      |".format(dt_weekday, dt.strptime(str(week_object[0]['open']), '%H:%M').strftime('%I:%M %p'), dt.strptime(str(week_object[0]['closed']), '%H:%M').strftime('%I:%M %p'))
        if markdown:
            markdown = "|   Day  |   Opens  |Closes |\n|:------------|:-----------------:|-------:|" + markdown

    response =  initialmessage 
    
    # - Set the response message in the event object, and return the event.
    
    if response and markdown:
        markdown = "{} \n{}".format(initialmessage, markdown)
        qnalib.markdown_response(event,markdown)
    elif response:
        ssml = response 
        text = response 
        qnalib.text_response(event,text)
        qnalib.ssml_response(event,ssml)
    
    elif markdown:
        qnalib.markdown_response(event,inactive_building_text) 
    else:
        inactive_building_text = "Building open hours can be found here http://slu.edu"
        inactive_schedule_ssml = "No buildings are open today"
        qnalib.text_response(event,inactive_building_text)
        qnalib.ssml_response(event,inactive_schedule_ssml)
        
        

    return event