Exemplo n.º 1
0
    def remove_participant(self):
        thread_id = self._thread_id
        chat_client = self._chat_client
        identity_client = self.identity_client

        from azure.communication.chat import ChatParticipant, CommunicationUserIdentifier
        from datetime import datetime

        # create 2 new users using CommunicationIdentityClient.create_user method
        user1 = identity_client.create_user()
        user2 = identity_client.create_user()

        # set `thread_id` to an existing thread id
        chat_thread_client = chat_client.get_chat_thread_client(
            thread_id=thread_id)

        # add user1 and user2 to chat thread
        participant1 = ChatParticipant(identifier=user1,
                                       display_name='Fred Flinstone',
                                       share_history_time=datetime.utcnow())

        participant2 = ChatParticipant(identifier=user2,
                                       display_name='Wilma Flinstone',
                                       share_history_time=datetime.utcnow())

        thread_participants = [participant1, participant2]
        chat_thread_client.add_participants(thread_participants)

        # [START remove_participant]
        # Option 1 : Iterate through all participants, find and delete Fred Flinstone
        chat_thread_participants = chat_thread_client.list_participants()

        for chat_thread_participant_page in chat_thread_participants.by_page():
            for chat_thread_participant in chat_thread_participant_page:
                print("ChatParticipant: ", chat_thread_participant)
                if chat_thread_participant.identifier.properties[
                        'id'] == user1.properties['id']:
                    print("Found Fred!")
                    chat_thread_client.remove_participant(
                        chat_thread_participant.identifier)
                    print("Fred has been removed from the thread...")
                    break

        # Option 2: Directly remove Wilma Flinstone
        unique_identifier = user2.properties[
            'id']  # in real scenario the identifier would need to be retrieved from elsewhere
        chat_thread_client.remove_participant(
            CommunicationUserIdentifier(unique_identifier))
        print("Wilma has been removed from the thread...")
        # [END remove_participant]

        # clean up temporary users
        self.identity_client.delete_user(user1)
        self.identity_client.delete_user(user2)
        print("remove_chat_participant succeeded")
async def test_create_chat_thread_raises_error():
    async def mock_send(*_, **__):
        return mock_response(status_code=400,
                             json_payload={"msg": "some error"})

    chat_client = ChatClient("https://endpoint",
                             credential,
                             transport=Mock(send=mock_send))

    topic = "test topic",
    user = CommunicationUserIdentifier(
        "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041")
    participants = [
        ChatParticipant(identifier=user,
                        display_name='name',
                        share_history_time=datetime.utcnow())
    ]

    raised = False
    try:
        await chat_client.create_chat_thread(topic=topic,
                                             thread_participants=participants)
    except:
        raised = True

    assert raised == True
Exemplo n.º 3
0
    async def add_participants_w_check_async(self):
        thread_id = self._thread_id
        chat_client = self._chat_client
        user = self.new_user

        # [START add_participants]
        def decide_to_retry(error):
            """
            Custom logic to decide whether to retry to add or not
            """
            return True

        async with chat_client:
            # set `thread_id` to an existing thread id
            chat_thread_client = chat_client.get_chat_thread_client(
                thread_id=thread_id)
            async with chat_thread_client:
                from azure.communication.chat import ChatParticipant
                from datetime import datetime
                new_participant = ChatParticipant(
                    identifier=self.new_user,
                    display_name='name',
                    share_history_time=datetime.utcnow())
                thread_participants = [new_participant]
                result = await chat_thread_client.add_participants(
                    thread_participants)

                # list of participants which were unsuccessful to be added to chat thread
                retry = [p for p, e in result if decide_to_retry(e)]
                if retry:
                    await chat_thread_client.add_participants(retry)

        # [END add_participants]
        print("add_participants_w_check_async succeeded")
Exemplo n.º 4
0
    def test_list_participants(self):
        self._create_thread()

        # add another participant
        share_history_time = datetime.utcnow()
        share_history_time = share_history_time.replace(tzinfo=TZ_UTC)
        new_participant = ChatParticipant(
            identifier=self.new_user,
            display_name='name',
            share_history_time=share_history_time)

        self.chat_thread_client.add_participants([new_participant])

        # fetch list of participants
        chat_thread_participants = self.chat_thread_client.list_participants(
            results_per_page=1, skip=1)

        participant_count = 0

        for chat_thread_participant_page in chat_thread_participants.by_page():
            li = list(chat_thread_participant_page)
            assert len(li) <= 1
            participant_count += len(li)
            li[0].identifier.properties['id'] = self.user.properties['id']
        assert participant_count == 1
