Esempio n. 1
0
    def __init__(self, logic: Coroutine = None, conversation: ConversationReference = None,
                 send_trace_activity: bool = False):
        """
        Creates a new TestAdapter instance.
        :param logic:
        :param conversation: A reference to the conversation to begin the adapter state with.
        """
        super(TestAdapter, self).__init__()
        self.logic = logic
        self._next_id: int = 0
        self._user_tokens: List[UserToken] = []
        self._magic_codes: List[TokenMagicCode] = []
        self.activity_buffer: List[Activity] = []
        self.updated_activities: List[Activity] = []
        self.deleted_activities: List[ConversationReference] = []

        self.template: Activity = Activity(
            channel_id='test',
            service_url='https://test.com',
            from_property=ChannelAccount(id='User1', name='user'),
            recipient=ChannelAccount(id='bot', name='Bot'),
            conversation=ConversationAccount(id='Convo1')
        )
        if self.template is not None:
            self.template.service_url = self.template.service_url
            self.template.conversation = self.template.conversation
            self.template.channel_id = self.template.channel_id
 def create_activities(self,
                       conversation_id: str,
                       date: datetime,
                       count: int = 5):
     activities: List[Activity] = []
     time_stamp = date
     for i in range(count):
         activities.append(
             Activity(
                 type=ActivityTypes.message,
                 timestamp=time_stamp,
                 id=str(uuid.uuid4()),
                 text=str(i),
                 channel_id="test",
                 from_property=ChannelAccount(id=f"User{i}"),
                 conversation=ConversationAccount(id=conversation_id),
                 recipient=ChannelAccount(id="bot1", name="2"),
                 service_url="http://foo.com/api/messages",
             ))
         time_stamp = time_stamp + datetime.timedelta(0, 60)
         activities.append(
             Activity(
                 type=ActivityTypes.message,
                 timestamp=date,
                 id=str(uuid.uuid4()),
                 text=str(i),
                 channel_id="test",
                 from_property=ChannelAccount(id="Bot1", name="2"),
                 conversation=ConversationAccount(id=conversation_id),
                 recipient=ChannelAccount(id=f"User{i}"),
                 service_url="http://foo.com/api/messages",
             ))
         time_stamp = time_stamp + datetime.timedelta(
             0, 60)  # days, seconds, then other fields.
     return activities
Esempio n. 3
0
    def __init__(
        self,
        logic: Coroutine = None,
        conversation: ConversationReference = None,
        send_trace_activity: bool = False,
    ):  # pylint: disable=unused-argument
        """
        Creates a new TestAdapter instance.
        :param logic:
        :param conversation: A reference to the conversation to begin the adapter state with.
        """
        super(TestAdapter, self).__init__()
        self.logic = logic
        self._next_id: int = 0
        self._user_tokens: List[UserToken] = []
        self._magic_codes: List[TokenMagicCode] = []
        self.activity_buffer: List[Activity] = []
        self.updated_activities: List[Activity] = []
        self.deleted_activities: List[ConversationReference] = []

        self.template: Activity = Activity(
            channel_id="test",
            service_url="https://test.com",
            from_property=ChannelAccount(id="User1", name="user"),
            recipient=ChannelAccount(id="bot", name="Bot"),
            conversation=ConversationAccount(id="Convo1"),
        )
        if self.template is not None:
            self.template.service_url = self.template.service_url
            self.template.conversation = self.template.conversation
            self.template.channel_id = self.template.channel_id
Esempio n. 4
0
    def __send(self, text, conversation, mentions=None):
        logger.info(f"Sending message: {text}")
        entities = list()
        if mentions is None:
            mentions = list()
        for name in mentions:
            user_id = self._user_map.get(name)
            if not user_id:
                logger.info("User not found: %s" % name)
                continue
            mention = Mention(mentioned=ChannelAccount(id=user_id, name=name), text="<at>%s</at>" % name,
                              type="mention")
            entities.append(mention)

        credentials = MicrosoftAppCredentials(self._app_id, self._app_password)
        connector = ConnectorClient(credentials, base_url=self._service_url)

        reply = Activity(
            type=ActivityTypes.message,
            channel_id=self._current_channel,
            conversation=conversation,
            from_property=ChannelAccount(id=self._current_bot_id["id"], name=self._current_bot_id["name"]),
            entities=entities,
            text=text,
            service_url=self._service_url)

        response = connector.conversations.send_to_conversation(reply.conversation.id, reply)
        logger.info(response)
