Пример #1
0
    async def confirm_suspectedcasecontact_step(
        self, step_context: WaterfallStepContext
    ) -> DialogTurnResult:

        # Set the last contact date to a confirmed case to what they entered in response to the name prompt.
        self.FIRST_DATE = "value-firstDate"
        if step_context.result:
            step_context.values[self.FIRST_DATE] = str(step_context.result[0].value)
        else:
            step_context.values[self.FIRST_DATE] = None

        print("[DEBUG] First date is " + str(step_context.values[self.FIRST_DATE]))

        await step_context.context.send_activity(
            MessageFactory.text(
                "Finden wir heraus, ob Sie engen Kontakt zu einem Covid-19-Verdachtsfall hatten.")
        )
        #time.sleep(1)
        await step_context.context.send_activity(
            MessageFactory.text(
                f"Als enger Kontakt gilt Kontakt von Angesicht zu Angesicht länger als 15 Minuten, oder direkter, physischer Kontakt (Berührung, Händeschütteln, Küssen), oder Kontakt mit oder Austausch von Körperflüssigkeiten, oder Teilen einer Wohnung.")
        )
        #time.sleep(2)
        return await step_context.prompt(
            ChoicePrompt.__name__,
            PromptOptions(
                choices=[Choice("Ja"), Choice("Nein")],
                prompt=MessageFactory.text("Hatten Sie engen Kontakt zu einem **Covid-19-Verdachtsfall**?")
            ),
        )
    async def _select_delivery_mode_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """
        Render a prompt to select the delivery mode to use.
        """

        # Create the PromptOptions with the delivery modes supported.
        message_text = (str(step_context.options) if step_context.options else
                        "What delivery mode would you like to use?")
        retry_message_text = (
            "That was not a valid choice, please select a valid delivery mode."
        )

        options = PromptOptions(
            prompt=MessageFactory.text(message_text, message_text,
                                       InputHints.expecting_input),
            retry_prompt=MessageFactory.text(retry_message_text,
                                             retry_message_text,
                                             InputHints.expecting_input),
            choices=[
                Choice(DeliveryModes.normal.value),
                Choice(DeliveryModes.expect_replies.value),
            ],
        )

        # Prompt the user to select a delivery mode.
        return await step_context.prompt(DELIVERY_MODE_PROMPT, options)
Пример #3
0
    async def _show_choices(self, turn_context: TurnContext):
        choices = [
            Choice(
                value=QUICK_REPLIES_OPTION,
                action=CardAction(
                    title=QUICK_REPLIES_OPTION,
                    type=ActionTypes.post_back,
                    value=QUICK_REPLIES_OPTION,
                ),
            ),
            Choice(
                value=FACEBOOK_PAGEID_OPTION,
                action=CardAction(
                    title=FACEBOOK_PAGEID_OPTION,
                    type=ActionTypes.post_back,
                    value=FACEBOOK_PAGEID_OPTION,
                ),
            ),
            Choice(
                value=POSTBACK_OPTION,
                action=CardAction(
                    title=POSTBACK_OPTION,
                    type=ActionTypes.post_back,
                    value=POSTBACK_OPTION,
                ),
            ),
        ]

        message = ChoiceFactory.for_channel(
            turn_context.activity.channel_id,
            choices,
            "What Facebook feature would you like to try? Here are some quick replies to choose from!",
        )
        await turn_context.send_activity(message)
    async def test_should_recognize_and_use_custom_locale_dict(self, ):
        async def exec_test(turn_context: TurnContext):
            dialog_context = await dialogs.create_context(turn_context)

            results: DialogTurnResult = await dialog_context.continue_dialog()

            if results.status == DialogTurnStatus.Empty:
                options = PromptOptions(prompt=Activity(
                    type=ActivityTypes.message, text="Please confirm."))
                await dialog_context.prompt("prompt", options)
            elif results.status == DialogTurnStatus.Complete:
                selected_choice = results.result
                await turn_context.send_activity(selected_choice.value)

            await convo_state.save_changes(turn_context)

        async def validator(prompt: PromptValidatorContext) -> bool:
            assert prompt

            if not prompt.recognized.succeeded:
                await prompt.context.send_activity("Bad input.")

            return prompt.recognized.succeeded

        adapter = TestAdapter(exec_test)

        convo_state = ConversationState(MemoryStorage())
        dialog_state = convo_state.create_property("dialogState")
        dialogs = DialogSet(dialog_state)

        culture = PromptCultureModel(
            locale="custom-locale",
            no_in_language="customNo",
            yes_in_language="customYes",
            separator="customSeparator",
            inline_or="customInlineOr",
            inline_or_more="customInlineOrMore",
        )

        custom_dict = {
            culture.locale: (
                Choice(culture.yes_in_language),
                Choice(culture.no_in_language),
                ChoiceFactoryOptions(culture.separator, culture.inline_or,
                                     culture.inline_or_more, True),
            )
        }

        confirm_prompt = ConfirmPrompt("prompt",
                                       validator,
                                       choice_defaults=custom_dict)
        dialogs.add(confirm_prompt)

        step1 = await adapter.send(
            Activity(type=ActivityTypes.message,
                     text="Hello",
                     locale=culture.locale))
        await step1.assert_reply(
            "Please confirm. (1) customYescustomInlineOr(2) customNo")
