Exemple #1
0
    def _create_select_items_result_attachment(
            self, search_query: str) -> MessagingExtensionAttachment:
        card_text = f"You said {search_query}"
        bf_logo = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU"

        buttons = CardAction(
            type="openUrl",
            title="Click for more Information",
            value=
            "https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-overview"
        )

        images = [CardImage(url=bf_logo)]
        buttons = [buttons]

        select_item_tap = CardAction(type="invoke",
                                     value={"query": search_query})

        hero_card = HeroCard(title="You searched for:",
                             text=card_text,
                             images=images,
                             buttons=buttons)

        preview = HeroCard(title=card_text,
                           text=card_text,
                           images=images,
                           tap=select_item_tap)

        return MessagingExtensionAttachment(
            content_type=CardFactory.content_types.hero_card,
            content=hero_card,
            preview=CardFactory.hero_card(preview))
Exemple #2
0
    def _create_dummy_search_result_attachment(
            self) -> MessagingExtensionAttachment:
        card_text = "https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-overview"
        bf_logo = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU"

        button = CardAction(
            type="openUrl",
            title="Click for more Information",
            value=
            "https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-overview"
        )

        images = [CardImage(url=bf_logo)]

        buttons = [button]

        hero_card = HeroCard(title="Learn more about Teams:",
                             text=card_text,
                             images=images,
                             buttons=buttons)

        preview = HeroCard(title="Learn more about Teams:",
                           text=card_text,
                           images=images)

        return MessagingExtensionAttachment(
            content_type=CardFactory.content_types.hero_card,
            content=hero_card,
            preview=CardFactory.hero_card(preview))
Exemple #3
0
    async def on_teams_messaging_extension_query(
            self, turn_context: TurnContext, query: MessagingExtensionQuery):
        search_query = str(query.parameters[0].value)
        response = requests.get(f"http://registry.npmjs.com/-/v1/search",
                                params={"text": search_query})
        data = response.json()

        attachments = []

        for obj in data["objects"]:
            hero_card = HeroCard(
                title=obj["package"]["name"],
                tap=CardAction(type="invoke", value=obj["package"]),
                preview=[CardImage(url=obj["package"]["links"]["npm"])])

            attachment = MessagingExtensionAttachment(
                content_type=CardFactory.content_types.hero_card,
                content=HeroCard(title=obj["package"]["name"]),
                preview=CardFactory.hero_card(hero_card))
            attachments.append(attachment)
        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type="result",
                attachment_layout="list",
                attachments=attachments))
Exemple #4
0
    async def on_teams_messaging_extension_query(
            self, turn_context: TurnContext, query: MessagingExtensionQuery):
        # These commandIds are defined in the Teams App Manifest.
        if not query.command_id == "searchQuery":
            raise NotImplementedError(f"Invalid CommandId: {query.command_id}")

        card = HeroCard(
            title="This is a Link Unfurling Sample",
            subtitle="It will unfurl links from *.BotFramework.com",
            text=
            "This sample demonstrates how to handle link unfurling in Teams.  Please review the readme for more "
            "information. ",
        )

        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                attachment_layout="list",
                type="result",
                attachments=[
                    MessagingExtensionAttachment(
                        content=card,
                        content_type=ContentTypes.hero_card,
                        preview=CardFactory.hero_card(card),
                    )
                ],
            ))
    async def on_teams_messaging_extension_query(
            self, turn_context: TurnContext, query: MessagingExtensionQuery):
        search_query = str(query.parameters[0].value).strip()
        if search_query == "":
            await turn_context.send_activity(
                MessageFactory.text(
                    "You cannot enter a blank string for the search"))
            return

        search_results = self._get_search_results(search_query)

        attachments = []
        for obj in search_results:
            hero_card = HeroCard(title=obj["name"],
                                 tap=CardAction(type="invoke", value=obj))

            attachment = MessagingExtensionAttachment(
                content_type=CardFactory.content_types.hero_card,
                content=HeroCard(title=obj["name"]),
                preview=CardFactory.hero_card(hero_card),
            )
            attachments.append(attachment)
        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type="result",
                attachment_layout="list",
                attachments=attachments))
    async def on_teams_messaging_extension_query(self, turn_context: TurnContext, query: MessagingExtensionQuery):
        if query.command_id == "searchQuery":
            card = HeroCard(
                title="This is a Link Unfurling Sample",
                subtitle="It will unfurl links from *.botframework.com",
                text="This sample demonstrates how to handle link unfurling in Teams. Please review the readme for more information."
            )
            attachment = Attachment(
                                content_type=CardFactory.content_types.hero_card,
                                content=card
                            )
            msg_ext_atc = MessagingExtensionAttachment(
                            content=card,
                            content_type=CardFactory.content_types.hero_card,
                            preview=attachment
                        )
            msg_ext_res = MessagingExtensionResult(
                    attachment_layout="list",
                    type="result",
                    attachments=[msg_ext_atc]
                )
            response = MessagingExtensionResponse(
                compose_extension=msg_ext_res
            )

            return response
        
        raise NotImplementedError(f"Invalid command: {query.command_id}")