Esempio n. 5
0
    def __init__(self, reference: ConversationReference = None):
        super(ConsoleAdapter, self).__init__()

        self.reference = ConversationReference(
            channel_id='console',
            user=ChannelAccount(id='user', name='User1'),
            bot=ChannelAccount(id='bot', name='Bot'),
            conversation=ConversationAccount(id='convo1',
                                             name='',
                                             is_group=False),
            service_url='')

        # Warn users to pass in an instance of a ConversationReference, otherwise the parameter will be ignored.
        if reference is not None and not isinstance(reference,
                                                    ConversationReference):
            warnings.warn(
                'ConsoleAdapter: `reference` argument is not an instance of ConversationReference and will '
                'be ignored.')
        else:
            self.reference.channel_id = getattr(reference, 'channel_id',
                                                self.reference.channel_id)
            self.reference.user = getattr(reference, 'user',
                                          self.reference.user)
            self.reference.bot = getattr(reference, 'bot', self.reference.bot)
            self.reference.conversation = getattr(reference, 'conversation',
                                                  self.reference.conversation)
            self.reference.service_url = getattr(reference, 'service_url',
                                                 self.reference.service_url)
            # The only attribute on self.reference without an initial value is activity_id, so if reference does not
            # have a value for activity_id, default self.reference.activity_id to None
            self.reference.activity_id = getattr(reference, 'activity_id',
                                                 None)

        self._next_id = 0
Esempio n. 6
0
    async def process_activities(self, msgs, logic: Callable):
        """
        Loops through array of strings to bot

        :param msgs:
        :param logic:
        :return:
        """
        for msg in msgs:
            if msg is None:
                pass
            else:
                self._next_id += 1
                activity = Activity(text=msg,
                                    channel_id='console',
                                    from_property=ChannelAccount(id='user', name='User1'),
                                    recipient=ChannelAccount(id='bot', name='Bot'),
                                    conversation=ConversationAccount(id='Convo1'),
                                    type=ActivityTypes.message,
                                    timestamp=datetime.datetime.now(),
                                    id=str(self._next_id))

                activity = TurnContext.apply_conversation_reference(activity, self.reference, True)
                context = TurnContext(self, activity)
                print(context.get_conversation_reference(activity))

                await self.run_middleware(context, logic)
    def test_apply_conversation_reference_with_is_incoming_true(self):
        # Arrange
        activity = self.__create_activity()
        conversation_reference = ConversationReference(
            channel_id="cr_123",
            service_url="cr_serviceUrl",
            conversation=ConversationAccount(id="cr_456"),
            user=ChannelAccount(id="cr_abc"),
            bot=ChannelAccount(id="cr_def"),
            activity_id="cr_12345",
            locale="en-uS",
        )

        # Act
        activity.apply_conversation_reference(reference=conversation_reference,
                                              is_incoming=True)

        # Assert
        self.assertEqual(conversation_reference.channel_id,
                         activity.channel_id)
        self.assertEqual(conversation_reference.locale, activity.locale)
        self.assertEqual(conversation_reference.service_url,
                         activity.service_url)
        self.assertEqual(conversation_reference.conversation.id,
                         activity.conversation.id)
        self.assertEqual(conversation_reference.user.id,
                         activity.from_property.id)
        self.assertEqual(conversation_reference.bot.id, activity.recipient.id)
        self.assertEqual(conversation_reference.activity_id, activity.id)
    def __create_activity() -> Activity:
        account1 = ChannelAccount(
            id="ChannelAccount_Id_1",
            name="ChannelAccount_Name_1",
            aad_object_id="ChannelAccount_aadObjectId_1",
            role="ChannelAccount_Role_1",
        )

        account2 = ChannelAccount(
            id="ChannelAccount_Id_2",
            name="ChannelAccount_Name_2",
            aad_object_id="ChannelAccount_aadObjectId_2",
            role="ChannelAccount_Role_2",
        )

        conversation_account = ConversationAccount(
            conversation_type="a",
            id="123",
            is_group=True,
            name="Name",
            role="ConversationAccount_Role",
        )

        activity = Activity(
            id="123",
            from_property=account1,
            recipient=account2,
            conversation=conversation_account,
            channel_id="ChannelId123",
            locale="en-uS",
            service_url="ServiceUrl123",
        )

        return activity