Пример #5
0
 def get_choices(self):
     insurance_services_options = [
         Choice(value="Health Insurance",
                synonyms=["Health Insurance", "*"]),
         Choice(value="Book an appointment",
                synonyms=["Book an appointment"]),
         Choice(value="Renew Insurance", synonyms=["Renew Insurance"]),
     ]
     return insurance_services_options
Пример #6
0
 async def icon_checkin_step(
         self, step_context: WaterfallStepContext) -> DialogTurnResult:
     return await step_context.prompt(
         ChoicePrompt.__name__,
         PromptOptions(
             prompt=MessageFactory.text(
                 "Overall, How are you feeling right now?"),
             choices=[Choice("💚"), Choice("💛"),
                      Choice("❤️")],
         ),
     )
Пример #7
0
 async def DisplayChoiceList(self, waterfall_step: WaterfallStepContext):
     listofchoice = [
         Choice("MTech"),
         Choice("BTech"),
         Choice("MCA"),
         Choice("PhD")
     ]
     return await waterfall_step.prompt(
         (ChoicePrompt.__name__),
         PromptOptions(
             prompt=MessageFactory.text("Please select the your education"),
             choices=listofchoice))
Пример #8
0
    def _get_skill_actions(self, skill: BotFrameworkSkill) -> List[Choice]:
        # Note: the bot would probably render this by reading the skill manifest.
        # We are just using hardcoded skill actions here for simplicity.

        choices = []
        if skill.id == "DialogSkillBot":
            choices.append(Choice(self._skill_action_book_flight))
            choices.append(
                Choice(self._skill_action_book_flight_with_input_parameters))
            choices.append(Choice(self._skill_action_get_weather))

        return choices
Пример #9
0
 def _to_choices(self, choices: dict) -> List[Choice]:
     """Converts the list of strings to the list of instances of Choice objects
         Args:
             choices (List[str]): list of strings to be converted
         Returns:
             List[Choice]: list of Choice objects which can now be passed to a prompt method.
     """
     choice_list: List[Choice] = []
     for key in choices:
         choice_list.append(Choice(value=key))
     choice_list.append(Choice(self.DONE_OPTION))
     return choice_list
Пример #10
0
 async def transport_step(
         self, step_context: WaterfallStepContext) -> DialogTurnResult:
     # WaterfallStep always finishes with the end of the Waterfall or with another dialog;
     # here it is a Prompt Dialog. Running a prompt here means the next WaterfallStep will
     # be run when the users response is received.
     return await step_context.prompt(
         ChoicePrompt.__name__,
         PromptOptions(
             prompt=MessageFactory.text(
                 "Please enter your mode of transport."),
             choices=[Choice("Car"),
                      Choice("Bus"),
                      Choice("Bicycle")]))
Пример #11
0
 async def what_step(
         self, step_context: WaterfallStepContext) -> DialogTurnResult:
     return await step_context.prompt(
         ChoicePrompt.__name__,
         PromptOptions(
             prompt=MessageFactory.text(f"Ciao, cosa vuoi fare?"),
             choices=[
                 Choice("Fattura testuale"),
                 Choice("Fattura visiva"),
                 Choice("Query")
             ],
             style=ListStyle.hero_card,
         ),
     )
