Esempio n. 1
0
    async def show_card_step(
        self, step_context: WaterfallStepContext
    ) -> DialogTurnResult:
        """
        Send a Rich Card response to the user based on their choice.
        self method is only called when a valid prompt response is parsed from the user's
        response to the ChoicePrompt.
        """
        reply = MessageFactory.list([])

        found_choice = step_context.result.value
        if found_choice == "Adaptive Card":
            reply.attachments.append(self.create_adaptive_card())
        elif found_choice == "Animation Card":
            reply.attachments.append(self.create_animation_card())
        elif found_choice == "Audio Card":
            reply.attachments.append(self.create_audio_card())
        elif found_choice == "Hero Card":
            reply.attachments.append(self.create_hero_card())
        elif found_choice == "OAuth Card":
            reply.attachments.append(self.create_oauth_card())
        elif found_choice == "Receipt Card":
            reply.attachments.append(self.create_receipt_card())
        elif found_choice == "Signin Card":
            reply.attachments.append(self.create_signin_card())
        elif found_choice == "Thumbnail Card":
            reply.attachments.append(self.create_thumbnail_card())
        elif found_choice == "Video Card":
            reply.attachments.append(self.create_video_card())
        else:
            reply.attachment_layout = AttachmentLayoutTypes.carousel
            reply.attachments.append(self.create_adaptive_card())
            reply.attachments.append(self.create_animation_card())
            reply.attachments.append(self.create_audio_card())
            reply.attachments.append(self.create_hero_card())
            reply.attachments.append(self.create_oauth_card())
            reply.attachments.append(self.create_receipt_card())
            reply.attachments.append(self.create_signin_card())
            reply.attachments.append(self.create_thumbnail_card())
            reply.attachments.append(self.create_video_card())

        # Send the card(s) to the user as an attachment to the activity
        await step_context.context.send_activity(reply)

        # Give the user instructions about what to do next
        await step_context.context.send_activity("Type anything to see another card.")

        return await step_context.end_dialog()
Esempio n. 2
0
    async def _send_suggested_actions(self, turn_context: TurnContext):
        """
            Creates and sends an activity with suggested actions to the user. When the user
            clicks one of the buttons the text value from the "CardAction" will be displayed
            in the channel just as if the user entered the text. There are multiple
            "ActionTypes" that may be used for different situations.
            """

        reply = MessageFactory.text("Confirm the option")

        reply.suggested_actions = SuggestedActions(actions=[
            CardAction(title="YES", type=ActionTypes.im_back, value="YES"),
            CardAction(title="NO", type=ActionTypes.im_back, value="NO"),
        ])

        return await turn_context.send_activity(reply)
Esempio n. 3
0
    async def budget_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """
        If a budget has not been provided, prompt for one.
        """
        booking_details = step_context.options
        booking_details.to_date = step_context.result
        self.message_history.add(step_context._turn_context.activity.text)

        if booking_details.budget is None:
            message_text = "What's your budget?"
            prompt_message = MessageFactory.text(message_text, message_text,
                                                 InputHints.expecting_input)
            return await step_context.prompt(
                TextPrompt.__name__, PromptOptions(prompt=prompt_message))
        return await step_context.next(booking_details.budget)
Esempio n. 4
0
    async def destination_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """
        If a destination city has not been provided, prompt for one.
        :param step_context:
        :return DialogTurnResult:
        """
        booking_details = step_context.options

        if booking_details.destination is None:
            message_text = "Where would you like to travel to?"
            prompt_message = MessageFactory.text(message_text, message_text,
                                                 InputHints.expecting_input)
            return await step_context.prompt(
                TextPrompt.__name__, PromptOptions(prompt=prompt_message))
        return await step_context.next(booking_details.destination)
Esempio n. 5
0
    async def date_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """
        If a destination city has not been provided, prompt for one.
        :param step_context:
        :return DialogTurnResult:
        """
        invoice_details = step_context.options

        if invoice_details.date is None and invoice_details.periodo is None:
            message_text = "Di quale giorno desideri conoscere il fatturato (DD-MM-YYYY)?"
            prompt_message = MessageFactory.text(message_text, message_text,
                                                 InputHints.expecting_input)
            return await step_context.prompt(
                TextPrompt.__name__, PromptOptions(prompt=prompt_message))
        return await step_context.next(invoice_details.date)