Esempio n. 9
0
    def __init__(self,
                 logic: Coroutine = None,
                 template: ConversationReference = None):
        """
        Creates a new TestAdapter instance.
        :param logic:
        :param template:
        """
        super(TestAdapter, self).__init__()
        self.logic = logic
        self._next_id: int = 0
        self.activity_buffer: List[Activity] = []
        self.updated_activities: List[Activity] = []
        self.deleted_activities: List[ConversationReference] = []

        self.template: Activity = Activity(
            channel_id='test',
            service_url='https://test.com',
            from_property=ChannelAccount(id='User1', name='user'),
            recipient=ChannelAccount(id='bot', name='Bot'),
            conversation=ConversationAccount(id='Convo1'))
        if template is not None:
            self.template.service_url = template.service_url
            self.template.conversation = template.conversation
            self.template.channel_id = template.channel_id
Esempio n. 10
0
    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_conversations_update_activity(self):
        activity = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Updating activity...",
        )

        activity_update = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Activity updated.",
        )

        connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
        response = connector.conversations.send_to_conversation(
            CONVERSATION_ID, activity)
        activity_id = response.id
        response = connector.conversations.update_activity(
            CONVERSATION_ID, activity_id, activity_update)

        assert response is not None
        assert response.id == activity_id
Esempio n. 12
0
def create_activity_reply(activity: Activity,
                          text: str = None,
                          locale: str = None,
                          attachments=None):
    if attachments is None:
        attachments = []
    attachments_aux = attachments.copy()

    return Activity(
        type=ActivityTypes.message,
        timestamp=datetime.utcnow(),
        from_property=ChannelAccount(
            id=getattr(activity.recipient, "id", None),
            name=getattr(activity.recipient, "name", None),
        ),
        recipient=ChannelAccount(id=activity.from_property.id,
                                 name=activity.from_property.name),
        reply_to_id=activity.id,
        service_url=activity.service_url,
        channel_id=activity.channel_id,
        conversation=ConversationAccount(
            is_group=activity.conversation.is_group,
            id=activity.conversation.id,
            name=activity.conversation.name,
        ),
        text=text or "",
        locale=locale or "",
        attachments=attachments_aux,
        entities=[],
    )