Exemplo n.º 5
0
    async def create_chat_thread_client_async(self):
        token = self.token
        endpoint = self.endpoint
        user = self.user
        # [START create_chat_thread_client]
        from datetime import datetime
        from azure.communication.chat.aio import ChatClient, CommunicationTokenCredential
        from azure.communication.chat import ChatParticipant, CommunicationUserIdentifier
        # set `endpoint` to an existing ACS endpoint
        chat_client = ChatClient(endpoint, CommunicationTokenCredential(token))

        async with chat_client:
            topic = "test topic"
            participants = [
                ChatParticipant(identifier=user,
                                display_name='name',
                                share_history_time=datetime.utcnow())
            ]
            create_chat_thread_result = await chat_client.create_chat_thread(
                topic, thread_participants=participants)
            chat_thread_client = chat_client.get_chat_thread_client(
                create_chat_thread_result.chat_thread.id)
        # [END create_chat_thread_client]

        self._thread_id = create_chat_thread_result.chat_thread.id
        print("thread created, id: " + self._thread_id)
        print("create_chat_thread_client_async succeeded")
Exemplo n.º 6
0
 def create_chat_thread_client(self):
     token = self.token
     endpoint = self.endpoint
     user = self.user
     # [START create_chat_thread_client]
     from datetime import datetime
     from azure.communication.chat import (ChatClient, ChatParticipant,
                                           CommunicationUserIdentifier,
                                           CommunicationTokenCredential)
     # retrieve `token` using CommunicationIdentityClient.get_token method
     # set `endpoint` to ACS service endpoint
     # create `user` using CommunicationIdentityClient.create_user method for new users;
     # else for existing users set `user` = CommunicationUserIdentifier(some_user_id)
     chat_client = ChatClient(endpoint, CommunicationTokenCredential(token))
     topic = "test topic"
     participants = [
         ChatParticipant(identifier=user,
                         display_name='name',
                         share_history_time=datetime.utcnow())
     ]
     create_chat_thread_result = chat_client.create_chat_thread(
         topic, thread_participants=participants)
     chat_thread_client = chat_client.get_chat_thread_client(
         create_chat_thread_result.chat_thread.id)
     # [END create_chat_thread_client]
     self._thread_id = create_chat_thread_result.chat_thread.id
     print("chat_thread_client created")
    async def create_thread_async(self):
        token = self.token
        endpoint = self.endpoint
        thread_id = self._thread_id

        # [START create_thread]
        from datetime import datetime
        from azure.communication.chat.aio import ChatClient, CommunicationTokenCredential
        from azure.communication.chat import ChatParticipant

        # set `endpoint` to an existing ACS endpoint
        chat_client = ChatClient(endpoint, CommunicationTokenCredential(token))
        async with chat_client:

            topic = "test topic"
            participants = [ChatParticipant(
                identifier=self.user,
                display_name='name',
                share_history_time=datetime.utcnow()
            )]
            # creates a new chat_thread everytime
            create_chat_thread_result = await chat_client.create_chat_thread(topic, thread_participants=participants)

            # creates a new chat_thread if not exists
            idempotency_token = 'b66d6031-fdcc-41df-8306-e524c9f226b8'  # unique identifier
            create_chat_thread_result_w_repeatability_id = await chat_client.create_chat_thread(
                topic,
                thread_participants=participants,
                idempotency_token=idempotency_token)
            # [END create_thread]

            self._thread_id = create_chat_thread_result.chat_thread.id
            print("thread created, id: " + self._thread_id)
Exemplo n.º 8
0
    async def test_list_participants(self):
        async with self.chat_client:
            await self._create_thread()

            async with self.chat_thread_client:
                # add another participant
                share_history_time = datetime.utcnow()
                share_history_time = share_history_time.replace(tzinfo=TZ_UTC)
                new_participant = ChatParticipant(
                    identifier=self.new_user,
                    display_name='name',
                    share_history_time=share_history_time)

                await self.chat_thread_client.add_participants(
                    [new_participant])

                chat_thread_participants = self.chat_thread_client.list_participants(
                    results_per_page=1, skip=1)

                items = []
                async for item in chat_thread_participants:
                    items.append(item)

                assert len(items) == 1

            # delete chat threads
            if not self.is_playback():
                await self.chat_client.delete_chat_thread(self.thread_id)