Esempio n. 6
0
    async def adjust_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        # If the child dialog ("BookingDialog") was cancelled or the user failed to confirm,
        # the Result here will be null.
        if not self._luis_recognizer.is_configured:
            # LUIS is not configured, we just run the BookingDialog path with an empty BookingDetailsInstance.
            return await step_context.begin_dialog(self._recommend_dialog_id,
                                                   ProductDetails())

        if step_context.context is not None:
            msg_txt = (f"您对这个推荐结果满意吗?")

            message = MessageFactory.text(msg_txt, msg_txt,
                                          InputHints.expecting_input)
            return await step_context.prompt(TextPrompt.__name__,
                                             PromptOptions(prompt=message))
Esempio n. 7
0
    async def login_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        # Get the token from the previous step. Note that we could also have gotten the
        # token directly from the prompt itself. There is an example of this in the next method.
        if step_context.result:
            await step_context.context.send_activity("You are now logged in.")
            return await step_context.prompt(
                TextPrompt.__name__,
                PromptOptions(prompt=MessageFactory.text(
                    "Would you like to do? (type 'me', 'send <EMAIL>' or 'recent')"
                )),
            )

        await step_context.context.send_activity(
            "Login was not successful please try again.")
        return await step_context.end_dialog()
    async def on_teams_members_added(  # pylint: disable=unused-argument
        self,
        teams_members_added: [TeamsChannelAccount],
        team_info: TeamInfo,
        turn_context: TurnContext,
    ):
        if not turn_context:
            raise Exception("turn_context cannot be null")

        location = (team_info.name if team_info else
                    turn_context.activity.conversation.conversation_type)
        hero_card = HeroCard(text=" ".join([
            f"{member.id} joined {location}" for member in teams_members_added
        ]))
        await turn_context.send_activity(
            MessageFactory.attachment(CardFactory.hero_card(hero_card)))
    async def _create_with_preview(self, turn_context: TurnContext,
                                   action: MessagingExtensionAction):
        preview_card = create_adaptive_card_preview(
            user_text=action.data["Question"],
            is_multi_select=action.data["MultiSelect"],
            option1=action.data["Option1"],
            option2=action.data["Option2"],
            option3=action.data["Option3"],
        )

        extension_result = MessagingExtensionResult(
            type="botMessagePreview",
            activity_preview=MessageFactory.attachment(preview_card),
        )
        return MessagingExtensionActionResponse(
            compose_extension=extension_result)
    async def summarize_issue_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """Prompt for issue to summarize."""
        sum_bot = step_context.options
        result = sum_bot.update_state_reply(step_context.context.activity.text)

        # Capture the results of the previous step
        if sum_bot.issue_header is None:
            return await step_context.prompt(
                TextPrompt.__name__,
                PromptOptions(
                    prompt=MessageFactory.text(step_context.result)
                ),
            )  # pylint: disable=line-too-long,bad-continuation
        else:
            return await step_context.next(result)
    async def start_selection_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        # Set the user's age to what they entered in response to the age prompt.
        user_profile: UserProfile = step_context.values[self.USER_INFO]
        user_profile.age = step_context.result

        if user_profile.age < 25:
            # If they are too young, skip the review selection dialog, and pass an empty list to the next step.
            await step_context.context.send_activity(
                MessageFactory.text("You must be 25 or older to participate."))

            return await step_context.next([])
        else:
            # Otherwise, start the review selection dialog.
            return await step_context.begin_dialog(
                ReviewSelectionDialog.__name__)
Esempio n. 12
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")],
        ),
    )
Esempio n. 13
0
    async def confirm_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        connectivity_details = step_context.options

        # Capture the results of the previous step
        connectivity_details.port = step_context.result
        message_text = (
            f"Please confirm, you want to check connectivity from { connectivity_details.source } to "
            f"{ connectivity_details.destination } on { connectivity_details.protocol.upper() } port { connectivity_details.port}?"
        )
        prompt_message = MessageFactory.text(message_text, message_text,
                                             InputHints.expecting_input)

        # Offer a YES/NO prompt.
        return await step_context.prompt(ConfirmPrompt.__name__,
                                         PromptOptions(prompt=prompt_message))