Esempio n. 13
0
def call_for_content():
    APP_ID = '5995b22a-e094-4d5b-8523-edd7bb089d89'
    APP_PASSWORD = '******'
    CHANNEL_ID = 'msteams'
    BOT_ID = '5995b22a-e094-4d5b-8523-edd7bb089d89'
    authcookie = Office365('https://thespurgroup.sharepoint.com', username='******', password='******').GetCookies()
    site = Site('https://thespurgroup.sharepoint.com/sites/bot_project_test/', version=Version.v2016, authcookie=authcookie)
    folder_path = 'Shared Documents/Lono2docs/'
    teams_tracker = folder.get_file('testing.csv')
    source_stream = io.BytesIO(teams_tracker)
    df = pd.read_csv(source_stream).drop(columns=['Unnamed: 0'])
    for index, row in df.iterrows():
        SERVICE_URL = row.serviceURL
        recipient_id = row.recipientID
        TENANT_ID = row.tenantID
        NAME = row.Name
        to = ChannelAccount(id=recipient_id)
        bot_channel = ChannelAccount(id=CHANNEL_ID)
        MicrosoftAppCredentials.trust_service_url(SERVICE_URL)
        credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
        conn_client = ConnectorClient(credentials, SERVICE_URL)
        message_activity = MessageFactory.text(f"Hello {NAME}, are you going to submit an article for this month's newsletter?");
        
        conversation_params = ConversationParameters(members=[to], channel_data={ 'tenant': { 'id': TENANT_ID } })
        conversation = conn_client.conversations.create_conversation(conversation_params)
        conn_client.conversations.send_to_conversation(conversation.id, message_activity)
    async def test_bot_on_teams_members_added_activity(self):
        # arrange
        activity = Activity(
            recipient=ChannelAccount(id="botid"),
            type=ActivityTypes.conversation_update,
            channel_data={
                "eventType": "teamMemberAdded",
                "team": {
                    "id": "team_id_1",
                    "name": "new_team_name"
                },
            },
            members_added=[
                ChannelAccount(
                    id="botid",
                    name="test_user",
                    aad_object_id="asdfqwerty",
                    role="tester",
                )
            ],
            channel_id=Channels.ms_teams,
            conversation=ConversationAccount(id="456"),
        )

        turn_context = TurnContext(SimpleAdapter(), activity)

        # Act
        bot = TestingTeamsActivityHandler()
        await bot.on_turn(turn_context)

        # Assert
        assert len(bot.record) == 2
        assert bot.record[0] == "on_conversation_update_activity"
        assert bot.record[1] == "on_teams_members_added"
Esempio n. 15
0
    def __init__(
        self,
        logic: Coroutine = None,
        template_or_conversation: Union[Activity,
                                        ConversationReference] = None,
        send_trace_activities: bool = False,
    ):
        """
        Creates a new TestAdapter instance.
        :param logic:
        :param conversation: A reference to the conversation to begin the adapter state with.
        """
        super(TestAdapter, self).__init__()
        self.logic = logic
        self._next_id: int = 0
        self._user_tokens: List[UserToken] = []
        self._magic_codes: List[TokenMagicCode] = []
        self._conversation_lock = Lock()
        self.exchangeable_tokens: Dict[str, ExchangeableToken] = {}
        self.activity_buffer: List[Activity] = []
        self.updated_activities: List[Activity] = []
        self.deleted_activities: List[ConversationReference] = []
        self.send_trace_activities = send_trace_activities

        self.template = (template_or_conversation if isinstance(
            template_or_conversation, Activity) else Activity(
                channel_id="test",
                service_url="https://test.com",
                from_property=ChannelAccount(id="User1", name="user"),
                recipient=ChannelAccount(id="bot", name="Bot"),
                conversation=ConversationAccount(id="Convo1"),
            ))

        if isinstance(template_or_conversation, ConversationReference):
            self.template.channel_id = template_or_conversation.channel_id
Esempio n. 16
0
 async def process_activity(self, logic: Callable):
     """
     Begins listening to console input.
     :param logic:
     :return:
     """
     while True:
         #user's input is set as variable msg
         msg = input()
         #Nothing happens if the user inputs a blank input
         if msg is None:
             pass
         else:
             #increases _next_id value by one
             self._next_id += 1
             # creating an object for communication with the Bot. Used as an initial message for a new conversation
             activity = Activity(
                 text=msg,
                 channel_id='console',
                 #Uniquely identifies ID of user and their name
                 from_property=ChannelAccount(id='user', name='User1'),
                 #identifies the bot as recipient and their name as Bot
                 recipient=ChannelAccount(id='bot', name='Bot'),
                 #identification of the conversation
                 conversation=ConversationAccount(id='Convo1'),
                 type=ActivityTypes.message,
                 timestamp=datetime.datetime.now(),
                 id=str(self._next_id))
             #send to the bot
             activity = TurnContext.apply_conversation_reference(
                 activity, self.reference, True)
             context = TurnContext(self, activity)
             # output of the function
             #logs message from user
             await self.run_middleware(context, logic)
