Exemple #1
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        _ = handler_input.attributes_manager.request_attributes["_"]
        logger.info("In CancelSubscriptionHandler")

        in_skill_response = in_skill_product_response(handler_input)
        if in_skill_response:
            product_name = get_resolved_value(
                handler_input.request_envelope.request, "productName")

            # No entity resolution match
            if product_name is None:
                product_name = "私のサンタクロースのプレミアム機能"
            else:
                product_name = "私のサンタクロースのプレミアム機能"

            product = [
                l for l in in_skill_response.in_skill_products
                if l.reference_name == product_name
            ]
            return handler_input.response_builder.add_directive(
                SendRequestDirective(name="Cancel",
                                     payload={
                                         "InSkillProduct": {
                                             "productId": product[0].product_id
                                         }
                                     },
                                     token="correlationToken")).response
Exemple #2
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In CancelSubscriptionHandler")

        in_skill_response = in_skill_product_response(handler_input)
        if in_skill_response:
            product_category = get_resolved_value(
                handler_input.request_envelope.request, "productCategory")

            # No entity resolution match
            if product_category is None:
                product_category = "all_access"
            else:
                product_category += "_pack"

            product = [
                l for l in in_skill_response.in_skill_products
                if l.reference_name == product_category
            ]
            return handler_input.response_builder.add_directive(
                SendRequestDirective(name="Cancel",
                                     payload={
                                         "InSkillProduct": {
                                             "productId": product[0].product_id
                                         }
                                     },
                                     token="correlationToken")).response
Exemple #3
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        _ = handler_input.attributes_manager.request_attributes["_"]
        logger.info("In BuyHandler")

        # Inform the user about what products are available for purchase
        in_skill_response = in_skill_product_response(handler_input)
        if in_skill_response:
            product_name = get_resolved_value(
                handler_input.request_envelope.request, "productName")

            # No entity resolution match
            if product_name is None:
                product_name = "パパの目安箱のプレミアム機能"
            else:
                product_name = "パパの目安箱のプレミアム機能"

            product = [
                l for l in in_skill_response.in_skill_products
                if l.reference_name == product_name
            ]
            return handler_input.response_builder.add_directive(
                SendRequestDirective(name="Buy",
                                     payload={
                                         "InSkillProduct": {
                                             "productId": product[0].product_id
                                         }
                                     },
                                     token="correlationToken")).response
    def handle(self, handler_input: HandlerInput):
        in_skill_response = util.in_skill_product_response(handler_input)
        if not in_skill_response:
            handler_input.response_builder.set_should_end_session(True)
            return handler_input.response_builder.speak('現在購入できる商品がございません。')

        purchasable_products = util.get_speakable_products(in_skill_response)
        speech = f'現在購入可能な商品は、{purchasable_products}です。' \
            f'詳しく知りたい場合には、ジェムパック大について教えて、のように言ってください。'
        handler_input.response_builder.speak(speech)

        skill_product = util.get_skill_product(
            in_skill_response, 'gem_1000')

        return handler_input.response_builder.add_directive(
            SendRequestDirective(
                name='Buy',
                payload={
                    'InSkillProduct': {
                        'productId': skill_product.product_id
                    }
                },
                token='correlationToken'
            )
        ).response
    def handle(self, handler_input):
        in_skill_response = util.in_skill_product_response(handler_input)
        if not in_skill_response:
            handler_input.response_builder.speak('現在購入できる商品はございません。')
            handler_input.response_builder.set_should_end_session(True)
            return handler_input.response_builder.response

        purchase_product = util.get_purchase_product(
            handler_input, 'product_category')
        if not purchase_product:
            speech_text = 'すみません、分かりませんでした。'
            ask = 'もう一度お願いできますか?'
            handler_input.response_builder.speak(speech_text + ask).ask(
                ask).set_should_end_session(False)
            return handler_input.response_builder.response

        skill_product = util.get_skill_product(
            in_skill_response, purchase_product.id)

        handler_input.response_builder.speak(skill_product.summary)
        return handler_input.response_builder.add_directive(
            SendRequestDirective(
                name='Buy',
                payload={
                    'InSkillProduct': {
                        'productId': skill_product.product_id
                    }
                },
                token='correlationToken'
            )
        ).response
    def handle(self, handler_input):
        in_skill_response = util.in_skill_product_response(handler_input)
        if not in_skill_response:
            handler_input.response_builder.speak('現在その商品は購入していません。')
            handler_input.response_builder.set_should_end_session(True)
            return handler_input.response_builder.response

        purchase_product = util.get_purchase_product(
            handler_input, 'product_category')

        if not purchase_product:
            handler_input.response_builder.speak('現在その商品は、スキル内で提供していません。')
            handler_input.response_builder.set_should_end_session(True)
            return handler_input.response_builder.response

        skill_product = util.get_skill_product(
            in_skill_response, purchase_product.id)

        handler_input.response_builder.speak(skill_product.summary)
        return handler_input.response_builder.add_directive(
            SendRequestDirective(
                name='Cancel',
                payload={
                    'InSkillProduct': {
                        'productId': skill_product.product_id
                    }
                },
                token='correlationToken'
            )
        ).response