async def test_create_chat_thread():
    thread_id = "19:[email protected]"

    async def mock_send(*_, **__):
        return mock_response(
            status_code=201,
            json_payload={
                "chatThread": {
                    "id":
                    thread_id,
                    "topic":
                    "test topic",
                    "createdOn":
                    "2020-12-03T21:09:17Z",
                    "createdBy":
                    "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041"
                }
            })

    chat_client = ChatClient("https://endpoint",
                             credential,
                             transport=Mock(send=mock_send))

    topic = "test topic"
    user = CommunicationUserIdentifier(
        "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041")
    participants = [
        ChatParticipant(identifier=user,
                        display_name='name',
                        share_history_time=datetime.utcnow())
    ]
    create_chat_thread_result = await chat_client.create_chat_thread(
        topic, thread_participants=participants)
    assert create_chat_thread_result.chat_thread.id == thread_id
Exemplo n.º 10
0
    def test_add_participants(self):
        thread_id = "19:[email protected]"
        new_participant_id = "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041"
        raised = False

        def mock_send(*_, **__):
            return mock_response(status_code=201)

        chat_thread_client = ChatThreadClient("https://endpoint",
                                              TestChatThreadClient.credential,
                                              thread_id,
                                              transport=Mock(send=mock_send))

        new_participant = ChatParticipant(
            identifier=CommunicationUserIdentifier(new_participant_id),
            display_name='name',
            share_history_time=datetime.utcnow())
        participants = [new_participant]

        try:
            result = chat_thread_client.add_participants(participants)
        except:
            raised = True

        self.assertFalse(raised, 'Expected is no excpetion raised')
        self.assertTrue(len(result) == 0)
Exemplo n.º 11
0
 async def _create_thread_w_two_users(self):
     # create chat thread
     topic = "test topic"
     share_history_time = datetime.utcnow()
     share_history_time = share_history_time.replace(tzinfo=TZ_UTC)
     participants = [
         ChatParticipant(identifier=self.user,
                         display_name='name',
                         share_history_time=share_history_time),
         ChatParticipant(identifier=self.new_user,
                         display_name='name',
                         share_history_time=share_history_time)
     ]
     create_chat_thread_result = await self.chat_client.create_chat_thread(
         topic, thread_participants=participants)
     self.chat_thread_client = self.chat_client.get_chat_thread_client(
         create_chat_thread_result.chat_thread.id)
     self.thread_id = self.chat_thread_client.thread_id
Exemplo n.º 12
0
 def _create_thread(self, idempotency_token=None):
     # create chat thread
     topic = "test topic"
     share_history_time = datetime.utcnow()
     share_history_time = share_history_time.replace(tzinfo=TZ_UTC)
     participants = [ChatParticipant(
         identifier=self.user,
         display_name='name',
         share_history_time=share_history_time
     )]
     create_chat_thread_result = self.chat_client.create_chat_thread(topic,
                                                                     thread_participants=participants,
                                                                     idempotency_token=idempotency_token)
     self.thread_id = create_chat_thread_result.chat_thread.id
Exemplo n.º 13
0
    def test_add_participants(self):
        self._create_thread()

        share_history_time = datetime.utcnow()
        share_history_time = share_history_time.replace(tzinfo=TZ_UTC)
        new_participant = ChatParticipant(
                identifier=self.new_user,
                display_name='name',
                share_history_time=share_history_time)
        participants = [new_participant]

        failed_participants = self.chat_thread_client.add_participants(participants)

        # no error occured while adding participants
        assert len(failed_participants) == 0