Exemple #7
0
    async def on_teams_messaging_extension_select_item(
            self, turn_context: TurnContext,
            query) -> MessagingExtensionResponse:
        hero_card = HeroCard(
            title=query["name"],
            subtitle=query["description"],
            buttons=[CardAction(type="openUrl", value=query["links"]["npm"])])
        attachment = MessagingExtensionAttachment(
            content_type=CardFactory.content_types.hero_card,
            content=hero_card)

        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type="result",
                attachment_layout="list",
                attachments=[attachment]))
Exemple #8
0
 async def on_teams_app_based_link_query(self, turn_context: TurnContext,
                                         query: AppBasedLinkQuery):
     hero_card = ThumbnailCard(
         title="Thumnnail card",
         text=query.url,
         images=[
             CardImage(
                 url=
                 "https://raw.githubusercontent.com/microsoft/botframework-sdk/master/icon.png"
             )
         ])
     attachments = MessagingExtensionAttachment(
         content_type=CardFactory.content_types.hero_card,
         content=hero_card)
     result = MessagingExtensionResult(attachment_layout="list",
                                       type="result",
                                       attachments=[attachments])
     return MessagingExtensionResponse(compose_extension=result)
Exemple #9
0
    async def on_teams_messaging_extension_select_item(
            self, turn_context: TurnContext,
            query) -> MessagingExtensionResponse:
        hero_card = HeroCard(
            title=query["name"],
            subtitle=query["summary"],
            buttons=[
                CardAction(type="openUrl",
                           value=f"https://pypi.org/project/{query['name']}")
            ],
        )
        attachment = MessagingExtensionAttachment(
            content_type=CardFactory.content_types.hero_card,
            content=hero_card)

        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type="result",
                attachment_layout="list",
                attachments=[attachment]))
Exemple #10
0
    async def create_card_command(
        self, turn_context: TurnContext, action: MessagingExtensionAction
    ) -> MessagingExtensionActionResponse:
        title = action.data["title"]
        subTitle = action.data["subTitle"]
        text = action.data["text"]

        card = HeroCard(title=title, subtitle=subTitle, text=text)
        cardAttachment = CardFactory.hero_card(card)
        attachment = MessagingExtensionAttachment(
            content=card,
            content_type=CardFactory.content_types.hero_card,
            preview=cardAttachment,
        )
        attachments = [attachment]

        extension_result = MessagingExtensionResult(
            attachment_layout="list", type="result", attachments=attachments
        )
        return MessagingExtensionActionResponse(compose_extension=extension_result)
    async def share_message_command(
            self, turn_context: TurnContext, action: MessagingExtensionAction
    ) -> MessagingExtensionActionResponse:
        # The user has chosen to share a message by choosing the 'Share Message' context menu command.

        # TODO: .user is None
        title = "Shared Message"  # f'{action.message_payload.from_property.user.display_name} orignally sent this message:'
        text = action.message_payload.body.content
        card = HeroCard(title=title, text=text)

        if not action.message_payload.attachments is None:
            # This sample does not add the MessagePayload Attachments.  This is left as an
            #  exercise for the user.
            card.subtitle = (
                f"({len(action.message_payload.attachments)} Attachments not included)"
            )

        # This Messaging Extension example allows the user to check a box to include an image with the
        # shared message.  This demonstrates sending custom parameters along with the message payload.
        include_image = action.data["includeImage"]
        if include_image == "true":
            image = CardImage(
                url=
                "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU"
            )
            card.images = [image]

        cardAttachment = CardFactory.hero_card(card)
        attachment = MessagingExtensionAttachment(
            content=card,
            content_type=CardFactory.content_types.hero_card,
            preview=cardAttachment,
        )
        attachments = [attachment]

        extension_result = MessagingExtensionResult(attachment_layout="list",
                                                    type="result",
                                                    attachments=attachments)
        return MessagingExtensionActionResponse(
            compose_extension=extension_result)
