Package: azure-communication-chat
Azure Communication Chat Package client library for PythonThis package contains a Python SDK for Azure Communication Services for Chat.
Read more about Azure Communication ServiceshereSource code|Package (Pypi)|Package (Conda)|API reference documentation|Product documentationDisclaimerAzure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer tohttps://github.com/Azure/azure-sdk-for-python/issues/20691Getting startedPrerequisitesPython 3.7 or later is required to use this package.A deployed Communication Services resource. You can use theAzure Portalor theAzure PowerShellto set it up.Install the packageInstall the Azure Communication Service Chat SDK.pipinstall--preazure-communication-chatUser Access TokensUser access tokens enable you to build client applications that directly authenticate to Azure Communication Services. You can generate these tokens with azure.communication.identity module, and then use them to initialize the Communication Services SDKs. Example of using azure.communication.identity:pipinstallazure-communication-identityfromazure.communication.identityimportCommunicationIdentityClientidentity_client=CommunicationIdentityClient.from_connection_string("<connection string of your Communication service>")user=identity_client.create_user()tokenresponse=identity_client.get_token(user,scopes=["chat"])token=tokenresponse.tokenTheusercreated above will be used later, because that user should be added as a participant of new chat thread when you creating
it with this token. It is because the initiator of the create request must be in the list of the participants of the chat thread.Create the Chat ClientThis will allow you to create, get, list or delete chat threads.fromazure.communication.chatimportChatClient,CommunicationTokenCredential# Your unique Azure Communication service endpointendpoint="https://<RESOURCE_NAME>.communcationservices.azure.com"chat_client=ChatClient(endpoint,CommunicationTokenCredential(token))Create Chat Thread ClientThe ChatThreadClient will allow you to perform operations specific to a chat thread, like send message, get message, update
the chat thread topic, add participants to chat thread, etc.You can get it by creating a new chat thread using ChatClient:create_chat_thread_result=chat_client.create_chat_thread(topic)chat_thread_client=chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id)Additionally, the client can also direct so that the request is repeatable; that is, if the client makes the
request multiple times with the same Idempotency-Token and it will get back an appropriate response without
the server executing the request multiple times. The value of the Idempotency-Token is an opaque string
representing a client-generated, globally unique for all time, identifier for the request.create_chat_thread_result=chat_client.create_chat_thread(topic,thread_participants=thread_participants,idempotency_token=idempotency_token)chat_thread_client=chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id)Alternatively, if you have created a chat thread before and you have its thread_id, you can create it by:chat_thread_client=chat_client.get_chat_thread_client(thread_id)# thread_id is the id of an existing chat threadKey conceptsA chat conversation is represented by a chat thread. Each user in the thread is called a thread participant.
Thread participants can chat with one another privately in a 1:1 chat or huddle up in a 1:N group chat.
Users also get near real-time updates for when others are typing and when they have read the messages.Once you initialized aChatClientclass, you can do the following chat operations:Create, get, update, and delete threadsPerform CRD(Create-Read-Delete) operations on threadscreate_chat_thread(topic,**kwargs)list_chat_threads(**kwargs)delete_chat_thread(thread_id,**kwargs)Once you initialized aChatThreadClientclass, you can do the following chat operations:Update threadPerform Update operation on thread topicupdate_topic(topic,**kwargs)Get Chat thread propertiesget_properties(**kwargs)Send, get, update, and delete messagesPerform CRUD(Create-Read-Update-Delete) operations on messagessend_message(content,**kwargs)get_message(message_id,**kwargs)list_messages(**kwargs)update_message(message_id,content,**kwargs)delete_message(message_id,**kwargs)Get, add, and remove participantsPerform CRD(Create-Read-Delete) operations on thread participantslist_participants(**kwargs)add_participants(thread_participants,**kwargs)remove_participant(participant_identifier,**kwargs)Send typing notificationNotify the service of typing notificationsend_typing_notification(**kwargs)Send and get read receiptNotify the service that a message is read and get list of read messages.send_read_receipt(message_id,**kwargs)list_read_receipts(**kwargs)ExamplesThe following sections provide several code snippets covering some of the most common tasks, including:Thread OperationsMessage OperationsThread Participant OperationsEvents OperationsThread OperationsCreate a threadUse thecreate_chat_threadmethod to create a chat thread.Usetopic, required, to give a thread topic;Usethread_participants, optional, to provide a list theChatParticipantto be added to the thread;user, required, it is theCommunicationUserIdentifieryou created by CommunicationIdentityClient.create_user()
from User Access Tokensdisplay_name, optional, is the display name for the thread participant.share_history_time, optional, time from which the chat history is shared with the participant.Useidempotency_token, optional, to specify the unique identifier for the request.CreateChatThreadResultis the result returned from creating a thread, you can use it to fetch theidof
the chat thread that got created. Thisidcan then be used to fetch aChatThreadClientobject using
theget_chat_thread_clientmethod.ChatThreadClientcan be used to perform other chat operations to this chat thread.# Without idempotency_token and thread_participantstopic="test topic"create_chat_thread_result=chat_client.create_chat_thread(topic)chat_thread_client=chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id)# With idempotency_token and thread_participantsfromazure.communication.identityimportCommunicationIdentityClientfromazure.communication.chatimportChatParticipant,ChatClient,CommunicationTokenCredentialimportuuidfromdatetimeimportdatetime# create an useridentity_client=CommunicationIdentityClient.from_connection_string('<connection_string>')user=identity_client.create_user()# user access tokenstokenresponse=identity_client.get_token(user,scopes=["chat"])token=tokenresponse.token## OR pass existing user# from azure.communication.chat import CommunicationUserIdentifier# user_id = 'some_user_id'# user = CommunicationUserIdentifier(user_id)# create the chat_clientendpoint="https://<RESOURCE_NAME>.communcationservices.azure.com"chat_client=ChatClient(endpoint,CommunicationTokenCredential(token))# modify function to implement customer logicdefget_unique_identifier_for_request(**kwargs):res=uuid.uuid4()returnrestopic="test topic"thread_participants=[ChatParticipant(identifier=user,display_name='name',share_history_time=datetime.utcnow())]# obtains idempotency_token using some customer logicidempotency_token=get_unique_identifier_for_request()create_chat_thread_result=chat_client.create_chat_thread(topic,thread_participants=thread_participants,idempotency_token=idempotency_token)thread_id=create_chat_thread_result.chat_thread.id# fetch ChatThreadClientchat_thread_client=chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id)# Additionally, you can also check if all participants were successfully added or not# and subsequently retry adding the failed participants againdefdecide_to_retry(error,**kwargs):"""Insert some custom logic to decide if retry is applicable based on error"""returnTrueretry=[thread_participantforthread_participant,errorincreate_chat_thread_result.errorsifdecide_to_retry(error)]ifretry:chat_thread_client.add_participants(retry)Get a threadUseget_propertiesmethod retrieves aChatThreadPropertiesfrom the service;thread_idis the unique ID of the thread.chat_thread_properties=chat_thread_client.get_properties()List chat threadsUselist_chat_threadsmethod retrieves the list of created chat threadsUseresults_per_page, optional, The maximum number of messages to be returned per page.Usestart_time, optional, The start time where the range query.An iterator of[ChatThreadItem]is the response returned from listing threadsfromazure.communication.chatimportChatClient,CommunicationTokenCredentialfromdatetimeimportdatetime,timedeltatoken="<token>"endpoint="https://<RESOURCE_NAME>.communcationservices.azure.com"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)forchat_thread_item_pageinchat_threads.by_page():forchat_thread_iteminchat_thread_item_page:print("thread id:",chat_thread_item.id)Update a thread topicUseupdate_topicmethod to update a thread's properties.topicis used to describe the change of the thread topicUsetopicto give thread a new topic;topic="new topic"chat_thread_client.update_topic(topic=topic)chat_thread=chat_thread_client.get_properties(thread_id)assertchat_thread.topic==topicDelete a threadUsedelete_chat_threadmethod to delete a thread;thread_idis the unique ID of the thread.Usethread_id, required, to specify the unique ID of the thread.chat_client.delete_chat_thread(thread_id=thread_id)Message OperationsSend a messageUsesend_messagemethod to sends a message to a thread identified bythread_id.Usecontent, required, to provide the chat message content.Usechat_message_type, optional, to provide the chat message type. Possible values include:ChatMessageType.TEXT,ChatMessageType.HTML,'text','html'; if not specified,ChatMessageType.TEXTwill be setUsesender_display_name,optional, to specify the display name of the sender, if not specified, empty name will be setSendChatMessageResultis the response returned from sending a message, it contains an id, which is the unique ID of the message.fromazure.communication.chatimportChatMessageTypetopic="test topic"create_chat_thread_result=chat_client.create_chat_thread(topic)thread_id=create_chat_thread_result.chat_thread.idchat_thread_client=chat_client.get_chat_thread_client(create_chat_thread_result.chat_thread.id)content='hello world'sender_display_name='sender name'chat_message_type=ChatMessageType.TEXT# without specifying sender_display_name and chat_message_typesend_message_result=chat_thread_client.send_message(content)send_message_result_id=send_message_result.idprint("Message sent: id: ",send_message_result_id)# specifying sender_display_name and chat_message_typesend_message_result_w_type=chat_thread_client.send_message(content,sender_display_name=sender_display_name,chat_message_type=chat_message_type# equivalent to chat_message_type = 'text')send_message_result_w_type_id=send_message_result_w_type.idprint("Message sent: id: ",send_message_result_w_type_id)Get a messageUseget_messagemethod retrieves a message from the service;message_idis the unique ID of the message.Usemessage_id,required, to specify message id of an existing messageChatMessageis the response returned from getting a message, it contains an id, which is the unique ID of the message, and other fields please refer to azure.communication.chat.ChatMessagechat_message=chat_thread_client.get_message(message_id=send_message_result_id)print("get_chat_message succeeded, message id:",chat_message.id,"content: ",chat_message.content)List messagesUselist_messagesmethod retrieves messages from the service.Useresults_per_page, optional, The maximum number of messages to be returned per page.Usestart_time, optional, The start time where the range query.An iterator of[ChatMessage]is the response returned from listing messagesfromdatetimeimportdatetime,timedeltastart_time=datetime.utcnow()-timedelta(days=1)chat_messages=chat_thread_client.list_messages(results_per_page=1,start_time=start_time)forchat_message_pageinchat_messages.by_page():forchat_messageinchat_message_page:print("ChatMessage: Id=",chat_message.id,"; Content=",chat_message.content.message)Update a messageUseupdate_messageto update a message identified by threadId and messageId.Usemessage_id,required, is the unique ID of the message.Usecontent, optional, is the message content to be updated; if not specified it is assigned to be emptycontent="updated message content"chat_thread_client.update_message(send_message_result_id,content=content)chat_message=chat_thread_client.get_message(message_id=send_message_result_id)assertchat_message.content.message==contentDelete a messageUsedelete_messageto delete a message.Usemessage_id, required, is the unique ID of the message.chat_thread_client.delete_message(message_id=send_message_result_id)Thread Participant OperationsList thread participantsUselist_participantsto retrieve the participants of the thread.Useresults_per_page, optional, The maximum number of participants to be returned per page.Useskip, optional, to skips participants up to a specified position in response.An iterator of[ChatParticipant]is the response returned from listing participantschat_participants=chat_thread_client.list_participants(results_per_page=5,skip=5)forchat_participant_pageinchat_participants.by_page():forchat_participantinchat_participant_page:print("ChatParticipant: ",chat_participant)Add thread participantsUseadd_participantsmethod to add thread participants to the thread.Usethread_participants, required, to list theChatParticipantto be added to the thread;user, required, it is theCommunicationUserIdentifieryou created by CommunicationIdentityClient.create_user() from User Access Tokensdisplay_name, optional, is the display name for the thread participant.share_history_time, optional, time from which the chat history is shared with the participant.Alist(tuple(ChatParticipant, ChatError))is returned. When participant is successfully added,
an empty list is expected. In case of an error encountered while adding participant, the list is populated
with the failed participants along with the error that was encountered.fromazure.communication.identityimportCommunicationIdentityClientfromazure.communication.chatimportChatParticipantfromdatetimeimportdatetime# create 2 usersidentity_client=CommunicationIdentityClient.from_connection_string('<connection_string>')new_users=[identity_client.create_user()foriinrange(2)]# # conversely, you can also add an existing user to a chat thread; provided the user_id is known# from azure.communication.chat import CommunicationUserIdentifier## user_id = 'some user id'# user_display_name = "Wilma Flinstone"# new_user = CommunicationUserIdentifier(user_id)# participant = ChatParticipant(#     identifier=new_user,#     display_name=user_display_name,#     share_history_time=datetime.utcnow())participants=[]for_userinnew_users:chat_participant=ChatParticipant(identifier=_user,display_name='Fred Flinstone',share_history_time=datetime.utcnow())participants.append(chat_participant)response=chat_thread_client.add_participants(thread_participants=participants)defdecide_to_retry(error,**kwargs):"""Insert some custom logic to decide if retry is applicable based on error"""returnTrue# verify if all users has been successfully added or not# in case of partial failures, you can retry to add all the failed participantsretry=[pforp,einresponseifdecide_to_retry(e)]ifretry:chat_thread_client.add_participants(retry)Remove thread participantUseremove_participantmethod to remove thread participant from the thread identified by threadId.identifieris theCommunicationUserIdentifieryou created by CommunicationIdentityClient.create_user() fromazure-communication-identityand was added into this chat thread.Useidentifierto specify theCommunicationUserIdentifieryou createdchat_thread_client.remove_participant(identifier=new_user)# # conversely you can also do the following; provided the user_id is known# from azure.communication.chat import CommunicationUserIdentifier## user_id = 'some user id'# chat_thread_client.remove_participant(identifier=CommunicationUserIdentifier(new_user))Events OperationsSend typing notificationUsesend_typing_notificationmethod to post a typing notification event to a thread, on behalf of a user.chat_thread_client.send_typing_notification()Send read receiptUsesend_read_receiptmethod to post a read receipt event to a thread, on behalf of a user.Usemessage_idto specify the id of the message whose read receipt is to be sentcontent='hello world'send_message_result=chat_thread_client.send_message(content)send_message_result_id=send_message_result.idchat_thread_client.send_read_receipt(message_id=send_message_result_id)List read receiptsUselist_read_receiptsmethod retrieves read receipts for a thread.Useresults_per_page, optional, The maximum number of read receipts to be returned per page.Useskip,optional, to skips read receipts up to a specified position in response.An iterator of[ChatMessageReadReceipt]is the response returned from listing read receiptsread_receipts=chat_thread_client.list_read_receipts(results_per_page=5,skip=5)forread_receipt_pageinread_receipts.by_page():forread_receiptinread_receipt_page:print(read_receipt)print(read_receipt.sender)print(read_receipt.chat_message_id)print(read_receipt.read_on)Sample CodeThese are code samples that show common scenario operations with the Azure Communication Chat client library.
The async versions of the samples (the python sample files appended with_async) show asynchronous operations.
Before run the sample code, refer to Prerequisitesto create a resource, then set some Environment VariablessetAZURE_COMMUNICATION_SERVICE_ENDPOINT="https://<RESOURCE_NAME>.communcationservices.azure.com"setCOMMUNICATION_SAMPLES_CONNECTION_STRING="<connection string of your Communication service>"pipinstallazure-communication-identity

pythonsamples\chat_client_sample.py
pythonsamples\chat_client_sample_async.py
pythonsamples\chat_thread_client_sample.py
pythonsamples\chat_thread_client_sample_async.pyTroubleshootingRunning into issues? This section should contain details as to what to do there.Next stepsMore sample code should gohere, along with links out to the appropriate example tests.ContributingIf you encounter any bugs or have suggestions, please file an issue in theIssuessection of the project.