Esempio n. 14
0
    async def final_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        user_info: UserProfile = step_context.result

        companies = "no companies" if len(
            user_info.companies_to_review) == 0 else " and ".join(
                user_info.companies_to_review)
        status = f"You are signed up to review {companies}."

        await step_context.context.send_activity(MessageFactory.text(status))

        # store the UserProfile
        accessor = self.user_state.create_property("UserProfile")
        await accessor.set(step_context.context, user_info)

        return await step_context.end_dialog()
    async def on_message_activity(self, turn_context: TurnContext):
        TurnContext.remove_recipient_mention(turn_context.activity)
        if turn_context.activity.text == "delete":
            for activity in self.activity_ids:
                await turn_context.delete_activity(activity)

            self.activity_ids = []
        else:
            await self._send_message_and_log_activity_id(
                turn_context, turn_context.activity.text
            )

            for activity_id in self.activity_ids:
                new_activity = MessageFactory.text(turn_context.activity.text)
                new_activity.id = activity_id
                await turn_context.update_activity(new_activity)
    async def on_teams_channel_created(  # pylint: disable=unused-argument
            self, channel_info: ChannelInfo, team_info: TeamInfo,
            turn_context: TurnContext):
        if not turn_context:
            raise Exception("turn_context cannot be null")

        if not channel_info:
            raise Exception("channel_info cannot be null")

        if not team_info:
            raise Exception("team_info cannot be null")

        hero_card = HeroCard(
            text=f"{channel_info.name} is the Channel Created")
        await turn_context.send_activity(
            MessageFactory.attachment(CardFactory.hero_card(hero_card)))