Пример #12
0
    async def selection_step(self, step_context: WaterfallStepContext):

        return await step_context.prompt(
            ChoicePrompt.__name__,
            PromptOptions(
                prompt=MessageFactory.text(
                    "Please indicate what do you want to know, or choose done to exit."
                ),
                choices=[
                    Choice('Covid-19 Social Distance'),
                    Choice('Covid-19 Mask Instructions'),
                    Choice("Done")
                ],
            ),
        )
Пример #13
0
    def get_choices(self):
        card_options = [
            Choice(value="Adaptive Card", synonyms=["adaptive"]),
            Choice(value="Animation Card", synonyms=["animation"]),
            Choice(value="Audio Card", synonyms=["audio"]),
            Choice(value="Hero Card", synonyms=["hero"]),
            Choice(value="OAuth Card", synonyms=["oauth"]),
            Choice(value="Receipt Card", synonyms=["receipt"]),
            Choice(value="Signin Card", synonyms=["signin"]),
            Choice(value="Thumbnail Card", synonyms=["thumbnail", "thumb"]),
            Choice(value="Video Card", synonyms=["video"]),
            Choice(value="All Cards", synonyms=["all"]),
        ]

        return card_options
Пример #14
0
 async def DisplayChoiceList(self, waterfall_step: WaterfallStepContext):
     name = waterfall_step._turn_context.activity.text
     waterfall_step.values["name"] = name
     listofchoice = [Choice("A"), Choice("B"), Choice("C")]
     await waterfall_step._turn_context.send_activity(
         "A) No puedo iniciar sesión")
     await waterfall_step._turn_context.send_activity(
         "B) Tengo problemas con un sistema")
     await waterfall_step._turn_context.send_activity(
         "C) Tengo problemas con mi computadora")
     return await waterfall_step.prompt(
         (ChoicePrompt.__name__),
         PromptOptions(
             prompt=MessageFactory.text("Seleccione el tipo de problema"),
             choices=listofchoice))
Пример #15
0
    async def selection_step(self, step_context: WaterfallStepContext):

        self.new_country = False

        step_context.values["country"] = step_context.result

        return await step_context.prompt(
        ChoicePrompt.__name__,
        PromptOptions(
            prompt=MessageFactory.text("Please indicate what do you want to know, or choose done to exit."),
            choices=[Choice("Covid-19 Cases"), 
                     Choice("Covid-19 Deaths"), 
                     Choice("Covid-19 Tests"),
                     Choice("Done")],
        ),
    )