Exemple #7
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        # Obtain the corresponding product_id for the requested in-skill
        # product by invoking InSkillProducts API.
        # The slot variable product_name used below is only for demonstration.

        locale = handler_input.request_envelope.request.locale
        ms = handler_input.service_client_factory.get_monetization_service()

        product_response = ms.get_in_skill_products(locale)
        slots = handler_input.request_envelope.request.intent.slots
        product_ref_name = slots.get("product_name").value
        product_record = [
            l for l in product_response.in_skill_products
            if l.reference_name == product_ref_name
        ]

        if product_record:
            return handler_input.response_builder.add_directive(
                SendRequestDirective(name="Buy",
                                     payload={
                                         "InSkillProduct": {
                                             "productId":
                                             product_record[0].product_id
                                         }
                                     },
                                     token="correlationToken")).response
        else:
            return handler_input.response_builder.speak(
                "I am sorry. That product is not available for purchase"
            ).response
Exemple #8
0
def refund_intent_handler(handler_input):
    attr = handler_input.attributes_manager.session_attributes
    persAttr = handler_input.attributes_manager.persistent_attributes

    try:
        userProduct = handler_input.request_envelope.request.intent.slots[
            "product"]
        productName = userProduct.value.lower().replace(" ", "")
    except:
        productName = ""

    products = in_skill_product_response(handler_input)
    product = None
    persAttr["livesToAdd"] = 0
    if "10" in productName:
        product = products.in_skill_products[2]
        persAttr["livesToAdd"] = -10
    elif "20" in productName:
        product = products.in_skill_products[1]
        persAttr["livesToAdd"] = -20
    elif "single" in productName or "one" in productName or "extralife" in productName:
        product = products.in_skill_products[0]
        persAttr["livesToAdd"] = -1

    handler_input.attributes_manager.save_persistent_attributes()
    return handler_input.response_builder.add_directive(
        SendRequestDirective(
            name="Cancel",
            payload={"InSkillProduct": {
                "productId": product.product_id
            }},
            token="correlationToken")).response
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        #retrieve ISP products on session
        try:
            #list of products associated to the skill
            isp_response = get_isp_products(handler_input)
            response_builder = handler_input.response_builder

            #check to see if user has a previously purchased a travel tip
            if is_user_entitled(isp_response):
                #if yes, let them use it
                tip_for_question = get_tip_for_question(
                    handler_input.attributes_manager.
                    session_attributes["country"], handler_input.
                    attributes_manager.session_attributes["stats_record"],
                    handler_input)
                next_question = get_next_question(
                    handler_input.attributes_manager.
                    session_attributes["country"], handler_input.
                    attributes_manager.session_attributes["stats_record"],
                    handler_input)
                speak_output = "<voice name=\"" + get_polly_voice(
                    handler_input.attributes_manager.
                    session_attributes["country"]
                ) + "\">Hello adventurer! " + tip_for_question + "</voice> " + next_question
                reprompt_output = "<voice name=\"" + get_polly_voice(
                    handler_input.attributes_manager.
                    session_attributes["country"]
                ) + "\"> Adventurer, don't hesistate! " + tip_for_question + "</voice> " + next_question
                include_display(handler_input)

                return (response_builder.speak(speak_output).ask(
                    reprompt_output).response)
            else:
                #if not, upsell (sell) it to them
                upsell_msg = (
                    "You don't currently own {}. Want to learn more?").format(
                        isp_response.in_skill_products[0].summary)
                include_display(handler_input)

                return response_builder.add_directive(
                    SendRequestDirective(
                        name="Upsell",
                        payload={
                            "InSkillProduct": {
                                "productId":
                                isp_response.in_skill_products[0].product_id,
                            },
                            "upsellMessage": upsell_msg,
                        },
                        token="correlationToken")).response
        except:
            logger.error(
                "An error in SpeakToGuideIntentHandler for text type {} ".
                format(handler_input))
            speak_output = "A tip is not available at this time. Make sure that you are in active game play. Say visit Italy or visit Australia"
            reprompt_output = "Would you like to visit Italy or Australia?"
            return (response_builder.speak(speak_output).ask(
                reprompt_output).response)