Esempio n. 17
0
    async def test_continue_conversation_direct_msg(self):
        callback_invoked = False
        adapter = TestAdapter()
        reference = ConversationReference(
            activity_id="activityId",
            bot=ChannelAccount(id="channelId",
                               name="testChannelAccount",
                               role="bot"),
            channel_id="testChannel",
            service_url="testUrl",
            conversation=ConversationAccount(
                conversation_type="",
                id="testConversationId",
                is_group=False,
                name="testConversationName",
                role="user",
            ),
            user=ChannelAccount(id="channelId",
                                name="testChannelAccount",
                                role="bot"),
        )

        async def continue_callback(turn_context):  # pylint: disable=unused-argument
            nonlocal callback_invoked
            callback_invoked = True

        await adapter.continue_conversation(reference, continue_callback,
                                            "MyBot")
        self.assertTrue(callback_invoked)
Esempio n. 18
0
    def __init__(self, reference: ConversationReference = None):
        super(ConsoleAdapter, self).__init__()

        self.reference = ConversationReference(
            channel_id="console",
            user=ChannelAccount(id="user", name="User1"),
            bot=ChannelAccount(id="bot", name="Bot"),
            conversation=ConversationAccount(id="convo1",
                                             name="",
                                             is_group=False),
            service_url="",
        )

        # Warn users to pass in an instance of a ConversationReference, otherwise the parameter will be ignored.
        if reference is not None and not isinstance(reference,
                                                    ConversationReference):
            warnings.warn(
                "ConsoleAdapter: `reference` argument is not an instance of ConversationReference and will "
                "be ignored.")
        else:
            self.reference.channel_id = getattr(reference, "channel_id",
                                                self.reference.channel_id)
            self.reference.user = getattr(reference, "user",
                                          self.reference.user)
            self.reference.bot = getattr(reference, "bot", self.reference.bot)
            self.reference.conversation = getattr(reference, "conversation",
                                                  self.reference.conversation)
            self.reference.service_url = getattr(reference, "service_url",
                                                 self.reference.service_url)
            # The only attribute on self.reference without an initial value is activity_id, so if reference does not
            # have a value for activity_id, default self.reference.activity_id to None
            self.reference.activity_id = getattr(reference, "activity_id",
                                                 None)

        self._next_id = 0
Esempio n. 19
0
    async def process_activity(self, logic: Callable):
        """
        Begins listening to console input.
        :param logic:
        :return:
        """
        while True:
            msg = input()
            if msg is None:
                pass
            else:
                self._next_id += 1
                activity = Activity(
                    text=msg,
                    channel_id="console",
                    from_property=ChannelAccount(id="user", name="User1"),
                    recipient=ChannelAccount(id="bot", name="Bot"),
                    conversation=ConversationAccount(id="Convo1"),
                    type=ActivityTypes.message,
                    timestamp=datetime.datetime.now(),
                    id=str(self._next_id),
                )

                activity = TurnContext.apply_conversation_reference(
                    activity, self.reference, True)
                context = TurnContext(self, activity)
                await self.run_pipeline(context, logic)
Esempio n. 20
0
    async def command_to_activity(body: SlackRequestBody,
                                  client: SlackClient) -> Activity:
        """
        Creates an activity based on a Slack event related to a slash command.

        :param body: The data of the Slack event.
        :type body: :class:`SlackRequestBody`
        :param client: The Slack client.
        :type client: :class:`SlackClient`
        :return: An activity containing the event data.
        :rtype: :class:`botbuilder.schema.Activity`
        """

        if not body:
            raise Exception("body is required")

        activity = Activity(
            id=body.trigger_id,
            channel_id="slack",
            conversation=ConversationAccount(id=body.channel_id,
                                             properties={}),
            from_property=ChannelAccount(id=body.user_id),
            recipient=ChannelAccount(id=None),
            channel_data=body,
            text=body.text,
            type=ActivityTypes.event,
            name="Command",
            value=body.command,
        )

        activity.recipient.id = await client.get_bot_user_identity(activity)
        activity.conversation.properties["team"] = body.team_id

        return activity