Exemplo n.º 14
0
 def _create_thread(self, **kwargs):
     # create chat thread, and ChatThreadClient
     topic = "test topic"
     share_history_time = datetime.utcnow()
     share_history_time = share_history_time.replace(tzinfo=TZ_UTC)
     participants = [
         ChatParticipant(identifier=self.user,
                         display_name='name',
                         share_history_time=share_history_time)
     ]
     create_chat_thread_result = self.chat_client.create_chat_thread(
         topic, thread_participants=participants)
     self.chat_thread_client = self.chat_client.get_chat_thread_client(
         create_chat_thread_result.chat_thread.id)
     self.thread_id = self.chat_thread_client.thread_id
Exemplo n.º 15
0
def communication_chat_add_participant(client,
                                       thread_id,
                                       user_id,
                                       display_name=None,
                                       start_time=None):
    from azure.communication.chat import ChatParticipant
    from azure.communication.identity import CommunicationUserIdentifier

    chat_thread_client = client.get_chat_thread_client(thread_id)
    participant = ChatParticipant(
        identifier=CommunicationUserIdentifier(user_id),
        display_name=display_name,
        share_history_time=start_time)
    res = chat_thread_client.add_participants([participant])
    return [r[1] for r in res]
Exemplo n.º 16
0
    def test_remove_participant(self):
        self._create_thread()

        # add participant first
        share_history_time = datetime.utcnow()
        share_history_time = share_history_time.replace(tzinfo=TZ_UTC)
        new_participant = ChatParticipant(
                identifier=self.new_user,
                display_name='name',
                share_history_time=share_history_time)
        participants = [new_participant]

        self.chat_thread_client.add_participants(participants)

        # test remove participant
        self.chat_thread_client.remove_participant(self.new_user)
Exemplo n.º 17
0
    def test_add_participants_w_failed_participants_returns_nonempty_list(
            self):
        thread_id = "19:[email protected]"
        new_participant_id = "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041"
        raised = False
        error_message = "some error message"

        def mock_send(*_, **__):
            return mock_response(status_code=201,
                                 json_payload={
                                     "invalidParticipants": [{
                                         "code": "string",
                                         "message": error_message,
                                         "target": new_participant_id,
                                         "details": []
                                     }]
                                 })

        chat_thread_client = ChatThreadClient("https://endpoint",
                                              TestChatThreadClient.credential,
                                              thread_id,
                                              transport=Mock(send=mock_send))

        new_participant = ChatParticipant(
            identifier=CommunicationUserIdentifier(new_participant_id),
            display_name='name',
            share_history_time=datetime.utcnow())
        participants = [new_participant]

        try:
            result = chat_thread_client.add_participants(participants)
        except:
            raised = True

        self.assertFalse(raised, 'Expected is no excpetion raised')
        self.assertTrue(len(result) == 1)

        failed_participant = result[0][0]
        communication_error = result[0][1]

        self.assertEqual(new_participant.identifier.properties['id'],
                         failed_participant.identifier.properties['id'])
        self.assertEqual(new_participant.display_name,
                         failed_participant.display_name)
        self.assertEqual(new_participant.share_history_time,
                         failed_participant.share_history_time)
        self.assertEqual(error_message, communication_error.message)
    def test_create_chat_thread_w_repeatability_request_id(self):
        thread_id = "19:[email protected]"
        chat_thread_client = None
        raised = False
        idempotency_token = "b66d6031-fdcc-41df-8306-e524c9f226b8"

        def mock_send(*_, **__):
            return mock_response(
                status_code=201,
                json_payload={
                    "chatThread": {
                        "id":
                        thread_id,
                        "topic":
                        "test topic",
                        "createdOn":
                        "2020-12-03T21:09:17Z",
                        "createdBy":
                        "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041"
                    }
                })

        chat_client = ChatClient("https://endpoint",
                                 TestChatClient.credential,
                                 transport=Mock(send=mock_send))

        topic = "test topic"
        user = CommunicationUserIdentifier(
            "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041")
        participants = [
            ChatParticipant(identifier=user,
                            display_name='name',
                            share_history_time=datetime.utcnow())
        ]
        try:
            create_chat_thread_result = chat_client.create_chat_thread(
                topic=topic,
                thread_participants=participants,
                idempotency_token=idempotency_token)
        except:
            raised = True
            raise

        self.assertFalse(raised, 'Expected is no excpetion raised')
        assert create_chat_thread_result.chat_thread.id == thread_id
    async def test_add_participants(self):
        async with self.chat_client:
            await self._create_thread()

            async with self.chat_thread_client:
                share_history_time = datetime.utcnow()
                share_history_time = share_history_time.replace(tzinfo=TZ_UTC)
                new_participant = ChatParticipant(
                        identifier=self.new_user,
                        display_name='name',
                        share_history_time=share_history_time)
                participants = [new_participant]

                failed_participants = await self.chat_thread_client.add_participants(participants)

                # no error occured while adding participants
                assert len(failed_participants) == 0

            if not self.is_playback():
                await self.chat_client.delete_chat_thread(self.thread_id)