Exemple #10
0
def set_up_amazon_pay(self, handler_input, charity_name):
    '''Customer has shown intent to purchase, call Setup to grab the customers shipping address detail and check amazon pay is set up'''
    # type: (HandlerInput, String) -> Response
    logger.info("In set_up_amazon_pay")

    # Permission check
    if is_missing_amazon_pay_permission(self, handler_input) is False:
        logger.info("Is FALSE")
        handler_input.response_builder.speak(data.PERMISSION_DENIED).set_card(
            AskForPermissionsConsentCard(['payments:autopay_consent'
                                          ])).set_should_end_session(True)
        return handler_input.response_builder.response
    logger.info("In set_up_amazon_pay again")

    foo = handler_input.request_envelope.request.locale

    token = 'correlationToken'

    message = data.DONATION_MADE_SPEECH + charity_name + " for " + \
        str(amount_donated) + " dollars. Should I process your payment now?"
    # logger.info(message)
    logger.info("Before Sending Setup Directive")
    handler_input.response_builder.add_directive(
        SendRequestDirective(name="Setup",
                             payload={
                                 '@type': 'SetupAmazonPayRequest',
                                 '@version': '2',
                                 'sellerId': 'A2G5K08S7KTD5R',
                                 'countryOfEstablishment': 'US',
                                 'ledgerCurrency': 'USD',
                                 'checkoutLanguage': 'en-US',
                                 'sandboxCustomerEmailId':
                                 '*****@*****.**',
                                 'sandboxMode': True,
                                 'needAmazonShippingAddress': True,
                                 'billingAgreementAttributes': {
                                     '@type':
                                     'BillingAgreementAttributes',
                                     '@version':
                                     '2',
                                     'sellerNote':
                                     'Thanks for your donation to ' +
                                     charity_name,
                                     'platformId':
                                     None,
                                     'sellerBillingAgreementAttributes': {
                                         '@type':
                                         'SellerBillingAgreementAttributes',
                                         '@version': '2',
                                         'sellerBillingAgreementId': 'BA12345',
                                         'storeName': charity_name,
                                         'customInformation': ''
                                     }
                                 }
                             },
                             token="correlationToken"))
    handler_input.response_builder.speak(message)
    return handler_input.response_builder.response