Exemple #12
0
    async def on_teams_messaging_extension_query(
        self,
        turn_context: TurnContext,
        query: MessagingExtensionQuery,
    ) -> MessagingExtensionResponse:
        search_query = str(query.parameters[0].value).strip()

        user_configuration = await self.user_config_property.get(
            turn_context, "UserConfiguration")
        if user_configuration is not None and "email" in user_configuration:
            return await self._get_auth_or_search_result(
                turn_context, query, search_query)

        # The user configuration is NOT set to search Email.
        if search_query is None:
            await turn_context.send_activity(
                MessageFactory.text(
                    "You cannot enter a blank string for the search"))
            return

        search_results = self._get_search_results(search_query)

        attachments = []
        for obj in search_results:
            hero_card = HeroCard(title=obj["name"],
                                 tap=CardAction(type="invoke", value=obj))

            attachment = MessagingExtensionAttachment(
                content_type=CardFactory.content_types.hero_card,
                content=HeroCard(title=obj["name"]),
                preview=CardFactory.hero_card(hero_card),
            )
            attachments.append(attachment)
        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type="result",
                attachment_layout="list",
                attachments=attachments))
Exemple #13
0
    async def _get_auth_or_search_result(
        self,
        turn_context: TurnContext,
        query: MessagingExtensionQuery,
        search_query: str,
    ) -> MessagingExtensionResponse:
        # When the Bot Service Auth flow completes, the action.State will contain
        # a magic code used for verification.
        magic_code = ""
        if query.state is not None:
            magic_code = query.state

        token_response = await turn_context.adapter.get_user_token(
            turn_context, self.connection_name, magic_code)
        if token_response is None or token_response.token is None:
            # There is no token, so the user has not signed in yet.

            # Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
            sign_in_link = await turn_context.adapter.get_oauth_sign_in_link(
                turn_context, self.connection_name)
            return MessagingExtensionResponse(
                compose_extension=MessagingExtensionResult(
                    type="auth",
                    suggested_actions=MessagingExtensionSuggestedAction(
                        actions=[
                            CardAction(
                                type="openUrl",
                                value=sign_in_link,
                                title="Bot Service OAuth",
                            )
                        ]),
                ))
        # User is signed in, so use their token to search email via the Graph Client
        client = SimpleGraphClient(token_response.token)
        search_results = await client.search_mail_inbox(search_query)

        # Here we construct a ThumbnailCard for every attachment, and provide a HeroCard which will be
        # displayed if the user selects that item.
        attachments = []
        for message_meta in search_results:
            message = message_meta["_source"]
            message_from = message["from"] if "from" in message else None
            if message_from:
                subtitle = (f"{message_from['emailAddress']['name']},"
                            f"<{message_from['emailAddress']['address']}>")
            else:
                subtitle = ""

            hero_card = HeroCard(
                title=message["subject"] if "subject" in message else "",
                subtitle=subtitle,
                text=message["bodyPreview"]
                if "bodyPreview" in message else "",
            )

            thumbnail_card = CardFactory.thumbnail_card(
                ThumbnailCard(
                    title=subtitle,
                    subtitle=message["subject"],
                    images=[
                        CardImage(
                            url=
                            "https://botframeworksamples.blob.core.windows.net/samples"
                            "/OutlookLogo.jpg",
                            alt="Outlook Logo",
                        )
                    ],
                ))
            attachment = MessagingExtensionAttachment(
                content_type=CardFactory.content_types.hero_card,
                content=hero_card,
                preview=thumbnail_card,
            )
            attachments.append(attachment)

        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type="result",
                attachment_layout="list",
                attachments=attachments))