Esempio n. 21
0
    def payload_to_activity(payload: SlackPayload) -> Activity:
        """
        Creates an activity based on the Slack event payload.

        :param payload: The payload of the Slack event.
        :type payload: :class:`SlackPayload`
        :return: An activity containing the event data.
        :rtype: :class:`botbuilder.schema.Activity`
        """

        if not payload:
            raise Exception("payload is required")

        activity = Activity(
            channel_id="slack",
            conversation=ConversationAccount(id=payload.channel.id,
                                             properties={}),
            from_property=ChannelAccount(id=payload.message.bot_id if payload.
                                         message.bot_id else payload.user.id),
            recipient=ChannelAccount(),
            channel_data=payload,
            text=None,
            type=ActivityTypes.event,
        )

        if payload.thread_ts:
            activity.conversation.properties["thread_ts"] = payload.thread_ts

        if payload.actions and (payload.type == "block_actions"
                                or payload.type == "interactive_message"):
            activity.type = ActivityTypes.message
            activity.text = payload.actions.value

        return activity
    def test_conversations_update_activity_invalid_conversation_id_fails(self):
        activity = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Updating activity...",
        )

        activity_update = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Activity updated.",
        )

        with pytest.raises(ErrorResponseException) as excinfo:
            connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
            response = connector.conversations.send_to_conversation(
                CONVERSATION_ID, activity)
            activity_id = response.id
            connector.conversations.update_activity("INVALID_ID", activity_id,
                                                    activity_update)

        assert excinfo.value.error.error.code == "ServiceError"
        assert "Invalid ConversationId" in str(
            excinfo.value.error.error.message)
 def test_conversations_create_conversation(self):
     test_object = ChannelAccount(id=RECIPIENT_ID)
     create_conversation = ConversationParameters(
         bot=ChannelAccount(id=BOT_ID),
         members=[test_object],
         activity=Activity(
             type=ActivityTypes.message,
             channel_id=CHANNEL_ID,
             from_property=ChannelAccount(id=BOT_ID),
             recipient=test_object,
             text="Hi there!",
         ),
     )
     # creds = MicrosoftTokenAuthenticationStub(get_auth_token())
     print("Printing the pointer to the generated MicrosoftAppCredentials:")
     # print(creds)
     connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
     try:
         conversation = self.loop.run_until_complete(
             connector.conversations.create_conversation(
                 create_conversation))
     except Exception as error:
         raise error
     else:
         assert conversation.id is not None
    def test_conversations_create_conversation_with_bot_as_only_member_fails(
            self):
        test_object = ChannelAccount(id=BOT_ID)
        sender = ChannelAccount(id=BOT_ID)
        create_conversation = ConversationParameters(
            bot=sender,
            members=[test_object],
            activity=Activity(
                type=ActivityTypes.message,
                channel_id=CHANNEL_ID,
                from_property=sender,
                recipient=test_object,
                text="Hi there!",
            ),
        )

        with pytest.raises(ErrorResponseException) as excinfo:
            connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
            self.loop.run_until_complete(
                connector.conversations.create_conversation(
                    create_conversation))

        assert excinfo.value.error.error.code == "BadArgument"
        assert "Bots cannot IM other bots" in str(
            excinfo.value.error.error.message)
    def test_conversations_reply_to_activity(self):
        activity = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Thread activity",
        )

        child_activity = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Child activity.",
        )

        connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
        response = connector.conversations.send_to_conversation(
            CONVERSATION_ID, activity)
        activity_id = response.id
        response = connector.conversations.reply_to_activity(
            CONVERSATION_ID, activity_id, child_activity)

        assert response is not None
        assert response.id != activity_id
Esempio n. 26
0
 def _get_context(utterance: str, bot_adapter: BotAdapter) -> TurnContext:
     activity = Activity(
         type=ActivityTypes.message,
         text=utterance,
         conversation=ConversationAccount(),
         recipient=ChannelAccount(),
         from_property=ChannelAccount(),
     )
     return TurnContext(bot_adapter, activity)
