def setUp(self): super(ChatThreadClientTest, self).setUp() self.recording_processors.extend([ BodyReplacerProcessor(keys=["id", "token", "senderId", "chatMessageId", "nextLink", "participants", "multipleStatus", "value"]), URIIdentityReplacer(), ChatURIReplacer()]) self.identity_client = CommunicationIdentityClient.from_connection_string( self.connection_str) endpoint, _ = parse_connection_str(self.connection_str) self.endpoint = endpoint # create user and issue token self.user = self.identity_client.create_user() tokenresponse = self.identity_client.get_token(self.user, scopes=["chat"]) self.token = tokenresponse.token # create another user self.new_user = self.identity_client.create_user() tokenresponse = self.identity_client.get_token(self.new_user, scopes=["chat"]) self.token_new_user = tokenresponse.token # create ChatClient refresh_options = CommunicationTokenRefreshOptions(self.token) refresh_options_new_user = CommunicationTokenRefreshOptions(self.token_new_user) self.chat_client = ChatClient(self.endpoint, CommunicationTokenCredential(refresh_options)) self.chat_client_new_user = ChatClient(self.endpoint, CommunicationTokenCredential(refresh_options_new_user))
def test_create_chat_thread(self): thread_id = "19:[email protected]" chat_thread_client = None raised = False def mock_send(*_, **__): return mock_response(status_code=207, json_payload={ "multipleStatus": [{ "id": thread_id, "statusCode": 201, "type": "Thread" }] }) chat_client = ChatClient("https://endpoint", TestChatClient.credential, transport=Mock(send=mock_send)) topic = "test topic" user = CommunicationUser( "8:acs:57b9bac9-df6c-4d39-a73b-26e944adf6ea_9b0110-08007f1041") members = [ ChatThreadMember(user=user, display_name='name', share_history_time=datetime.utcnow()) ] try: chat_thread_client = chat_client.create_chat_thread(topic, members) except: raised = True raise self.assertFalse(raised, 'Expected is no excpetion raised') assert chat_thread_client.thread_id == thread_id
def test_get_chat_thread(self): thread_id = "19:[email protected]" raised = False def mock_send(*_, **__): return mock_response(status_code=200, json_payload={ "id": thread_id, "topic": "Lunch Chat thread", "createdOn": "2020-10-30T10:50:50Z", "deletedOn": "2020-10-30T10:50:50Z", "createdByCommunicationIdentifier": { "rawId": "string", "communicationUser": { "id": "string" } } }) chat_client = ChatClient("https://endpoint", TestChatClient.credential, transport=Mock(send=mock_send)) get_thread_result = None try: get_thread_result = chat_client.get_chat_thread(thread_id) except: raised = True self.assertFalse(raised, 'Expected is no excpetion raised') assert get_thread_result.id == thread_id
def test_get_chat_thread(self): thread_id = "19:[email protected]" raised = False def mock_send(*_, **__): return mock_response(status_code=200, json_payload={ "id": thread_id, "created_by": "8:acs:resource_user", "participants": [{ "id": "", "display_name": "name", "share_history_time": "1970-01-01T00:00:00Z" }] }) chat_client = ChatClient("https://endpoint", TestChatClient.credential, transport=Mock(send=mock_send)) get_thread_result = None try: get_thread_result = chat_client.get_chat_thread(thread_id) except: raised = True self.assertFalse(raised, 'Expected is no excpetion raised') assert get_thread_result.id == thread_id
def create_thread(self): token = self.token endpoint = self.endpoint user = self.user # [START create_thread] from datetime import datetime from azure.communication.chat import (ChatClient, ChatParticipant, CommunicationUserIdentifier, CommunicationTokenCredential) # set `endpoint` to an existing ACS endpoint chat_client = ChatClient(endpoint, CommunicationTokenCredential(token)) topic = "test topic" participants = [ ChatParticipant(identifier=user, display_name='name', share_history_time=datetime.utcnow()) ] # creates a new chat_thread everytime create_chat_thread_result = 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 = 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)
def test_list_chat_threads(self): thread_id = "19:[email protected]" raised = False def mock_send(*_, **__): return mock_response(status_code=200, json_payload={"value": [{ "id": thread_id }]}) chat_client = ChatClient("https://endpoint", TestChatClient.credential, transport=Mock(send=mock_send)) chat_threads = None try: chat_threads = chat_client.list_chat_threads() except: raised = True self.assertFalse(raised, 'Expected is no excpetion raised') for chat_thread_item_page in chat_threads.by_page(): l = list(chat_thread_item_page) assert len(l) == 1 assert l[0].id == thread_id
def create_thread(self): # [START create_thread] from datetime import datetime from azure.communication.chat import( ChatClient, CommunicationUserIdentifier, CommunicationTokenCredential, CommunicationTokenRefreshOptions ChatThreadParticipant ) refresh_options = CommunicationTokenRefreshOptions(self.token) chat_client = ChatClient(self.endpoint, CommunicationTokenCredential(refresh_options)) topic = "test topic" participants = [ChatThreadParticipant( user=self.user, display_name='name', share_history_time=datetime.utcnow() )] # creates a new chat_thread everytime chat_thread_client = chat_client.create_chat_thread(topic, participants) # creates a new chat_thread if not exists repeatability_request_id = 'b66d6031-fdcc-41df-8306-e524c9f226b8' # unique identifier chat_thread_client_w_repeatability_id = chat_client.create_chat_thread(topic, participants, repeatability_request_id) # [END create_thread] self._thread_id = chat_thread_client.thread_id print("thread created, id: " + self._thread_id)
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.identity import CommunicationUserIdentifier from azure.communication.chat import ( ChatClient, ChatThreadParticipant, 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 = [ChatThreadParticipant( user=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")
def test_access_token_validation(self): """ This is to make sure that consecutive calls made using the same chat_client or chat_thread_client does not throw an exception due to mismatch in the generation of azure.core.credentials.AccessToken """ # create ChatClient chat_client = ChatClient(self.endpoint, CommunicationTokenCredential(self.token)) raised = False try: # create chat thread topic1 = "test topic1" create_chat_thread1_result = chat_client.create_chat_thread(topic1) self.thread_id = create_chat_thread1_result.chat_thread.id # get chat thread client chat_thread1_client = chat_client.get_chat_thread_client( self.thread_id) # list all chat threads chat_thead_infos = chat_client.list_chat_threads() for chat_threads_info_page in chat_thead_infos.by_page(): for chat_thread_info in chat_threads_info_page: print("ChatThreadInfo: ", chat_thread_info) except: raised = True assert raised is False
def setUp(self): super(ChatClientTest, self).setUp() self.recording_processors.extend([ BodyReplacerProcessor(keys=[ "id", "token", "createdBy", "participants", "multipleStatus", "value" ]), URIIdentityReplacer(), ChatURIReplacer() ]) self.identity_client = CommunicationIdentityClient.from_connection_string( self.connection_str) endpoint, _ = parse_connection_str(self.connection_str) self.endpoint = endpoint # create user and issue token self.user = self.identity_client.create_user() tokenresponse = self.identity_client.get_token(self.user, scopes=["chat"]) self.token = tokenresponse.token # create ChatClient self.chat_client = ChatClient(self.endpoint, CommunicationTokenCredential(self.token))
def get_thread(self): # [START get_thread] from azure.communication.chat import ChatClient, CommunicationTokenCredential, CommunicationTokenRefreshOptions refresh_options = CommunicationTokenRefreshOptions(self.token) chat_client = ChatClient(self.endpoint, CommunicationTokenCredential(refresh_options)) chat_thread = chat_client.get_chat_thread(self._thread_id) # [END get_thread] print("get_thread succeeded, thread id: " + chat_thread.id + ", thread topic: " + chat_thread.topic)
def get_chat_thread_client(self): # [START get_chat_thread_client] from azure.communication.chat import ChatClient, CommunicationTokenCredential, CommunicationTokenRefreshOptions refresh_options = CommunicationTokenRefreshOptions(self.token) chat_client = ChatClient(self.endpoint, CommunicationTokenCredential(refresh_options)) chat_thread_client = chat_client.get_chat_thread_client(self._thread_id) # [END get_chat_thread_client] print("chat_thread_client created with thread id: ", chat_thread_client.thread_id)
def delete_thread(self): # [START delete_thread] from azure.communication.chat import ChatClient, CommunicationTokenCredential chat_client = ChatClient(self.endpoint, CommunicationTokenCredential(self.token)) chat_client.delete_chat_thread(self._thread_id) # [END delete_thread] print("delete_thread succeeded")
def get_thread(self): # [START get_thread] from azure.communication.chat import ChatClient, CommunicationUserCredential chat_client = ChatClient(self.endpoint, CommunicationUserCredential(self.token)) chat_thread = chat_client.get_chat_thread(self._thread_id) # [END get_thread] print("get_thread succeeded, thread id: " + chat_thread.id + ", thread topic: " + chat_thread.topic)
def get_chat_thread_client(self): # [START get_chat_thread_client] from azure.communication.chat import ChatClient, CommunicationUserCredential chat_client = ChatClient(self.endpoint, CommunicationUserCredential(self.token)) chat_thread_client = chat_client.get_chat_thread_client( self._thread_id) # [END get_chat_thread_client] print("chat_thread_client created with thread id: ", chat_thread_client.thread_id)
def get_chat_thread_client(self): token = self.token endpoint = self.endpoint thread_id = self._thread_id # [START get_chat_thread_client] from azure.communication.chat import ChatClient, CommunicationTokenCredential chat_client = ChatClient(endpoint, CommunicationTokenCredential(token)) chat_thread_client = chat_client.get_chat_thread_client(thread_id) # [END get_chat_thread_client] print("get_chat_thread_client succeeded with thread id: ", chat_thread_client.thread_id)
def delete_thread(self): token = self.token endpoint = self.endpoint thread_id = self._thread_id # [START delete_thread] from azure.communication.chat import ChatClient, CommunicationTokenCredential # set `endpoint` to an existing ACS endpoint chat_client = ChatClient(endpoint, CommunicationTokenCredential(token)) # set `thread_id` to an existing chat thread id chat_client.delete_chat_thread(thread_id) # [END delete_thread] print("delete_thread succeeded")
def get_chat_thread_properties(self): thread_id = self._thread_id token = self.token endpoint = self.endpoint # [START get_thread] from azure.communication.chat import ChatClient, CommunicationTokenCredential # set `endpoint` to an existing ACS endpoint chat_client = ChatClient(endpoint, CommunicationTokenCredential(token)) chat_thread_client = chat_client.get_chat_thread_client(thread_id) chat_thread_properties = chat_thread_client.get_properties() print('Expected Thread Id: ', thread_id, ' Actual Value: ', chat_thread_properties.id) # [END get_thread] print("get_chat_thread_properties succeeded, thread id: " + chat_thread.id + ", thread topic: " + chat_thread.topic)
def list_threads(self): # [START list_threads] from azure.communication.chat import ChatClient, CommunicationTokenCredential, CommunicationTokenRefreshOptions from datetime import datetime, timedelta import pytz refresh_options = CommunicationTokenRefreshOptions(self.token) chat_client = ChatClient(self.endpoint, CommunicationTokenCredential(refresh_options)) start_time = datetime.utcnow() - timedelta(days=2) start_time = start_time.replace(tzinfo=pytz.utc) chat_thread_infos = chat_client.list_chat_threads(results_per_page=5, start_time=start_time) print("list_threads succeeded with results_per_page is 5, and were created since 2 days ago.") for info in chat_thread_infos: print("thread id:", info.id)
def create_chat_client(self): token = self.token endpoint = self.endpoint # [START create_chat_client] from azure.communication.chat import ChatClient, CommunicationTokenCredential chat_client = ChatClient(endpoint, CommunicationTokenCredential(token))
def test_delete_chat_thread(self): thread_id = "19:[email protected]" raised = False def mock_send(*_, **__): return mock_response(status_code=204) chat_client = ChatClient("https://endpoint", TestChatClient.credential, transport=Mock(send=mock_send)) try: chat_client.delete_chat_thread(thread_id) except: raised = True self.assertFalse(raised, 'Expected is no excpetion raised')
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
def get_chat_thread_properties(self): thread_id = self._thread_id # [START get_thread] from azure.communication.chat import ChatClient from azure.communication.identity._shared.user_credential import CommunicationTokenCredential from azure.communication.chat._shared.user_token_refresh_options import CommunicationTokenRefreshOptions refresh_options = CommunicationTokenRefreshOptions(self.token) chat_client = ChatClient(self.endpoint, CommunicationTokenCredential(refresh_options)) chat_thread_client = chat_client.get_chat_thread_client(thread_id) chat_thread_properties = chat_thread_client.get_properties() print('Expected Thread Id: ', thread_id, ' Actual Value: ', chat_thread_properties.id) # [END get_thread] print("get_chat_thread_properties succeeded, thread id: " + chat_thread.id + ", thread topic: " + chat_thread.topic)
def create_chat_thread_client(self): # [START create_chat_thread_client] from datetime import datetime from azure.communication.chat import (ChatClient, ChatThreadMember, CommunicationUser, CommunicationUserCredential) chat_client = ChatClient(self.endpoint, CommunicationUserCredential(self.token)) topic = "test topic" members = [ ChatThreadMember(user=self.user, display_name='name', share_history_time=datetime.utcnow()) ] chat_thread_client = chat_client.create_chat_thread(topic, members) # [END create_chat_thread_client] self._thread_id = chat_thread_client.thread_id print("chat_thread_client created")
def list_threads(self): token = self.token endpoint = self.endpoint # [START list_threads] from azure.communication.chat import ChatClient, CommunicationTokenCredential from datetime import datetime, timedelta chat_client = ChatClient(endpoint, CommunicationTokenCredential(token)) start_time = datetime.utcnow() - timedelta(days=2) chat_threads = chat_client.list_chat_threads(results_per_page=5, start_time=start_time) print( "list_threads succeeded with results_per_page is 5, and were created since 2 days ago." ) for chat_thread_item_page in chat_threads.by_page(): for chat_thread_item in chat_thread_item_page: print("thread id:", chat_thread_item.id)
def create_chat_thread_client(self): # [START create_chat_thread_client] from datetime import datetime from azure.communication.chat import ( ChatClient, CommunicationUserIdentifier, CommunicationTokenCredential, CommunicationTokenRefreshOptions, ChatThreadParticipant ) refresh_options = CommunicationTokenRefreshOptions(self.token) chat_client = ChatClient(self.endpoint, CommunicationTokenCredential(refresh_options)) topic = "test topic" participants = [ChatThreadParticipant( user=self.user, display_name='name', share_history_time=datetime.utcnow() )] chat_thread_client = chat_client.create_chat_thread(topic, participants) # [END create_chat_thread_client] self._thread_id = chat_thread_client.thread_id print("chat_thread_client created")
def cf_communication_chat(cli_ctx, kwargs): from azure.communication.chat import ChatClient, CommunicationTokenCredential endpoint = kwargs.pop('endpoint', None) if endpoint is None: raise RequiredArgumentMissingError( 'Please specify --endpoint, or set AZURE_COMMUNICATION_ENDPOINT.') token = kwargs.pop('access_token', None) if token is None: raise RequiredArgumentMissingError( 'Please specify --access-token or set AZURE_COMMUNICATION_ACCESS_TOKEN.' ) client = ChatClient(endpoint, CommunicationTokenCredential(token)) return client
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)
class ChatClientTest(CommunicationTestCase): def setUp(self): super(ChatClientTest, self).setUp() self.recording_processors.extend([ BodyReplacerProcessor(keys=["id", "token", "createdBy", "participants", "multipleStatus", "value"]), URIIdentityReplacer(), ChatURIReplacer()]) self.identity_client = CommunicationIdentityClient.from_connection_string( self.connection_str) endpoint, _ = parse_connection_str(self.connection_str) self.endpoint = endpoint # create user and issue token self.user = self.identity_client.create_user() tokenresponse = self.identity_client.get_token(self.user, scopes=["chat"]) self.token = tokenresponse.token # create ChatClient refresh_options = CommunicationTokenRefreshOptions(self.token) self.chat_client = ChatClient(self.endpoint, CommunicationTokenCredential(refresh_options)) def tearDown(self): super(ChatClientTest, self).tearDown() # delete created users and chat threads if not self.is_playback(): self.identity_client.delete_user(self.user) self.chat_client.delete_chat_thread(self.thread_id) def _create_thread(self, repeatability_request_id=None): # create chat thread topic = "test topic" share_history_time = datetime.utcnow() share_history_time = share_history_time.replace(tzinfo=TZ_UTC) participants = [ChatThreadParticipant( user=self.user, display_name='name', share_history_time=share_history_time )] chat_thread_client = self.chat_client.create_chat_thread(topic, participants, repeatability_request_id) self.thread_id = chat_thread_client.thread_id @pytest.mark.live_test_only def test_create_chat_thread(self): self._create_thread() assert self.thread_id is not None @pytest.mark.live_test_only def test_create_chat_thread_w_repeatability_request_id(self): repeatability_request_id = str(uuid4()) # create thread self._create_thread(repeatability_request_id=repeatability_request_id) thread_id = self.thread_id # re-create thread with same repeatability_request_id self._create_thread(repeatability_request_id=repeatability_request_id) # test idempotency assert thread_id == self.thread_id @pytest.mark.live_test_only def test_get_chat_thread(self): self._create_thread() get_thread_result = self.chat_client.get_chat_thread(self.thread_id) assert get_thread_result.id == self.thread_id @pytest.mark.live_test_only def test_list_chat_threads(self): self._create_thread() if self.is_live: time.sleep(2) chat_thread_infos = self.chat_client.list_chat_threads(results_per_page=1) for chat_thread_page in chat_thread_infos.by_page(): li = list(chat_thread_page) assert len(li) <= 1 @pytest.mark.live_test_only def test_get_thread_client(self): self._create_thread() chat_thread_client = self.chat_client.get_chat_thread_client(self.thread_id) assert chat_thread_client.thread_id == self.thread_id @pytest.mark.live_test_only def test_delete_chat_thread(self): self._create_thread() self.chat_client.delete_chat_thread(self.thread_id)
class ChatThreadClientSamples(object): from azure.communication.identity import CommunicationIdentityClient from azure.communication.chat import ( ChatClient, CommunicationTokenCredential ) connection_string = os.environ.get("AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING", None) if not connection_string: raise ValueError("Set AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING env before run this sample.") identity_client = CommunicationIdentityClient.from_connection_string(connection_string) user = identity_client.create_user() tokenresponse = identity_client.get_token(user, scopes=["chat"]) token = tokenresponse.token endpoint = os.environ.get("AZURE_COMMUNICATION_SERVICE_ENDPOINT", None) if not endpoint: raise ValueError("Set AZURE_COMMUNICATION_SERVICE_ENDPOINT env before run this sample.") _thread_id = None _message_id = None new_user = identity_client.create_user() _chat_client = ChatClient(endpoint, CommunicationTokenCredential(token)) 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.identity import CommunicationUserIdentifier from azure.communication.chat import ( ChatClient, ChatThreadParticipant, 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 = [ChatThreadParticipant( user=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") def get_chat_thread_properties(self): thread_id = self._thread_id token = self.token endpoint = self.endpoint # [START get_thread] from azure.communication.chat import ChatClient, CommunicationTokenCredential # set `endpoint` to an existing ACS endpoint chat_client = ChatClient(endpoint, CommunicationTokenCredential(token)) chat_thread_client = chat_client.get_chat_thread_client(thread_id) chat_thread_properties = chat_thread_client.get_properties() print('Expected Thread Id: ', thread_id, ' Actual Value: ', chat_thread_properties.id) # [END get_thread] print("get_chat_thread_properties succeeded, thread id: " + chat_thread.id + ", thread topic: " + chat_thread.topic) def update_topic(self): thread_id = self._thread_id chat_client = self._chat_client # [START update_topic] # set `thread_id` to an existing thread id chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) chat_thread_properties = chat_thread_client.get_properties() previous_topic = chat_thread_properties.topic topic = "updated thread topic" chat_thread_client.update_topic(topic=topic) chat_thread_properties = chat_thread_client.get_properties() updated_topic = chat_thread_properties.topic print("Chat Thread Topic Update: Previous value: ", previous_topic, ", Current value: ", updated_topic) # [END update_topic] print("update_chat_thread succeeded") def send_message(self): thread_id = self._thread_id chat_client = self._chat_client # [START send_message] from azure.communication.chat import ChatMessageType # set `thread_id` to an existing thread id chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) # Scenario 1: Send message without specifying chat_message_type send_message_result = chat_thread_client.send_message( "Hello! My name is Fred Flinstone", sender_display_name="Fred Flinstone") send_message_result_id = send_message_result.id # Scenario 2: Send message specifying chat_message_type send_message_result_w_type = chat_thread_client.send_message( "Hello! My name is Wilma Flinstone", sender_display_name="Wilma Flinstone", chat_message_type=ChatMessageType.TEXT) # equivalent to setting chat_message_type='text' send_message_result_w_type_id = send_message_result_w_type.id # Verify message content print("First Message:", chat_thread_client.get_message(send_message_result_id).content.message) print("Second Message:", chat_thread_client.get_message(send_message_result_w_type_id).content.message) # [END send_message] self._message_id = send_message_result_id print("send_message succeeded, message_id=", send_message_result_id) print("send_message succeeded with type specified, message_id:", send_message_result_w_type_id) def get_message(self): thread_id = self._thread_id chat_client = self._chat_client message_id = self._message_id # [START get_message] # set `thread_id` to an existing thread id chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) # set `message_id` to an existing message id chat_message = chat_thread_client.get_message(message_id) print("Message received: ChatMessage: content=", chat_message.content.message, ", id=", chat_message.id) # [END get_message] print("get_message succeeded, message id:", chat_message.id, \ "content: ", chat_message.content.message) def list_messages(self): thread_id = self._thread_id chat_client = self._chat_client # [START list_messages] from datetime import datetime, timedelta # set `thread_id` to an existing thread id chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) start_time = datetime.utcnow() - timedelta(days=1) chat_messages = chat_thread_client.list_messages(results_per_page=1, start_time=start_time) print("list_messages succeeded with results_per_page is 1, and start time is yesterday UTC") for chat_message_page in chat_messages.by_page(): for chat_message in chat_message_page: print("ChatMessage: message=", chat_message.content.message) # [END list_messages] print("list_messages succeeded") def update_message(self): thread_id = self._thread_id chat_client = self._chat_client message_id = self._message_id # [START update_message] # set `thread_id` to an existing thread id chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) # set `message_id` to an existing message id previous_content = chat_thread_client.get_message(message_id).content.message content = "updated content" chat_thread_client.update_message(message_id, content=content) current_content = chat_thread_client.get_message(message_id).content.message print("Chat Message Updated: Previous value: ", previous_content, ", Current value: ", current_content) # [END update_message] print("update_message succeeded") def send_read_receipt(self): thread_id = self._thread_id chat_client = self._chat_client message_id = self._message_id # [START send_read_receipt] # set `thread_id` to an existing thread id chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) # set `message_id` to an existing message id chat_thread_client.send_read_receipt(message_id) # [END send_read_receipt] print("send_read_receipt succeeded") def list_read_receipts(self): thread_id = self._thread_id chat_client = self._chat_client # [START list_read_receipts] # set `thread_id` to an existing thread id chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) read_receipts = chat_thread_client.list_read_receipts() for read_receipt_page in read_receipts.by_page(): for read_receipt in read_receipt_page: print(read_receipt) # [END list_read_receipts] print("list_read_receipts succeeded") def delete_message(self): thread_id = self._thread_id chat_client = self._chat_client message_id = self._message_id # [START delete_message] # set `thread_id` to an existing thread id chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) # set `message_id` to an existing message id chat_thread_client.delete_message(message_id) # [END delete_message] print("delete_message succeeded") def list_participants(self): thread_id = self._thread_id chat_client = self._chat_client # [START list_participants] # set `thread_id` to an existing thread id chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) 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("ChatThreadParticipant: ", chat_thread_participant) # [END list_participants] print("list_participants succeeded") 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 ChatThreadParticipant 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 = ChatThreadParticipant( user=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 remove_participant(self): thread_id = self._thread_id chat_client = self._chat_client identity_client = self.identity_client from azure.communication.chat import ChatThreadParticipant from azure.communication.identity import 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 = ChatThreadParticipant( user=user1, display_name='Fred Flinstone', share_history_time=datetime.utcnow()) participant2 = ChatThreadParticipant( user=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("ChatThreadParticipant: ", chat_thread_participant) if chat_thread_participant.user.identifier == user1.identifier: print("Found Fred!") chat_thread_client.remove_participant(chat_thread_participant.user) print("Fred has been removed from the thread...") break # Option 2: Directly remove Wilma Flinstone unique_identifier = user2.identifier # 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") def send_typing_notification(self): thread_id = self._thread_id chat_client = self._chat_client # [START send_typing_notification] # set `thread_id` to an existing thread id chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id) chat_thread_client.send_typing_notification() # [END send_typing_notification] print("send_typing_notification succeeded") def clean_up(self): print("cleaning up: deleting created users.") self.identity_client.delete_user(self.user) self.identity_client.delete_user(self.new_user)