Пример #16
0
 async def waitAgent(self, waterfall_step: WaterfallStepContext):
     problemd = waterfall_step._turn_context.activity.text
     waterfall_step.values["problem"] = problemd
     name = waterfall_step.values["name"]
     choiceoption = waterfall_step.values["choiceoption"]
     request = f"Name : {name} , Choice: {choiceoption}, Problem : {problemd}"
     teams_connector = pymsteams.connectorcard(
         'https://azdemoclient01.webhook.office.com/webhookb2/0ce88ac6-b9c8-465a-8d62-1304be0e566f@13773ef3-c394-4997-8354-fc43061fa64a/IncomingWebhook/932330c1334447da8f610f9b7b7a62cc/f634a77c-a64c-427d-889d-7f7f1a73ee25'
     )
     teams_connector.text("Nuevo request: " + request)
     teams_connector.send()
     listofchoice = [Choice("Sí"), Choice("No")]
     return await waterfall_step.prompt(
         (ChoicePrompt.__name__),
         PromptOptions(prompt=MessageFactory.text("Ha sido contactado"),
                       choices=listofchoice))
    async def _select_skill_group_step(self,
                                       step_context: WaterfallStepContext):
        """
        Render a prompt to select the group of skills to use.
        """

        # Remember the delivery mode selected by the user.
        step_context.values[DELIVERY_MODE_NAME] = step_context.result.value

        # Create the PromptOptions with the types of supported skills.
        message_text = "What group of skills would you like to use?"
        retry_message_text = (
            "That was not a valid choice, please select a valid skill group.")

        choices = []
        groups = []
        for skill in self._skills_config.SKILLS.values():
            if skill.group not in groups:
                groups.append(skill.group)
                choices.append(Choice(skill.group))

        options = PromptOptions(
            prompt=MessageFactory.text(message_text, message_text,
                                       InputHints.expecting_input),
            retry_prompt=MessageFactory.text(retry_message_text,
                                             retry_message_text,
                                             InputHints.expecting_input),
            choices=choices,
        )

        # Prompt the user to select a type of skill.
        return await step_context.prompt(SKILL_GROUP_PROMPT, options)
    async def _select_skill_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """
        Render a prompt to select the skill to call.
        """

        skill_group = step_context.result.value

        # Create the PromptOptions from the skill configuration which contain the list of configured skills.
        message_text = "What skill would you like to call?"
        retry_message_text = "That was not a valid choice, please select a valid skill."

        options = PromptOptions(
            prompt=MessageFactory.text(message_text, message_text,
                                       InputHints.expecting_input),
            retry_prompt=MessageFactory.text(retry_message_text,
                                             retry_message_text,
                                             InputHints.expecting_input),
            style=ListStyle.list_style,
            choices=[
                Choice(skill.id)
                for skill in self._skills_config.SKILLS.values()
                if skill.group.lower().startswith(skill_group.lower())
            ],
        )

        # Prompt the user to select a skill.
        return await step_context.prompt(SKILL_PROMPT, options)
Пример #19
0
    async def subscription_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        if step_context.result:
            vm_details = step_context.options
            vm_details.name = step_context.result

        if vm_details.subscription is None:
            # Ask for the Subscription
            list_of_choices = [
                Choice(value=v)
                for v in AzureConfig.AZURE_SUBSCRIPTION_ID_MAP.keys()
            ]

            # If there's only one subscription, no need to ask
            if len(list_of_choices) == 1:
                subscription_id = AzureConfig.AZURE_SUBSCRIPTION_ID_MAP.values(
                )[0]
                vm_details.subscription = subscription_id
                return step_context.next(vm_details.subscription)

            choice_message_text = "In which subscription?"
            prompt_message = MessageFactory.text(choice_message_text,
                                                 choice_message_text,
                                                 InputHints.expecting_input)

            return await step_context.prompt(
                ChoicePrompt.__name__,
                PromptOptions(prompt=prompt_message,
                              choices=list_of_choices,
                              style=ListStyle.auto))

        return await step_context.next(vm_details.subscription)
Пример #20
0
    async def gender_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        # Set the user's first name to what they entered in response to the firstname prompt.
        personal_data = step_context.values[self.PERSONAL_DATA]
        personal_data.family_name = step_context.result

        # Ask the user to choose their gender.
        return await step_context.begin_dialog(
            ChoicePrompt.__name__,
            PromptOptions(
                prompt=MessageFactory.text("Was ist Ihr Geschlecht?"),
                choices=[
                    Choice("Männlich", synonyms=["m"]),
                    Choice("Weiblich", synonyms=["w"]),
                    Choice("Divers", synonyms=["d"])
                ],
                style=ListStyle.suggested_action))
 async def select_delivery_mode_step(
         self, step_context: WaterfallStepContext) -> DialogTurnResult:
     # Create the PromptOptions with the delivery modes supported.
     message = "What delivery mode would you like to use?"
     reprompt_message = (
         "That was not a valid choice, please select a valid delivery mode."
     )
     options = PromptOptions(
         prompt=MessageFactory.text(message, message,
                                    InputHints.expecting_input),
         retry_prompt=MessageFactory.text(reprompt_message,
                                          reprompt_message,
                                          InputHints.expecting_input),
         choices=[Choice("normal"),
                  Choice("expectReplies")],
     )
     return await step_context.prompt(
         self.select_delivery_mode_step.__name__, options)