Exemple #11
0
 def handle(self, handler_input):
     # type: (HandlerInput) -> Response
     planet_story.previous_speech_text = planet_story.speech_text
     return handler_input.response_builder.add_directive(
         SendRequestDirective(
             name="Buy",
             payload={
                 "InSkillProduct": {
                     "productId":
                     'amzn1.adg.product.0be04a0c-2fb5-4763-acd0-f370dbafa339'
                 }
             },
             token="correlationToken")).response
def get_speak_ask_upsell_response(handler_input):
    handler_input.response_builder.speak(planet_story.speech_text).ask(
        planet_story.reprompt
    ).add_directive(
        SendRequestDirective(
            name="Upsell",
            payload={
                "InSkillProduct": {
                    "productId":
                    'amzn1.adg.product.9881949f-e95d-4e03-a790-885468e8b080'
                },
                "upsellMessage": 'This is a test upsell'
            },
            token="correlationToken"))
    return handler_input.response_builder.response
 def handle(self, handler_input):
     response_builder = handler_input.response_builder
     isp_response = get_isp_products(handler_input)
     include_display(handler_input)
                     
     return response_builder.add_directive(
             SendRequestDirective(
                 name="Cancel",
                 payload={
                     "InSkillProduct": {
                         "productId": isp_response.in_skill_products[0].product_id
                     }
                 },
                         token="correlationToken")
                 ).response
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        planet_story.previous_speech_text = planet_story.speech_text

        product_name = get_slot_value_from_handler(handler_input,
                                                   slot_name=Slots.PRODUCT)

        return handler_input.response_builder.add_directive(
            SendRequestDirective(
                name="Buy",
                payload={
                    "InSkillProduct": {
                        "productId":
                        'amzn1.adg.product.9881949f-e95d-4e03-a790-885468e8b080'
                    }
                },
                token="correlationToken")).response
Exemple #15
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Union[None, Response]
        logger.info('In BuyHandler')

        in_skill_response = utils.in_skill_product_resposne(handler_input)
        if in_skill_response:
            product = [
                l for l in in_skill_response.in_skill_products
                if l.reference_name == 'better_water'
            ]
            return handler_input.response_builder.add_directive(
                SendRequestDirective(name='Buy',
                                     payload={
                                         'InSkillProduct': {
                                             'productId': product[0].product_id
                                         }
                                     },
                                     token='correlationToken')).response
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In BuyHandler")

        # Inform the user about what products are available for purchase
        in_skill_response = in_skill_product_response(handler_input)
        if in_skill_response:
            product_category = "1000_cookies"

            product = [
                l for l in in_skill_response.in_skill_products
                if l.reference_name == product_category
            ]
            return handler_input.response_builder.add_directive(
                SendRequestDirective(name="Buy",
                                     payload={
                                         "InSkillProduct": {
                                             "productId": product[0].product_id
                                         }
                                     },
                                     token="correlationToken")).response
Exemple #17
0
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In CancelSubscriptionHandler")

        in_skill_response = in_skill_product_response(handler_input)
        if in_skill_response:
            product_category = "1000_cookies"

            # No entity resolution match

            product = [
                l for l in in_skill_response.in_skill_products
                if l.reference_name == product_category
            ]
            return handler_input.response_builder.add_directive(
                SendRequestDirective(name="Cancel",
                                     payload={
                                         "InSkillProduct": {
                                             "productId": product[0].product_id
                                         }
                                     },
                                     token="correlationToken")).response
Exemple #18
0
    def handle(self, handler_input):
        logger.info("In TimerIntent Handler")

        response_builder = handler_input.response_builder
        permissions = handler_input.request_envelope.context.system.user.permissions
        if not (permissions and permissions.consent_token):
            return response_builder.add_directive(
                SendRequestDirective(
                    name="AskFor",
                    payload= {
                        "@type": "AskForPermissionsConsentRequest",
                        "@version": "1",
                        "permissionScope": "alexa::alerts:timers:skill:readwrite"
                    },
                    token= "correlationToken"
                )
            ).response
        logger.info("Voice permission provided")
        timer_service = handler_input.service_client_factory.get_timer_management_service()
        timer_response = timer_service.create_timer(new_timer_request)
        logger.info("Timer created")
        
        if str(timer_response.status) == "Status.ON":
            session_attr = handler_input.attributes_manager.session_attributes
            if not session_attr:
                session_attr['lastTimerId'] = timer_response.id

            speech_text = 'Your 10 minutes timer has started!.'
        else:
            speech_text = 'Timer did not start'

        return (
            handler_input.response_builder
            .speak(speech_text)
            .response
        )