Exemple #14
0
    async def on_teams_messaging_extension_select_item(
            self, turn_context: TurnContext,
            query) -> MessagingExtensionResponse:
        nb = pynetbox.api(CONFIG.NETBOX_HOST,
                          token=CONFIG.NETBOX_APIKEY,
                          threading=True)
        if query['module'] == 'dcim/devices':
            device = nb.dcim.devices.get(int(query['id']))
            hero_card = HeroCard(
                title=query['name'],
                tap=CardAction(
                    type="openUrl",
                    value=
                    f"{CONFIG.NETBOX_HOST}/{query['module']}/{query['id']}"),
                text=
                f"<code>{query['name']}</code> is a <em>{query['type']}</em>"
                f" of type <strong>{device.device_type.display_name}</strong>"
                f" having the role of <strong>{device.device_role}</strong>"
                f" located at <strong>{device.site}</strong>"
                f" with the primary IP address of <code>{device.primary_ip}</code>"
            )
        elif query['module'] == 'virtualization/virtual-machines':
            vm = nb.virtualization.virtual_machines.get(int(query['id']))
            hero_card = HeroCard(
                title=query['name'],
                tap=CardAction(
                    type="openUrl",
                    value=
                    f"{CONFIG.NETBOX_HOST}/{query['module']}/{query['id']}"),
                text=
                f"<code>{query['name']}</code> is a <em>{query['type']}</em>"
                f" having the role of <strong>{vm.role}</strong>"
                f" located in cluster <strong>{vm.cluster}</strong>"
                f" at <strong>{vm.site}</strong>"
                f" with the primary IP address of <code>{vm.primary_ip}</code>"
            )
        elif query['module'] == 'ipam/prefixes':
            prefix = nb.ipam.prefixes.get(int(query['id']))
            hero_card = HeroCard(
                title=query['name'],
                tap=CardAction(
                    type="openUrl",
                    value=
                    f"{CONFIG.NETBOX_HOST}/{query['module']}/{query['id']}"),
                text=
                f"<code>{query['name']}</code> is a <em>{query['type']}</em>"
                f" having the role of <strong>{prefix.role}</strong>"
                f" located at <strong>{prefix.site}</strong>")
        elif query['module'] == 'ipam/ip-addresses':
            ip = nb.ipam.ip_addresses.get(int(query['id']))
            hero_card = HeroCard(
                title=query['name'],
                tap=CardAction(
                    type="openUrl",
                    value=
                    f"{CONFIG.NETBOX_HOST}/{query['module']}/{query['id']}"),
                text=
                f"<code>{query['name']}</code> is a <em>{query['type']}</em>"
                f" having the role of <strong>{ip.role}</strong>"
                f" used by interface <code>{ip.interface}</code>"
                f" on device <code>{ip.interface.device}</code>")
        elif query['module'] == 'dcim/sites':
            site = nb.dcim.sites.get(int(query['id']))
            hero_card = HeroCard(
                title=query['name'],
                tap=CardAction(
                    type="openUrl",
                    value=
                    f"{CONFIG.NETBOX_HOST}/{query['module']}/{query['id']}"),
                text=
                f"<code>{query['name']}</code> is a <em>{query['type']}</em>"
                f" located in region <strong>{site.region}</strong>"
                f" with the address of <strong>{site.physical_address}</strong>"
                f" managed by <strong>{site.contact_name}</strong>")
        elif query['module'] == 'circuits/circuits':
            circuit = nb.circuits.circuits.get(int(query['id']))
            if circuit.termination_a is not None:
                site = circuit.termination_a.site
                device = circuit.termination_a.connected_endpoint.device
                interface = circuit.termination_a.connected_endpoint
                speed_down = circuit.termination_a.port_speed
                if speed_down is not None:
                    speed_down = speed_down / 1000
                speed_up = circuit.termination_a.upstream_speed
                if speed_up is not None:
                    speed_up = speed_up / 1000
                else:
                    speed_up = speed_down
            if circuit.termination_z is not None:
                site = circuit.termination_z.site
                device = circuit.termination_z.connected_endpoint.device
                interface = circuit.termination_z.connected_endpoint
                speed_down = circuit.termination_z.port_speed
                if speed_down is not None:
                    speed_down = speed_down / 1000
                speed_up = circuit.termination_z.upstream_speed
                if speed_up is not None:
                    speed_up = speed_up / 1000
                else:
                    speed_up = speed_down
            hero_card = HeroCard(
                title=query['name'],
                tap=CardAction(
                    type="openUrl",
                    value=
                    f"{CONFIG.NETBOX_HOST}/{query['module']}/{query['id']}"),
                text=
                f"<code>{query['name']}</code> is a <em>{query['type']}</em>"
                f" of type <strong>{circuit.type}</strong>"
                f" provided by <strong>{circuit.provider}</strong>"
                f" terminating on <code>{interface}</code> of <code>{device}</code> at <strong>{site}</strong>"
                f" with <strong>{speed_down}mbps ⬇</strong> and <strong>{speed_up}mbps ⬆</strong>"
            )

        attachment = MessagingExtensionAttachment(
            content_type=CardFactory.content_types.hero_card,
            content=hero_card)

        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type="result",
                attachment_layout="list",
                attachments=[attachment]))
    async def on_teams_messaging_extension_query(
            self,
            turn_context: TurnContext,
            query: MessagingExtensionQuery,  # pylint: disable=unused-argument
    ):
        search_query = str(query.parameters[0].value).strip()

        user_configuration = await self.user_config_property.get(
            turn_context, "UserConfiguration")
        if user_configuration is not None and "email" in user_configuration:
            # When the Bot Service Auth flow completes, the action.State will contain
            # a magic code used for verification.
            magic_code = ""
            if query.state is not None:
                magic_code = query.state

            token_response = await turn_context.adapter.get_user_token(
                turn_context, self.connection_name, magic_code)
            if token_response is None or token_response.token is None:
                # There is no token, so the user has not signed in yet.

                # Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
                sign_in_link = await turn_context.adapter.get_oauth_sign_in_link(
                    turn_context, self.connection_name)
                return MessagingExtensionResponse(
                    compose_extension=MessagingExtensionResult(
                        type="auth",
                        suggested_actions=MessagingExtensionSuggestedAction(
                            actions=[
                                CardAction(
                                    type="openUrl",
                                    value=sign_in_link,
                                    title="Bot Service OAuth",
                                )
                            ]),
                    ))
            # User is signed in, so use their token to search email via the Graph Client
            client = SimpleGraphClient(token_response.token)
            search_results = await client.search_mail_inbox(search_query)

            # Here we construct a ThumbnailCard for every attachment, and provide a HeroCard which will be
            # displayed if the user selects that item.
            attachments = []
            for message_meta in search_results:
                message = message_meta["_source"]
                message_from = message["from"] if "from" in message else None
                if message_from:
                    subtitle = (f"{message_from['emailAddress']['name']},"
                                f"<{message_from['emailAddress']['address']}>")
                else:
                    subtitle = ""

                hero_card = HeroCard(
                    title=message["subject"] if "subject" in message else "",
                    subtitle=subtitle,
                    text=message["bodyPreview"]
                    if "bodyPreview" in message else "",
                )

                thumbnail_card = CardFactory.thumbnail_card(
                    ThumbnailCard(
                        title=subtitle,
                        subtitle=message["subject"],
                        images=[
                            CardImage(
                                url=
                                "https://botframeworksamples.blob.core.windows.net/samples"
                                "/OutlookLogo.jpg",
                                alt="Outlook Logo",
                            )
                        ],
                    ))
                attachment = MessagingExtensionAttachment(
                    content_type=CardFactory.content_types.hero_card,
                    content=hero_card,
                    preview=thumbnail_card,
                )
                attachments.append(attachment)

            return MessagingExtensionResponse(
                compose_extension=MessagingExtensionResult(
                    type="result",
                    attachment_layout="list",
                    attachments=attachments))

        # The user configuration is NOT set to search Email.
        if search_query is None:
            turn_context.send_activity(
                MessageFactory.text(
                    "You cannot enter a blank string for the search"))
            return

        search_results = self._get_search_results(search_query)

        attachments = []
        for obj in search_results:
            hero_card = HeroCard(title=obj["name"],
                                 tap=CardAction(type="invoke", value=obj))

            attachment = MessagingExtensionAttachment(
                content_type=CardFactory.content_types.hero_card,
                content=HeroCard(title=obj["name"]),
                preview=CardFactory.hero_card(hero_card),
            )
            attachments.append(attachment)
        return MessagingExtensionResponse(
            compose_extension=MessagingExtensionResult(
                type="result",
                attachment_layout="list",
                attachments=attachments))