Esempio n. 17
0
async def send_message(req: Request) -> Response:
    try:
        credentials = MicrosoftAppCredentials(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
        client = ConnectorClient(credentials, 'https://smba.trafficmanager.net/fr/')
        teams_client = TeamsConnectorClient(credentials, 'https://smba.trafficmanager.net/fr/')
        teams_channels = teams_client.teams.get_teams_channels('19:[email protected]')
        general_channel = next(channel for channel in teams_channels.conversations if channel.name is None)
        conversation_parameters = ConversationParameters(
            is_group=True,
            channel_data={"channel": {"id": general_channel.id}},
            activity=MessageFactory.content_url('https://picsum.photos/200/300', 'image/png'),
        )
        client.conversations.create_conversation(conversation_parameters)
        return Response(status=HTTPStatus.OK)
    except Exception:
        traceback.print_exc()
    async def on_teams_messaging_extension_bot_message_preview_send(  # pylint: disable=unused-argument
            self, turn_context: TurnContext, action: MessagingExtensionAction
    ) -> MessagingExtensionActionResponse:
        activity_preview = action.bot_activity_preview[0]
        content = activity_preview.attachments[0].content
        data = self._get_example_data(content)
        card = create_adaptive_card_preview(
            data.question,
            data.is_multi_select,
            data.option1,
            data.option2,
            data.option3,
        )

        message = MessageFactory.attachment(card)
        await turn_context.send_activity(message)
    async def on_teams_task_module_submit(
            self, turn_context: TurnContext,
            task_module_request: TaskModuleRequest) -> TaskModuleResponse:
        """
        Called when data is being returned from the selected option (see `on_teams_task_module_fetch').
        """

        # Echo the users input back.  In a production bot, this is where you'd add behavior in
        # response to the input.
        await turn_context.send_activity(
            MessageFactory.text(
                f"on_teams_task_module_submit: {json.dumps(task_module_request.data)}"
            ))

        message_response = TaskModuleMessageResponse(value="Thanks!")
        return TaskModuleResponse(task=message_response)
 def test_should_return_a_carousel_with_text_speak_and_input_hint(self):
     activity = MessageFactory.carousel(
         [Attachment(content_type="a"),
          Attachment(content_type="b")],
         "test1",
         "test2",
         InputHints.ignoring_input,
     )
     assert_message(activity)
     assert_attachments(activity, 2, ["a", "b"])
     assert (activity.attachment_layout == AttachmentLayoutTypes.carousel
             ), "invalid attachment_layout."
     assert activity.text == "test1", "invalid text field."
     assert activity.speak == "test2", "invalid speak field."
     assert (activity.input_hint == InputHints.ignoring_input
             ), "invalid input_hint field."
Esempio n. 21
0
 async def on_members_added_activity(self,
                                     members_added: List[ChannelAccount],
                                     turn_context: TurnContext):
     # Greet anyone that was not the target (recipient) of this message.
     # To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards.
     for member in members_added:
         if member.id != turn_context.activity.recipient.id:
             welcome_card = self._create_adaptive_card_attachment()
             activity = MessageFactory.attachment(welcome_card)
             activity.speak = "Welcome to the waterfall host bot"
             await turn_context.send_activity(activity)
             await DialogExtensions.run_dialog(
                 self._main_dialog,
                 turn_context,
                 self._dialog_state_property,
             )
    async def on_teams_messaging_extension_submit_action(  # pylint: disable=unused-argument
        self, turn_context: TurnContext, action: MessagingExtensionAction
    ) -> MessagingExtensionActionResponse:
        preview_card = create_adaptive_card_preview(
            user_text=action.data["Question"],
            is_multi_select=action.data["MultiSelect"],
            option1=action.data["Option1"],
            option2=action.data["Option2"],
            option3=action.data["Option3"],
        )

        extension_result = MessagingExtensionResult(
            type="botMessagePreview",
            activity_preview=MessageFactory.attachment(preview_card),
        )
        return MessagingExtensionActionResponse(compose_extension=extension_result)
    async def email_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """
        If a destination city has not been provided, prompt for one.
        :param step_context:
        :return DialogTurnResult:
        """
        ordering_details = step_context.options

        if ordering_details.email is None:
            message_text = "Please enter your email id."
            prompt_message = MessageFactory.text(message_text, message_text,
                                                 InputHints.expecting_input)
            return await step_context.prompt(
                TextPrompt.__name__, PromptOptions(prompt=prompt_message))
        return await step_context.next(ordering_details.email)
Esempio n. 24
0
    async def origin_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """Prompt for origin city."""
        booking_details = step_context.options

        # Capture the response to the previous step's prompt
        booking_details.destination = step_context.result
        if booking_details.origin is None:
            return await step_context.prompt(
                TextPrompt.__name__,
                PromptOptions(
                    prompt=MessageFactory.text("From what city will you be travelling?")
                ),
            )  # pylint: disable=line-too-long,bad-continuation
        else:
            return await step_context.next(booking_details.origin)
async def validator(prompt_context: PromptValidatorContext):
    tester = unittest.TestCase()
    tester.assertTrue(prompt_context.attempt_count > 0)

    activity = prompt_context.recognized.value

    if activity.type == ActivityTypes.event:
        if int(activity.value) == 2:
            prompt_context.recognized.value = MessageFactory.text(
                str(activity.value))
            return True
    else:
        await prompt_context.context.send_activity(
            "Please send an 'event'-type Activity with a value of 2.")

    return False
Esempio n. 26
0
    async def confirm_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """Confirm the information the user has provided."""
        booking_details = step_context.options

        # Capture the results of the previous step
        booking_details.travel_date = step_context.result
        msg = (
            f"Please confirm, I have you traveling to: { booking_details.destination }"
            f" from: { booking_details.origin } on: { booking_details.travel_date}."
        )

        # Offer a YES/NO prompt.
        return await step_context.prompt(
            ConfirmPrompt.__name__,
            PromptOptions(prompt=MessageFactory.text(msg)))
Esempio n. 27
0
    async def on_message_activity(self, turn_context: TurnContext):
        # The actual call to the QnA Maker service.
        response = await self.qna_maker.get_answers(turn_context)
        prompts = response[0].context.prompts

        if response and len(response) > 0:
            reply = MessageFactory.text(response[0].answer)
            if prompts and len(prompts) > 0:
                reply.suggested_actions = SuggestedActions(
                      actions=[
                          CardAction(title = prompts[iter].display_text, type=ActionTypes.im_back, value=prompts[iter].display_text) for iter in range(len(prompts))
                       ]
                      )
            await turn_context.send_activity(reply)
        else:
            await turn_context.send_activity("No QnA Maker answers were found.")
        async def exec_test(turn_context: TurnContext):
            dc = await dialogs.create_context(turn_context)

            results = await dc.continue_dialog()
            if results.status == DialogTurnStatus.Empty:
                options = PromptOptions(
                    prompt=Activity(type=ActivityTypes.message, text='please add an attachment.'),
                    retry_prompt=Activity(type=ActivityTypes.message, text='please try again.')
                )
                await dc.prompt('AttachmentPrompt', options)
            elif results.status == DialogTurnStatus.Complete:
                attachment = results.result[0]
                content = MessageFactory.text(attachment.content)
                await turn_context.send_activity(content)

            await convo_state.save_changes(turn_context)
Esempio n. 29
0
    async def final_step(
            self, step_context: WaterfallStepContext) -> DialogTurnResult:
        user_input = str(step_context.result)

        meme_data = user_input.split(',')

        possible_memes = MemeProcessor.get_meme_by_keyword(meme_data[0])
        created_meme = MemeRequests.create_meme(possible_memes[0].id,
                                                meme_data[1],
                                                meme_data[2])['data']['url']
        #await step_context.context.send_activity(MessageFactory.text(f'Your created meme can be found at: {created_meme}'))
        await step_context.context.send_activity(
            MessageFactory.text(
                f'Your created meme can be found at: {created_meme}'))

        return await step_context.end_dialog()
Esempio n. 30
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))