Exemplo n.º 20
0
    async def test_remove_participant(self):
        async with self.chat_client:
            await self._create_thread()

            async with self.chat_thread_client:
                # add participant first
                share_history_time = datetime.utcnow()
                share_history_time = share_history_time.replace(tzinfo=TZ_UTC)
                new_participant = ChatParticipant(
                    identifier=self.new_user,
                    display_name='name',
                    share_history_time=share_history_time)
                participants = [new_participant]

                await self.chat_thread_client.add_participants(participants)

                # test remove participant
                await self.chat_thread_client.remove_participant(self.new_user)

            if not self.is_playback():
                await self.chat_client.delete_chat_thread(self.thread_id)
Exemplo n.º 21
0
    def add_participants_w_check(self):
        # initially remove already added user
        thread_id = self._thread_id
        chat_client = self._chat_client
        user = self.new_user
        chat_thread_client = chat_client.get_chat_thread_client(
            thread_id=thread_id)

        chat_thread_client.remove_participant(user)

        # [START add_participants]
        from azure.communication.chat import ChatParticipant
        from datetime import datetime

        def decide_to_retry(error):
            """
            Custom logic to decide whether to retry to add or not
            """
            return True

        # set `thread_id` to an existing thread id
        chat_thread_client = chat_client.get_chat_thread_client(
            thread_id=thread_id)

        # create `user` using CommunicationIdentityClient.create_user method for new users;
        # else for existing users set `user` = CommunicationUserIdentifier(some_user_id)
        new_participant = ChatParticipant(identifier=user,
                                          display_name='name',
                                          share_history_time=datetime.utcnow())

        # create list containing one or more participants
        thread_participants = [new_participant]
        result = chat_thread_client.add_participants(thread_participants)

        # list of participants which were unsuccessful to be added to chat thread
        retry = [p for p, e in result if decide_to_retry(e)]
        if retry:
            chat_thread_client.add_participants(retry)
        # [END add_participants]
        print("add_participants_w_check succeeded")
    def test_create_chat_thread_raises_error(self):
        def mock_send(*_, **__):
            return mock_response(status_code=400,
                                 json_payload={"msg": "some error"})

        chat_client = ChatClient("https://endpoint",
                                 TestChatClient.credential,
                                 transport=Mock(send=mock_send))

        topic = "test topic",
        user = CommunicationUserIdentifier(
            "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041")
        thread_participants = [
            ChatParticipant(identifier=user,
                            display_name='name',
                            share_history_time=datetime.utcnow())
        ]

        self.assertRaises(HttpResponseError,
                          chat_client.create_chat_thread,
                          topic=topic,
                          thread_participants=thread_participants)
Exemplo n.º 23
0
    # # conversely, you can also add an existing user to a chat thread; provided the user_id is known
    # from azure.communication.identity import CommunicationUserIdentifier
    #
    # user_id = 'some user id'
    # user_display_name = "Wilma Flinstone"
    # new_user = CommunicationUserIdentifier(user_id)
    # participant = ChatParticipant(
    #     user=new_user,
    #     display_name=user_display_name,
    #     share_history_time=datetime.utcnow())

    participants = []
    for _user in new_users:
        chat_thread_participant = ChatParticipant(
            identifier=_user,
            display_name='Fred Flinstone',
            share_history_time=datetime.utcnow())
    participants.append(chat_thread_participant)

    response = chat_thread_client.add_participants(participants)

    def decide_to_retry(error, **kwargs):
        """
		Insert some custom logic to decide if retry is applicable based on error
		"""
        return True

    # verify if all users has been successfully added or not
    # in case of partial failures, you can retry to add all the failed participants
    retry = [p for p, e in response if decide_to_retry(e)]
    if retry: