def content_url( url: str, content_type: str, name: str = None, text: str = None, speak: str = None, input_hint: Union[InputHints, str] = None, ): """ Returns a message that will display a single image or video to a user. :Example: message = MessageFactory.content_url('https://example.com/hawaii.jpg', 'image/jpeg', 'Hawaii Trip', 'A photo from our family vacation.') await context.send_activity(message) :param url: :param content_type: :param name: :param text: :param speak: :param input_hint: :return: """ attachment = Attachment(content_type=content_type, content_url=url) if name: attachment.name = name return attachment_activity(AttachmentLayoutTypes.list, [attachment], text, speak, input_hint)
def test_should_return_a_carousel(self): activity = MessageFactory.carousel( [Attachment(content_type='a'), Attachment(content_type='b')]) assert_message(activity) assert_attachments(activity, 2, ['a', 'b']) assert activity.attachment_layout == AttachmentLayoutTypes.carousel, 'invalid attachment_layout.'
def test_conversations_send_to_conversation_with_attachment(self): card1 = HeroCard( title="A static image", text="JPEG image", images=[ CardImage( url="https://docs.com/en-us/bot-framework/media/designing-bots/core/dialogs-screens.png" ) ], ) card2 = HeroCard( title="An animation", subtitle="GIF image", images=[CardImage(url="http://i.giphy.com/Ki55RUbOV5njy.gif")], ) activity = Activity( type=ActivityTypes.message, channel_id=CHANNEL_ID, recipient=ChannelAccount(id=RECIPIENT_ID), from_property=ChannelAccount(id=BOT_ID), attachment_layout=AttachmentLayoutTypes.list, attachments=[ Attachment(content_type="application/vnd.card.hero", content=card1), Attachment(content_type="application/vnd.card.hero", content=card2), ], ) connector = ConnectorClient(self.credentials, base_url=SERVICE_URL) response = self.loop.run_until_complete( connector.conversations.send_to_conversation(CONVERSATION_ID, activity) ) assert response is not None
def test_should_return_a_carousel(self): activity = MessageFactory.carousel( [Attachment(content_type="a"), Attachment(content_type="b")]) assert_message(activity) assert_attachments(activity, 2, ["a", "b"]) assert (activity.attachment_layout == AttachmentLayoutTypes.carousel ), "invalid attachment_layout."
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.'
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}")
async def test_should_not_send_retry_if_not_specified(self): async def exec_test(turn_context: TurnContext): dc = await dialogs.create_context(turn_context) results = await dc.continue_dialog() if results.status == DialogTurnStatus.Empty: await dc.begin_dialog('AttachmentPrompt', PromptOptions()) 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) # Initialize TestAdapter. adapter = TestAdapter(exec_test) # Create ConversationState with MemoryStorage and register the state as middleware. convo_state = ConversationState(MemoryStorage()) # Create a DialogState property, DialogSet and AttachmentPrompt. dialog_state = convo_state.create_property('dialog_state') dialogs = DialogSet(dialog_state) dialogs.add(AttachmentPrompt('AttachmentPrompt')) # Create incoming activity with attachment. attachment = Attachment(content='some content', content_type='text/plain') attachment_activity = Activity(type=ActivityTypes.message, attachments=[attachment]) step1 = await adapter.send('hello') step2 = await step1.send('what?') step3 = await step2.send(attachment_activity) await step3.assert_reply('some content')
async def _get_spiral_example(self, turn_context: TurnContext) -> Attachment: """ Creates an "Attachment" to be sent from the bot to the user at welcome message. :param turn_context: :return: Attachment """ with open(os.path.join(os.getcwd(), "img/sparch.png"), "rb") as in_file: image_data = in_file.read() connector = await turn_context.adapter.create_connector_client( turn_context.activity.service_url) conversation_id = turn_context.activity.conversation.id response = await connector.conversations.upload_attachment( conversation_id, AttachmentData( original_base64=image_data, type="image/png", ), ) base_uri: str = connector.config.base_url attachment_uri = (base_uri + ("" if base_uri.endswith("/") else "/") + f"v3/attachments/{response.id}/views/original") return Attachment( content_type="image/png", content_url=attachment_uri, )
def test_should_render_choices_as_hero_card(self): expected = Activity( type=ActivityTypes.message, input_hint=InputHints.expecting_input, attachment_layout=AttachmentLayoutTypes.list, attachments=[ Attachment( content=HeroCard( text="select from:", buttons=[ CardAction(type=ActionTypes.im_back, value="red", title="red"), CardAction(type=ActionTypes.im_back, value="green", title="green"), CardAction(type=ActionTypes.im_back, value="blue", title="blue"), ], ), content_type="application/vnd.microsoft.card.hero", ) ], ) activity = ChoiceFactory.hero_card(ChoiceFactoryTest.color_choices, "select from:") self.assertEqual(expected, activity)
async def _file_upload_complete( self, turn_context: TurnContext, file_consent_card_response: FileConsentCardResponse): """ The file was uploaded, so display a FileInfoCard so the user can view the file in Teams. """ name = file_consent_card_response.upload_info.name download_card = FileInfoCard( unique_id=file_consent_card_response.upload_info.unique_id, file_type=file_consent_card_response.upload_info.file_type) as_attachment = Attachment( content=download_card.serialize(), content_type=ContentType.FILE_INFO_CARD, name=name, content_url=file_consent_card_response.upload_info.content_url) reply = self._create_reply( turn_context.activity, f"<b>File uploaded.</b> Your file <b>{name}</b> is ready to download", "xml") reply.attachments = [as_attachment] await turn_context.send_activity(reply)
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."
def test_ShouldIncludeChoiceActionsInHeroCards(self): expected = Activity( type=ActivityTypes.message, input_hint=InputHints.expecting_input, attachment_layout=AttachmentLayoutTypes.list, attachments=[ Attachment( content=HeroCard( text="select from:", buttons=[ CardAction( type=ActionTypes.im_back, value="ImBack Value", title="ImBack Action", ), CardAction( type=ActionTypes.message_back, value="MessageBack Value", title="MessageBack Action", ), CardAction( type=ActionTypes.post_back, value="PostBack Value", title="PostBack Action", ), ], ), content_type="application/vnd.microsoft.card.hero", ) ], ) activity = ChoiceFactory.hero_card( ChoiceFactoryTest.choices_with_actions, "select from:") self.assertEqual(expected, activity)
def create_adaptive_card_attachment(self, id): relative_path = os.path.abspath(os.path.dirname(__file__)) with open( os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/save/color.txt', 'r+') as f: color = f.readline() if color == 'deep': suffix = '.2' print('深色') else: suffix = '.1' print('浅色') path = os.path.join( relative_path, os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/json/test.json") img_path = os.path.dirname(os.path.dirname(os.path.abspath( __file__))) + '/sources/img/' + str(id + 1) + suffix + '.jpg' with open(path) as in_file: card = json.load(in_file) card['body'][0]['url'] = img_path with open( os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/sources/test.txt', 'w+') as f: f.write(str(card)) #print(card) return Attachment( content_type="application/vnd.microsoft.card.adaptive", content=card)
def test_should_return_attachment_with_text_and_speak(self): activity = MessageFactory.attachment(Attachment(content_type='none'), 'test1', 'test2') assert_message(activity) assert_attachments(activity, 1, ['none']) assert activity.text == 'test1', 'invalid text field.' assert activity.speak == 'test2', 'invalid speak field.'
def test_should_return_attachment_with_text_and_speak(self): activity = MessageFactory.attachment(Attachment(content_type="none"), "test1", "test2") assert_message(activity) assert_attachments(activity, 1, ["none"]) assert activity.text == "test1", "invalid text field." assert activity.speak == "test2", "invalid speak field."
def create_adaptive_card_attachment(self): with open('resources/welcomeCard.json') as f: card = json.load(f) return Attachment( content_type="application/vnd.microsoft.card.adaptive", content=card)
async def get_internet_attachment(self): return Attachment( name=f"Files/{ self._picture }", content_type="image/png", content_url= f"{self.configuration.SERVER_URL}/images/{self._picture}", )
async def _send_hero_card(self, turn_context: TurnContext): card_path = os.path.join(os.getcwd(), "cards\\hero_card.json") with open(card_path, "rb") as in_file: card_data = json.load(in_file) await turn_context.send_activity( MessageFactory.attachment( Attachment(content_type=CardFactory.content_types.hero_card, content=card_data)))
def create_adaptive_card_attachment(self): relative_path = os.path.abspath(os.path.dirname(__file__)) path = os.path.join(relative_path, "./cards/welcomeCard.json") with open(path) as card_file: card = json.load(card_file) return Attachment( content_type="application/vnd.microsoft.card.adaptive", content=card )
def test_has_content_with_attachment(self): # Arrange activity_with_attachment = Activity(attachments=[Attachment()]) # Act result_with_attachment = activity_with_attachment.has_content() # Assert self.assertEqual(result_with_attachment, True)
def test_should_return_attachment_with_text_speak_and_input_hint(self): activity = MessageFactory.attachment(Attachment(content_type='none'), 'test1', 'test2', InputHints.ignoring_input) assert_message(activity) assert_attachments(activity, 1, ['none']) 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.'
def __create_interactive_message(self, file_path: str) -> Attachment: with open(file_path, "rb") as in_file: adaptive_card_attachment = json.load(in_file) return Attachment( content=adaptive_card_attachment, content_type="application/json", name="blocks", )
def test_should_return_attachment_with_text_speak_and_input_hint(self): activity = MessageFactory.attachment(Attachment(content_type="none"), "test1", "test2", InputHints.ignoring_input) assert_message(activity) assert_attachments(activity, 1, ["none"]) 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."
def create_adaptive_card_attachment(self): path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "cards/models.json") with open(path) as card_file: card = json.load(card_file) attachment = Attachment( content_type="application/vnd.microsoft.card.adaptive", content=card) return attachment
def create_adaptive_card_attachment(): """Create an adaptive card.""" path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "..\cards\models.json") with open(path) as card_file: card = json.load(card_file) return Attachment( content_type="application/vnd.microsoft.card.adaptive", content=card)
def _get_internet_attachment(self) -> Attachment: """ Creates an Attachment to be sent from the bot to the user from a HTTP URL. :return: Attachment """ return Attachment( name="architecture-resize.png", content_type="image/png", content_url="https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png", )
async def test_should_send_ignore_retry_rompt_if_validator_replies(self): async def exec_test(turn_context: TurnContext): dialog_context = await dialogs.create_context(turn_context) results = await dialog_context.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 dialog_context.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) # Initialize TestAdapter. adapter = TestAdapter(exec_test) # Create ConversationState with MemoryStorage and register the state as middleware. convo_state = ConversationState(MemoryStorage()) # Create a DialogState property, DialogSet and AttachmentPrompt. dialog_state = convo_state.create_property("dialog_state") dialogs = DialogSet(dialog_state) async def aux_validator(prompt_context: PromptValidatorContext): assert prompt_context, "Validator missing prompt_context" if not prompt_context.recognized.succeeded: await prompt_context.context.send_activity("Bad input.") return prompt_context.recognized.succeeded dialogs.add(AttachmentPrompt("AttachmentPrompt", aux_validator)) # Create incoming activity with attachment. attachment = Attachment(content="some content", content_type="text/plain") attachment_activity = Activity( type=ActivityTypes.message, attachments=[attachment] ) invalid_activty = Activity(type=ActivityTypes.message, text="invalid") step1 = await adapter.send("hello") step2 = await step1.assert_reply("please add an attachment.") step3 = await step2.send(invalid_activty) step4 = await step3.assert_reply("Bad input.") step5 = await step4.send(attachment_activity) await step5.assert_reply("some content")
async def get_inline_attachment(self): file_path = os.path.join(os.getcwd(), "images", self._picture) with open(file_path, "rb") as in_file: file = base64.b64encode(in_file.read()).decode() return Attachment( name=f"Files/{ self._picture }", content_type="image/png", content_url=f"data:image/png;base64,{file}", )
def create_oauth_card_attachment_activity(uri: str) -> Activity: oauth_card = OAuthCard(token_exchange_resource=TokenExchangeResource(uri=uri)) attachment = Attachment( content_type=ContentTypes.oauth_card, content=oauth_card, ) attachment_activity = MessageFactory.attachment(attachment) attachment_activity.conversation = ConversationAccount(id=str(uuid.uuid4())) attachment_activity.from_property = ChannelAccount(id="blah", name="name") return attachment_activity
async def _send_o365_card(self, turn_context: TurnContext): card_path = os.path.join(os.getcwd(), "cards\\o365_card.json") with open(card_path, "rb") as in_file: card_data = json.load(in_file) await turn_context.send_activity( MessageFactory.attachment( Attachment( content_type= "application/vnd.microsoft.teams.card.o365connector", content=card_data, )))