Пример #22
0
    async def confirm_confirmedcasecontact_step(
        self, step_context: WaterfallStepContext
    ) -> DialogTurnResult:

        await step_context.context.send_activity(
            MessageFactory.text(
                "Finden wir heraus, ob Sie engen Kontakt zu einem bestätigten Covid-19-Fall hatten.")
        )
        #time.sleep(1)
        await step_context.context.send_activity(
            MessageFactory.text(
                f"Als enger Kontakt gilt Kontakt von Angesicht zu Angesicht länger als 15 Minuten, oder direkter, physischer Kontakt (Berührung, Händeschütteln, Küssen), oder Kontakt mit oder Austausch von Körperflüssigkeiten, oder Teilen einer Wohnung.")
        )
        #time.sleep(2)
        return await step_context.prompt(
            ChoicePrompt.__name__,
            PromptOptions(
                choices=[Choice("Ja"), Choice("Nein")],
                prompt=MessageFactory.text("Hatten Sie engen Kontakt zu einem **bestätigten Covid-19-Fall**?")
            ),
        )
Пример #23
0
    async def genre_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """
        If the user has not provided any emotion in their initial greeting or a genre that they're looking for.
        :param step_context:
        :return DialogTurnResult
        """
        recommendation_details = step_context.options

        # Inquire the user about the genre they'd like to listen to
        if recommendation_details["genre"] == "":
            message_text = "What kind of music would you like me to recommend?"
            prompt_message = MessageFactory.text(message_text, message_text,
                                                 InputHints.expecting_input)
            genre_choices = [
                Choice("rock"),
                Choice("metal"),
                Choice("classical"),
                Choice("jazz"),
                Choice("pop"),
                Choice("electronic")
            ]
            return await step_context.prompt(
                ChoicePrompt.__name__,
                PromptOptions(prompt=prompt_message, choices=genre_choices))

        return await step_context.next(recommendation_details)
    async def _select_skill_action_step(self,
                                        step_context: WaterfallStepContext):
        """
        Render a prompt to select the begin action for the skill.
        """

        # Get the skill info based on the selected skill.
        selected_skill_id = step_context.result.value
        delivery_mode = str(step_context.values[DELIVERY_MODE_NAME])
        v3_bots = ["EchoSkillBotDotNetV3", "EchoSkillBotJSV3"]

        # Exclude v3 bots from ExpectReplies
        if (delivery_mode == DeliveryModes.expect_replies
                and selected_skill_id in v3_bots):
            await step_context.context.send_activity(
                MessageFactory.text(
                    "V3 Bots do not support 'expectReplies' delivery mode."))

            # Restart setup dialog
            return await step_context.replace_dialog(self.initial_dialog_id)

        selected_skill = next(
            val for key, val in self._skills_config.SKILLS.items()
            if val.id == selected_skill_id)

        # Remember the skill selected by the user.
        step_context.values[SELECTED_SKILL_KEY_NAME] = selected_skill

        skill_action_choices = [
            Choice(action) for action in selected_skill.get_actions()
        ]
        if len(skill_action_choices) == 1:
            # The skill only supports one action (e.g. Echo), skip the prompt.
            return await step_context.next(
                FoundChoice(value=skill_action_choices[0].value,
                            index=0,
                            score=0))

        # Create the PromptOptions with the actions supported by the selected skill.
        message_text = f"Select an action to send to **{selected_skill.id}**."

        options = PromptOptions(
            prompt=MessageFactory.text(message_text, message_text,
                                       InputHints.expecting_input),
            choices=skill_action_choices,
        )

        # Prompt the user to select a skill action.
        return await step_context.prompt(SKILL_ACTION_PROMPT, options)