Exemple #19
0
def charge_amazon_pay(self, handler_input, charity_name, amount_donated):
    ''' Customer has requested checkout and wants to be charged'''
    # type: (HandlerInput, String, Integer) -> Response
    logger.info("In charge_amazon_pay")

    # Permission check
    if is_missing_amazon_pay_permission(self, handler_input) is False:
        handler_input.response_builder.speak(data.PERMISSION_DENIED).set_card(
            AskForPermissionsConsentCard(['payments:autopay_consent'
                                          ])).set_should_end_session(True)
        return handler_input.response_builder.response

    permissions = handler_input.request_envelope.context.system.user.permissions
    amazonPayPermission = permissions.scopes['payments:autopay_consent']

    logger.info("In charge_amazon_pay")
    logger.info(amazonPayPermission.status)

    # If you have a valid billing agreement from a previous session, skip the Setup action and call the Charge action instead
    token = 'correlationToken'

    # database query to get the total contribution made to the charity
    table_name = "CharityInfo"
    total_contribution = get_total_contribution(charity_id, table_name)

    # access the user spoken slot value for the amount of contribution
    total_contribution = total_contribution + int(amount_donated)

    # database query to update the total contribution
    update_total_contribution(charity_id, table_name, int(total_contribution))

    return handler_input.response_builder.add_directive(
        SendRequestDirective(name="Charge",
                             payload={
                                 '@type': 'ChargeAmazonPayRequest',
                                 '@version': '2',
                                 'sellerId': 'A2G5K08S7KTD5R',
                                 'billingAgreementId': 'C01-1108076-6653603',
                                 'paymentAction': 'AuthorizeAndCapture',
                                 'authorizeAttributes': {
                                     '@type':
                                     'AuthorizeAttributes',
                                     '@version':
                                     '2',
                                     'authorizationReferenceId':
                                     str(get_random_string(18)),
                                     'authorizationAmount': {
                                         '@type': 'Price',
                                         '@version': '2',
                                         'amount': str(amount_donated),
                                         'currencyCode': 'USD'
                                     },
                                     'transactionTimeout':
                                     0,
                                     'sellerAuthorizationNote':
                                     'Billing Agreement Seller Note',
                                     'softDescriptor':
                                     charity_name
                                 },
                                 'sellerOrderAttributes': {
                                     '@type':
                                     'SellerOrderAttributes',
                                     '@version':
                                     '2',
                                     'sellerOrderId':
                                     str(get_random_string(3)) + '-' +
                                     str(random.randrange(100, 999)) + '-' +
                                     str(random.randrange(100000, 999999)),
                                     'storeName':
                                     charity_name,
                                     'customInformation':
                                     '',
                                     'sellerNote':
                                     'Thanks for donating to ' + charity_name
                                 }
                             },
                             token="correlationToken")).response
    def handle(self, handler_input: HandlerInput) -> Response:
        session = handler_input.attributes_manager.session_attributes
        state = session.get('state')
        node = session.get('node')
        destinations_choice = session.get('destinations_choice')
        total_ticket_amount = session.get('total_ticket_amount')
        turn_times = session.get('turn_times')
        not_enough_gem = session.get('not_enough_gem')
        fof_sfn_input = {
            'alexa_user_id': handler_input.request_envelope.context.system.user.user_id,
            'IsPreResponse': False,
            'intent': 'AMAZON.YesIntent',
            'state': state,
            'node': node,
            'destinations_choice': destinations_choice,
            'total_ticket_amount': total_ticket_amount,
            'turn_times': turn_times,
            'not_enough_gem': not_enough_gem,
            'env_type': util.get_env_type(handler_input)
        }

        if node:
            fof_sfn_input['node'] = node
            if node == 'recommend_gem' or node == 'ask_gem_pack':
                in_skill_response = util.in_skill_product_response(
                    handler_input)

                product_name = session.get('product_name')
                skill_product = util.get_skill_product(
                    in_skill_response, product_name)

                return handler_input.response_builder.add_directive(
                    SendRequestDirective(
                        name='Buy',
                        payload={
                            'InSkillProduct': {
                                'productId': skill_product.product_id
                            }
                        },
                        token='correlationToken'
                    )
                ).response

        print(fof_sfn_input)
        response = sfn_ctl.execute(fof_sfn_input)

        if 'state' in response:
            session['state'] = response['state']

        if 'node' in response:
            session['node'] = response['node']

        if 'destinations_choice' in response:
            session['destinations_choice'] = response['destinations_choice']

        if 'turn_times' in response:
            session['turn_times'] = response['turn_times']

        if 'total_ticket_amount' in response:
            session['total_ticket_amount'] = response['total_ticket_amount']

        if 'product_name' in response:
            session['product_name'] = response['product_name']

        if 'not_enough_gem' in response:
            session['not_enough_gem'] = response['not_enough_gem']

        image_url = response.get('image_url')
        bg_image_url = response.get('bg_image_url')
        image_title = response.get('image_title')
        image_text = response.get('image_text')
        if image_url:
            img_obj = Image(sources=[ImageInstance(url=image_url)])
            bg_img_obj = Image(sources=[ImageInstance(url=bg_image_url)])
            if util.is_support_display(handler_input):
                handler_input.response_builder.add_directive(
                    RenderTemplateDirective(
                        BodyTemplate7(
                            back_button=BackButtonBehavior.VISIBLE,
                            image=img_obj,
                            background_image=bg_img_obj,
                            title='')
                    )
                )
            else:
                handler_input.response_builder.set_card(
                    ui.StandardCard(
                        title='',
                        text='',
                        image=ui.Image(
                            small_image_url=image_url,
                            large_image_url=image_url
                        )
                    )
                )

        speech_text = response["response_text"]
        handler_input.response_builder.speak(speech_text).ask(speech_text)
        return handler_input.response_builder.response
    def handle(self, handler_input: HandlerInput) -> Optional[Response]:
        session = handler_input.attributes_manager.session_attributes
        node = session.get('node')
        state = session.get('state')
        total_ticket_amount = session.get('total_ticket_amount')
        turn_times = session.get('turn_times')

        if state == 'ganesha':
            fof_sfn_input = {
                'alexa_user_id': handler_input.request_envelope.context.system.user.user_id,
                'IsPreResponse': False,
                'state': 'ganesha',
                'node': node,
                'total_ticket_amount': total_ticket_amount,
                'turn_times': turn_times,
                'env_type': util.get_env_type(handler_input)
            }
            response = sfn_ctl.execute(fof_sfn_input)

        else:
            fof_sfn_input = {
                'alexa_user_id': handler_input.request_envelope.context.system.user.user_id,
                'IsPreResponse': True,
                'state': state,
                'intent': 'UseIntent',
                'node': node,
                'env_type': util.get_env_type(handler_input)
            }
            response = sfn_ctl.execute(fof_sfn_input)

            if response.get('state') == 'Buy':
                in_skill_response = util.in_skill_product_response(
                    handler_input)

                product_name = session.get('product_name')
                skill_product = util.get_skill_product(
                    in_skill_response, product_name)

                return handler_input.response_builder.add_directive(
                    SendRequestDirective(
                        name='Buy',
                        payload={
                            'InSkillProduct': {
                                'productId': skill_product.product_id
                            }
                        },
                        token='correlationToken'
                    )
                ).response

        if 'state' in response:
            session['state'] = response['state']

        if 'node' in response:
            session['node'] = response['node']

        if 'destinations_choice' in response:
            session['destinations_choice'] = response['destinations_choice']

        if 'turn_times' in response:
            session['turn_times'] = response['turn_times']

        if 'total_ticket_amount' in response:
            session['total_ticket_amount'] = response['total_ticket_amount']

        speech_text = response["response_text"]
        handler_input.response_builder.speak(speech_text).ask(speech_text)
        return handler_input.response_builder.response
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response

        session_attr = handler_input.attributes_manager.session_attributes
        if "intent_history" in session_attr.keys():
            session_attr["intent_history"].append("CreateMealPlanIntent")
        else:
            session_attr["intent_history"] = [
                "Launch", "CreateMealPlanIntent", "CountrySelectorIntent"
            ]

        # country attribute
        selected_country = ask_utils.get_slot_value(handler_input, "country")
        logger.info("SELECTED COUNTRY = {}".format(selected_country))

        if selected_country.lower()[0:4] == "the ":
            selected_country_lower = selected_country[4:].lower()
        else:
            selected_country_lower = selected_country.lower()

        session_attr["country"] = selected_country_lower
        premium_countries = [
            text.lower() for text in alexa_responses.premium_countries
        ]

        # response to country selection - PREMIUM CONTENT
        if selected_country_lower in premium_countries:
            in_skill_response = in_skill_product_response(handler_input)

            if in_skill_response:
                product = [
                    l for l in in_skill_response.in_skill_products
                    if l.reference_name == "premium_content_onetime"
                ]
                logger.info("PRODUCT: {}".format(product))
                if is_entitled(product):
                    speak_output = "Here are recipes from {}.".format(
                        selected_country)
                    apl_document = _load_apl_document(
                        "./apl/{}.json".format(selected_country_lower))
                    return handler_input.response_builder.speak(
                        speak_output).response
                else:
                    upsell_msg = (
                        "This selection contains premium content. "
                        "You are not a premium member. Would you hear how to unlock premium content?"
                    )

                    return (handler_input.response_builder.add_directive(
                        SendRequestDirective(
                            name="Upsell",
                            payload={
                                "InSkillProduct": {
                                    "productId": product[0].product_id,
                                },
                                "upsellMessage": upsell_msg
                            },
                            token="correlationToken")).response)
        else:
            # response to country selection - FREE OR PAID UP CONTENT
            speak_output = "Here are recipes from {}.".format(selected_country)
            apl_document = _load_apl_document(
                "./apl/{}.json".format(selected_country_lower))

            return (handler_input.response_builder.speak(speak_output).ask(
                speak_output).add_directive(
                    RenderDocumentDirective(
                        token="selected_country",
                        document=apl_document["document"],
                        datasources=apl_document["datasources"])).response)
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("In GetCategoryFactHandler")

        fact_category = get_resolved_value(
            handler_input.request_envelope.request, 'factCategory')
        logger.info("FACT CATEGORY = {}".format(fact_category))

        if fact_category is not None:
            # If there was an entity resolution match for this slot value
            category_facts = [
                l for l in all_facts if l.get("type") == fact_category]
        else:
            # If there was not an entity resolution match for this slot value
            category_facts = []

        if not category_facts:
            slot_value = get_spoken_value(
                handler_input.request_envelope.request, "factCategory")
            if slot_value is not None:
                speak_prefix = "I heard you say {}.".format(slot_value)
            else:
                speak_prefix = ""
            speech = (
                "{} I don't have facts for that category.  You can ask for "
                "science, space or history facts.  Which one would you "
                "like?".format(speak_prefix))
            reprompt = (
                "Which fact category would you like?  I have science, space, "
                "or history.")
            return handler_input.response_builder.speak(speech).ask(
                reprompt).response
        else:
            in_skill_response = in_skill_product_response(handler_input)
            if in_skill_response:
                subscription = [
                    l for l in in_skill_response.in_skill_products
                    if l.reference_name == "all_access"]
                category_product = [
                    l for l in in_skill_response.in_skill_products
                    if l.reference_name == "{}_pack".format(fact_category)]

                if is_entitled(subscription) or is_entitled(category_product):
                    speech = "Here's your {} fact: {} {}".format(
                        fact_category, get_random_from_list(category_facts),
                        get_random_yes_no_question())
                    reprompt = get_random_yes_no_question()
                    return handler_input.response_builder.speak(speech).ask(
                        reprompt).response
                else:
                    upsell_msg = (
                        "You don't currently own the {} pack. {} "
                        "Want to learn more?").format(
                        fact_category, category_product[0].summary)
                    return handler_input.response_builder.add_directive(
                        SendRequestDirective(
                            name="Upsell",
                            payload={
                                "InSkillProduct": {
                                    "productId": category_product[0].product_id,
                                },
                                "upsellMessage": upsell_msg,
                            },
                            token="correlationToken")
                    ).response
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        logger.info("Reminder Intent handler")
        request_envelope = handler_input.request_envelope
        response_builder = handler_input.response_builder
        reminder_service = handler_input.service_client_factory.get_reminder_management_service(
        )

        if not (request_envelope.context.system.user.permissions and
                request_envelope.context.system.user.permissions.consent_token
                ):

            #return response_builder.speak(NOTIFY_MISSING_PERMISSIONS).set_card(AskForPermissionsConsentCard(permissions=PERMISSIONS)).response

            return response_builder.add_directive(
                SendRequestDirective(
                    name="AskFor",
                    payload={
                        "@type":
                        "AskForPermissionsConsentRequest",
                        "@version":
                        "1",
                        "permissionScope":
                        "alexa::alerts:reminders:skill:readwrite"
                    },
                    token="correlationToken")).response

        now = datetime.datetime.now(pytz.timezone(TIME_ZONE_ID))
        five_mins_from_now = now + datetime.timedelta(minutes=+5)
        notification_time = five_mins_from_now.strftime("%Y-%m-%dT%H:%M:%S")

        # Create an instance of the recurrence object

        # Set the missing attributes on the instance's deserialized_types map,
        # as following :
        recurrence_pattern = [
            "FREQ=DAILY;BYHOUR=6;BYMINUTE=10;BYSECOND=0;INTERVAL=1;",
            "FREQ=DAILY;BYHOUR=17;BYMINUTE=15;BYSECOND=0;INTERVAL=1;",
            "FREQ=DAILY;BYHOUR=19;BYMINUTE=45;BYSECOND=0;INTERVAL=1;"
        ]

        trigger = Trigger(
            object_type=TriggerType.SCHEDULED_ABSOLUTE,
            scheduled_time=notification_time,
            time_zone_id=TIME_ZONE_ID,
            recurrence=Recurrence(recurrence_rules=recurrence_pattern))
        text = SpokenText(
            locale='en-US',
            ssml="<speak> Great! I have scheduled reminder for you.</speak>",
            text='This is medicine reminder. Please take your medicine')
        alert_info = AlertInfo(SpokenInfo([text]))
        push_notification = PushNotification(PushNotificationStatus.ENABLED)
        reminder_request = ReminderRequest(notification_time, trigger,
                                           alert_info, push_notification)

        try:
            reminder_response = reminder_service.create_reminder(
                reminder_request)
            logger.info("Reminder Created: {}".format(reminder_response))
        except ServiceException as e:
            logger.info("Exception encountered: {}".format(e.body))
            return response_builder.speak(ERROR).response

        return response_builder.speak(
            "Your medicine reminder created").set_card(
                SimpleCard("Medicine Reminder",
                           "Medicine Reminder created")).response