Esempio n. 27
0
    async def event_to_activity(event: SlackEvent,
                                client: SlackClient) -> Activity:
        """
        Creates an activity based on the Slack event data.

        :param event: The data of the Slack event.
        :type event: :class:`SlackEvent`
        :param client: The Slack client.
        :type client: :class:`SlackClient`
        :return: An activity containing the event data.
        :rtype: :class:`botbuilder.schema.Activity`
        """

        if not event:
            raise Exception("slack event is required")

        activity = Activity(
            id=event.event_ts,
            channel_id="slack",
            conversation=ConversationAccount(
                id=event.channel if event.channel else event.channel_id,
                properties={}),
            from_property=ChannelAccount(
                id=event.bot_id if event.bot_id else event.user_id if event.
                user_id else event.user),
            recipient=ChannelAccount(id=None),
            channel_data=event,
            text=event.text,
            type=ActivityTypes.event,
            timestamp=datetime.fromtimestamp(float(event.event_ts),
                                             tz=timezone.utc),
        )

        if event.thread_ts:
            activity.conversation.properties["thread_ts"] = event.thread_ts

        if not activity.conversation.id:
            if event.item and event.item_channel:
                activity.conversation.id = event.item_channel
            else:
                activity.conversation.id = event.team

        activity.recipient.id = await client.get_bot_user_by_team(
            activity=activity)

        # If this is a message originating from a user, we'll mark it as such
        # If this is a message from a bot (bot_id != None), we want to ignore it by
        # leaving the activity type as Event.  This will stop it from being included in dialogs,
        # but still allow the Bot to act on it if it chooses (via ActivityHandler.on_event_activity).
        # NOTE: This catches a message from ANY bot, including this bot.
        # Note also, bot_id here is not the same as bot_user_id so we can't (yet) identify messages
        # originating from this bot without doing an additional API call.
        if event.type == "message" and not event.subtype and not event.bot_id:
            activity.type = ActivityTypes.message

        return activity
Esempio n. 28
0
    async def event_to_activity(event: SlackEvent,
                                client: SlackClient) -> Activity:
        """
        Creates an activity based on the Slack event data.

        :param event: The data of the Slack event.
        :type event: :class:`SlackEvent`
        :param client: The Slack client.
        :type client: :class:`SlackClient`
        :return: An activity containing the event data.
        :rtype: :class:`botbuilder.schema.Activity`
        """

        if not event:
            raise Exception("slack event is required")

        activity = Activity(
            id=event.event_ts,
            channel_id="slack",
            conversation=ConversationAccount(
                id=event.channel if event.channel else event.channel_id,
                properties={}),
            from_property=ChannelAccount(
                id=event.bot_id if event.bot_id else event.user_id),
            recipient=ChannelAccount(id=None),
            channel_data=event,
            text=event.text,
            type=ActivityTypes.event,
        )

        if not activity.conversation.id:
            if event.item and event.item_channel:
                activity.conversation.id = event.item_channel
            else:
                activity.conversation.id = event.team

        activity.recipient.id = await client.get_bot_user_identity(
            activity=activity)

        if event.thread_ts:
            activity.conversation.properties["thread_ts"] = event.thread_ts

        if event.type == "message" and not event.subtype and not event.bot_id:
            if not event.subtype:
                activity.type = ActivityTypes.message
                activity.text = event.text

            activity.conversation.properties[
                "channel_type"] = event.channel_type
            activity.value = event
        else:
            activity.name = event.type
            activity.value = event

        return activity
Esempio n. 29
0
    def _get_context(question: str, bot_adapter: BotAdapter) -> TurnContext:
        test_adapter = bot_adapter or TestAdapter()
        activity = Activity(
            type=ActivityTypes.message,
            text=question,
            conversation=ConversationAccount(),
            recipient=ChannelAccount(),
            from_property=ChannelAccount(),
        )

        return TurnContext(test_adapter, activity)
Esempio n. 30
0
 def message(id: str = "1234") -> Activity:  # pylint: disable=invalid-name
     return Activity(
         type=ActivityTypes.message,
         id=id,
         text="test",
         from_property=ChannelAccount(id="user", name="User Name"),
         recipient=ChannelAccount(id="bot", name="Bot Name"),
         conversation=ConversationAccount(id="convo", name="Convo Name"),
         channel_id="UnitTest",
         service_url="https://example.org",
     )