Пример #25
0
    async def _select_skill_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        # Create the PromptOptions from the skill configuration which contain the list of configured skills.
        message_text = (str(step_context.options) if step_context.options else
                        "What skill would you like to call?")
        reprompt_text = "That was not a valid choice, please select a valid skill."
        options = PromptOptions(
            prompt=MessageFactory.text(message_text),
            retry_prompt=MessageFactory.text(reprompt_text),
            choices=[
                Choice(value=skill.id)
                for _, skill in self._skills_config.SKILLS.items()
            ],
        )

        # Prompt the user to select a skill.
        return await step_context.prompt("SkillPrompt", options)
    async def select_skill_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        # Set delivery mode.
        self._delivery_mode = step_context.result.value
        await self._delivery_mode_property.set(step_context.context,
                                               step_context.result.value)

        # Create the PromptOptions from the skill configuration which contains the list of configured skills.
        message = "What skill would you like to call?"
        reprompt_message = "That was not a valid choice, please select a valid skill."
        options = PromptOptions(
            prompt=MessageFactory.text(message, message,
                                       InputHints.expecting_input),
            retry_prompt=MessageFactory.text(reprompt_message,
                                             reprompt_message),
            choices=[
                Choice(value=skill.id)
                for _, skill in sorted(self._skills_config.SKILLS.items())
            ],
            style=ListStyle.suggested_action)

        return await step_context.prompt(self.select_skill_step.__name__,
                                         options)
    async def intro_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
        if not self._luis_recognizer.is_configured:
            await step_context.context.send_activity(
                MessageFactory.text(
                    "NOTE: LUIS is not configured. To enable all capabilities, add 'LuisAppId', 'LuisAPIKey' and "
                    "'LuisAPIHostName' to the appsettings.json file.",
                    input_hint=InputHints.ignoring_input,
                )
            )

            return await step_context.next(None)

        if self._firstRun:
            self._firstRun = False
            card_options = [Choice(synonyms=[area], value=area) for area in AreaOwners.org_areas]
            return await step_context.prompt(
                        "cardPrompt",
                        PromptOptions(
                            prompt=MessageFactory.text(
                                "Please select the AI area. We will find their contact for you."
                            ),
                            choices=card_options
                        ),
                    )

        message_text = (
            str(step_context.options)
            if step_context.options
            else "Please tell me the AI area. We will find their contact for you."
        )
        prompt_message = MessageFactory.text(
            message_text, message_text, InputHints.expecting_input
        )

        return await step_context.prompt(
            TextPrompt.__name__, PromptOptions(prompt=prompt_message)
        )
Пример #28
0
 def _to_choices(self, choices: [str]) -> List[Choice]:
     choice_list: List[Choice] = []
     for c in choices:
         choice_list.append(Choice(value=c))
     return choice_list
Пример #29
0
class ConfirmPrompt(Prompt):
    # TODO: Fix to reference recognizer to use proper constants
    choice_defaults: Dict[str, object] = {
        "Spanish": (
            Choice("Si"),
            Choice("No"),
            ChoiceFactoryOptions(", ", " o ", ", o ", True),
        ),
        "Dutch": (
            Choice("Ja"),
            Choice("Nee"),
            ChoiceFactoryOptions(", ", " of ", ", of ", True),
        ),
        "English": (
            Choice("Yes"),
            Choice("No"),
            ChoiceFactoryOptions(", ", " or ", ", or ", True),
        ),
        "French": (
            Choice("Oui"),
            Choice("Non"),
            ChoiceFactoryOptions(", ", " ou ", ", ou ", True),
        ),
        "German": (
            Choice("Ja"),
            Choice("Nein"),
            ChoiceFactoryOptions(", ", " oder ", ", oder ", True),
        ),
        "Japanese": (
            Choice("はい"),
            Choice("いいえ"),
            ChoiceFactoryOptions("、 ", " または ", "、 または ", True),
        ),
        "Portuguese": (
            Choice("Sim"),
            Choice("Não"),
            ChoiceFactoryOptions(", ", " ou ", ", ou ", True),
        ),
        "Chinese": (
            Choice("是的"),
            Choice("不"),
            ChoiceFactoryOptions(", ", " 要么 ", ", 要么 ", True),
        ),
    }

    # TODO: PromptValidator
    def __init__(self,
                 dialog_id: str,
                 validator: object = None,
                 default_locale: str = None):
        super(ConfirmPrompt, self).__init__(dialog_id, validator)
        if dialog_id is None:
            raise TypeError("ConfirmPrompt(): dialog_id cannot be None.")
        # TODO: Port ListStyle
        self.style = ListStyle.auto
        # TODO: Import defaultLocale
        self.default_locale = default_locale
        self.choice_options = None
        self.confirm_choices = None

    async def on_prompt(
        self,
        turn_context: TurnContext,
        state: Dict[str, object],
        options: PromptOptions,
        is_retry: bool,
    ):
        if not turn_context:
            raise TypeError(
                "ConfirmPrompt.on_prompt(): turn_context cannot be None.")
        if not options:
            raise TypeError(
                "ConfirmPrompt.on_prompt(): options cannot be None.")

        # Format prompt to send
        channel_id = turn_context.activity.channel_id
        culture = self.determine_culture(turn_context.activity)
        defaults = self.choice_defaults[culture]
        choice_opts = (self.choice_options
                       if self.choice_options is not None else defaults[2])
        confirms = (self.confirm_choices if self.confirm_choices is not None
                    else (defaults[0], defaults[1]))
        choices = {confirms[0], confirms[1]}
        if is_retry and options.retry_prompt is not None:
            prompt = self.append_choices(options.retry_prompt, channel_id,
                                         choices, self.style, choice_opts)
        else:
            prompt = self.append_choices(options.prompt, channel_id, choices,
                                         self.style, choice_opts)
        await turn_context.send_activity(prompt)

    async def on_recognize(
        self,
        turn_context: TurnContext,
        state: Dict[str, object],
        options: PromptOptions,
    ) -> PromptRecognizerResult:
        # pylint: disable=undefined-variable
        if not turn_context:
            raise TypeError(
                "ConfirmPrompt.on_prompt(): turn_context cannot be None.")

        result = PromptRecognizerResult()
        if turn_context.activity.type == ActivityTypes.message:
            # Recognize utterance
            message = turn_context.activity
            culture = self.determine_culture(turn_context.activity)
            # TODO: Port ChoiceRecognizer
            results = ChoiceRecognizer.recognize_boolean(message.text, culture)
            if results.Count > 0:
                first = results[0]
                if "value" in first.Resolution:
                    result.succeeded = True
                    result.value = str(first.Resolution["value"])
            else:
                # First check whether the prompt was sent to the user with numbers
                # if it was we should recognize numbers
                defaults = self.choice_defaults[culture]
                opts = (self.choice_options
                        if self.choice_options is not None else defaults[2])

                # This logic reflects the fact that IncludeNumbers is nullable and True is the default set in
                # Inline style
                if opts.include_numbers.has_value or opts.include_numbers.value:
                    # The text may be a number in which case we will interpret that as a choice.
                    confirm_choices = (self.confirm_choices
                                       if self.confirm_choices is not None else
                                       (defaults[0], defaults[1]))
                    choices = {confirm_choices[0], confirm_choices[1]}
                    # TODO: Port ChoiceRecognizer
                    second_attempt_results = ChoiceRecognizers.recognize_choices(
                        message.text, choices)
                    if second_attempt_results:
                        result.succeeded = True
                        result.value = second_attempt_results[
                            0].resolution.index == 0

        return result

    def determine_culture(self, activity: Activity) -> str:
        culture = (activity.locale
                   if activity.locale is not None else self.default_locale)
        if not culture or culture not in self.choice_defaults:
            culture = (
                "English"
            )  # TODO: Fix to reference recognizer to use proper constants
        return culture
Пример #30
0
import aiounittest
from recognizers_text import Culture

from botbuilder.core import CardFactory, ConversationState, MemoryStorage, TurnContext
from botbuilder.core.adapters import TestAdapter
from botbuilder.dialogs import DialogSet, DialogTurnResult, DialogTurnStatus
from botbuilder.dialogs.choices import Choice, ListStyle
from botbuilder.dialogs.prompts import (
    ChoicePrompt,
    PromptOptions,
    PromptValidatorContext,
)
from botbuilder.schema import Activity, ActivityTypes

_color_choices: List[Choice] = [
    Choice(value="red"),
    Choice(value="green"),
    Choice(value="blue"),
]

_answer_message: Activity = Activity(text="red", type=ActivityTypes.message)
_invalid_message: Activity = Activity(text="purple",
                                      type=ActivityTypes.message)


class ChoicePromptTest(aiounittest.AsyncTestCase):
    def test_choice_prompt_with_empty_id_should_fail(self):
        empty_id = ""

        with self.assertRaises(TypeError):
            ChoicePrompt(empty_id)