azure.communication.chat.aio package

class azure.communication.chat.aio.ChatClient(endpoint: str, credential: azure.communication.chat._shared.user_credential_async.CommunicationTokenCredential, **kwargs: Any)[source]

A client to interact with the AzureCommunicationService Chat gateway.

This client provides operations to create chat thread, delete chat thread, get chat thread client by thread id, list chat threads.

Parameters
  • endpoint (str) – The endpoint of the Azure Communication resource.

  • credential (CommunicationTokenCredential) – The credentials with which to authenticate.

Example:

Creating the ChatClient from a URL and token.
from azure.communication.chat.aio import ChatClient, CommunicationTokenCredential

# set `endpoint` to an existing ACS endpoint
chat_client = ChatClient(endpoint, CommunicationTokenCredential(token))
async close()None[source]
async create_chat_thread(topic: str, **kwargs)azure.communication.chat._models.CreateChatThreadResult[source]

Creates a chat thread.

Parameters

topic (str) – Required. The thread topic.

Keyword Arguments
  • thread_participants (List[ChatParticipant]) – Optional. Participants to be added to the thread.

  • idempotency_token (str) – Optional. If specified, the client directs that the request is repeatable; that is, the client can make the request multiple times with the same Idempotency_Token and 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. If not specified, a new unique id would be generated.

Returns

CreateChatThreadResult

Return type

CreateChatThreadResult

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Creating a new chat thread.
 datetime import datetime
 azure.communication.chat.aio import ChatClient, CommunicationTokenCredential
 azure.communication.chat import ChatParticipant

t `endpoint` to an existing ACS endpoint
_client = ChatClient(endpoint, CommunicationTokenCredential(token))
c 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)
async delete_chat_thread(thread_id: str, **kwargs)None[source]

Deletes a chat thread.

Parameters

thread_id (str) – Required. Thread id to delete.

Returns

None

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Deleting a chat thread.
 azure.communication.chat.aio import ChatClient, CommunicationTokenCredential

t `endpoint` to an existing ACS endpoint
_client = ChatClient(endpoint, CommunicationTokenCredential(token))
c with chat_client:
# set `thread_id` to an existing chat thread id
await chat_client.delete_chat_thread(thread_id)
get_chat_thread_client(thread_id: str, **kwargs: Any)azure.communication.chat.aio._chat_thread_client_async.ChatThreadClient[source]

Get ChatThreadClient by providing a thread_id.

Parameters

thread_id (str) – Required. The thread id.

Returns

ChatThreadClient

Return type

ChatThreadClient

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Retrieving the ChatThreadClient from an existing chat thread id.
from azure.communication.chat.aio 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_thread_client = chat_client.get_chat_thread_client(thread_id)
list_chat_threads(**kwargs: Any)AsyncItemPaged[ChatThreadItem][source]

Gets the list of chat threads of a user.

Keyword Arguments
  • results_per_page (int) – The maximum number of chat threads to be returned per page.

  • start_time (datetime) – The earliest point in time to get chat threads up to.

Returns

An iterator like instance of ChatThreadItem

Return type

AsyncItemPaged[ChatThreadItem]

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Listing chat threads.
 azure.communication.chat.aio import ChatClient, CommunicationTokenCredential

t `endpoint` to an existing ACS endpoint
_client = ChatClient(endpoint, CommunicationTokenCredential(token))
c with chat_client:

from datetime import datetime, timedelta
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.")
async for chat_thread_item_page in chat_threads.by_page():
    async for chat_thread_item in chat_thread_item_page:
        print("thread id: ", chat_thread_item.id)
class azure.communication.chat.aio.ChatThreadClient(endpoint: str, credential: azure.communication.chat._shared.user_credential_async.CommunicationTokenCredential, thread_id: str, **kwargs: Any)[source]

A client to interact with the AzureCommunicationService Chat gateway. Instances of this class is normally retrieved by ChatClient.get_chat_thread_client()

This client provides operations to add participant(s) to chat thread, remove participant from chat thread, send message, delete message, update message, send typing notifications, send and list read receipt

Variables

thread_id (str) – Chat thread id.

Parameters
  • endpoint (str) – The endpoint of the Azure Communication resource.

  • credential (CommunicationTokenCredential) – The credentials with which to authenticate. The value contains a User Access Token

  • thread_id (str) – The unique thread id.

Example:

Creating the ChatThreadClient.
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)
async add_participants(thread_participants: List[azure.communication.chat._models.ChatParticipant], **kwargs)List[Tuple[azure.communication.chat._models.ChatParticipant, azure.communication.chat._generated.models._models_py3.ChatError]][source]

Adds thread participants to a thread. If participants already exist, no change occurs.

If all participants are added successfully, then an empty list is returned; otherwise, a list of tuple(chat_thread_participant, chat_error) is returned, of failed participants and its respective error

Parameters

thread_participants (List[ChatParticipant]) – Thread participants to be added to the thread.

Returns

List[Tuple[ChatParticipant, ChatError]]

Return type

List[Tuple[ChatParticipant, ChatError]]

Raises

~azure.core.exceptions.HttpResponseError

Example:

Adding participants to chat thread.
decide_to_retry(error):
"""
Custom logic to decide whether to retry to add or not
"""
return True

c 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)

async close()None[source]
async delete_message(message_id: str, **kwargs)None[source]

Deletes a message.

Parameters

message_id (str) – Required. The message id.

Returns

None

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Deleting a message.
c 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:
    # set `message_id` to an existing message id
    await chat_thread_client.delete_message(message_id)
async get_message(message_id: str, **kwargs)azure.communication.chat._models.ChatMessage[source]

Gets a message by id.

Parameters

message_id (str) – Required. The message id.

Returns

ChatMessage

Return type

ChatMessage

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Retrieving a message by message id.
c 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:
    # set `message_id` to an existing message id
    chat_message = await chat_thread_client.get_message(message_id)

    print("Message received: ChatMessage: content=", chat_message.content.message, ", id=", chat_message.id)
async get_properties(**kwargs)ChatThreadProperties[source]

Gets the properties of the chat thread.

Returns

ChatThreadProperties

Return type

ChatThreadProperties

Raises

~azure.core.exceptions.HttpResponseError

Example:

Retrieving chat thread properties by chat thread id.
 azure.communication.chat.aio import ChatClient, CommunicationTokenCredential

t `endpoint` to an existing ACS endpoint
_client = ChatClient(endpoint, CommunicationTokenCredential(token))
c with chat_client:
chat_thread_client = chat_client.get_chat_thread_client(thread_id)

async with chat_thread_client:
    chat_thread_properties = chat_thread_client.get_properties()
    print('Expected Thread Id: ', thread_id, ' Actual Value: ', chat_thread_properties.id)
list_messages(**kwargs: Any)AsyncItemPaged[ChatMessage][source]

Gets a list of messages from a thread.

Keyword Arguments
  • results_per_page (int) – The maximum number of messages to be returned per page.

  • start_time (datetime) – The start time where the range query.

Returns

An iterator like instance of ChatMessage

Return type

AsyncItemPaged[ChatMessage]

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Listing messages of a chat thread.
 datetime import datetime, timedelta
c 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:
    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")
    async for chat_message_page in chat_messages.by_page():
        async for chat_message in chat_message_page:
            print("ChatMessage: message=", chat_message.content.message)
list_participants(**kwargs: Any)AsyncItemPaged[ChatParticipant][source]

Gets the participants of a thread.

Keyword Arguments
  • results_per_page (int) – The maximum number of participants to be returned per page.

  • skip (int) – Skips participants up to a specified position in response.

Returns

An iterator like instance of ChatParticipant

Return type

AsyncItemPaged[ChatParticipant]

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Listing participants of chat thread.
c 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:
    chat_thread_participants = chat_thread_client.list_participants()
    print("list_participants succeeded, participants:")
    async for chat_thread_participant_page in chat_thread_participants.by_page():
        async for chat_thread_participant in chat_thread_participant_page:
            print("ChatParticipant: ", chat_thread_participant)
list_read_receipts(**kwargs: Any)AsyncItemPaged[ChatMessageReadReceipt][source]

Gets read receipts for a thread.

Keyword Arguments
  • results_per_page (int) – The maximum number of chat message read receipts to be returned per page.

  • skip (int) – Skips chat message read receipts up to a specified position in response.

Returns

An iterator like instance of ChatMessageReadReceipt

Return type

AsyncItemPaged[ChatMessageReadReceipt]

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Listing read receipts.
c 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:
    read_receipts = chat_thread_client.list_read_receipts()
    print("list_read_receipts succeeded, receipts:")
    async for read_receipt_page in read_receipts.by_page():
        async for read_receipt in read_receipt_page:
            print(read_receipt)
async remove_participant(identifier: azure.communication.chat._shared.models.CommunicationIdentifier, **kwargs)None[source]

Remove a participant from a thread.

Parameters

identifier (CommunicationIdentifier) – Required. Identifier of the thread participant to remove from the thread.

Returns

None

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Removing participant from chat thread.
    # Option 1 : Iterate through all participants, find and delete Fred Flinstone
    chat_thread_participants = chat_thread_client.list_participants()

    async for chat_thread_participant_page in chat_thread_participants.by_page():
        async 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!")
                await 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
    await chat_thread_client.remove_participant(CommunicationUserIdentifier(unique_identifier))
    print("Wilma has been removed from the thread...")
async send_message(content: str, *, metadata: Dict[str, str] = None, **kwargs)azure.communication.chat._generated.models._models_py3.SendChatMessageResult[source]

Sends a message to a thread.

Parameters

content (str) – Required. Chat message content.

Keyword Arguments
  • chat_message_type (Union[str, ChatMessageType]) – The chat message type. Possible values include: “text”, “html”. Default: ChatMessageType.TEXT

  • sender_display_name (str) – The display name of the message sender. This property is used to populate sender name for push notifications.

  • str] metadata (dict[str,) – Message metadata.

Returns

SendChatMessageResult

Return type

SendChatMessageResult

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Sending a message.
 azure.communication.chat import ChatMessageType
c with chat_client:
chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id)
async with chat_thread_client:
    # Scenario 1: Send message without specifying chat_message_type
    send_message_result = await chat_thread_client.send_message(
        "Hello! My name is Fred Flinstone",
        sender_display_name="Fred Flinstone",
        metadata={"tags": "tags"})
    send_message_result_id = send_message_result.id

    # Scenario 2: Send message specifying chat_message_type
    send_message_result_w_type = await 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
    chat_message_1 = await chat_thread_client.get_message(send_message_result_id)
    print("First Message:", chat_message_1.content.message, chat_message_1.metadata)
    print("Second Message:", (await chat_thread_client.get_message(send_message_result_w_type_id)).content.message)
async send_read_receipt(message_id: str, **kwargs)None[source]

Posts a read receipt event to a chat thread, on behalf of a user.

Parameters

message_id (str) – Required. Id of the latest message read by current user.

Returns

None

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Sending read receipt of a chat message.
c 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:
    # set `message_id` to an existing message id
    await chat_thread_client.send_read_receipt(message_id)
async send_typing_notification(*, sender_display_name: Optional[str] = None, **kwargs)None[source]

Posts a typing event to a thread, on behalf of a user.

Keyword Arguments

sender_display_name (str) – The display name of the typing notification sender. This property is used to populate sender name for push notifications.

Returns

None

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Send typing notification.
c 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:
    await chat_thread_client.send_typing_notification()
async update_message(message_id: str, content: str = None, *, metadata: Dict[str, str] = None, **kwargs)None[source]

Updates a message.

Parameters

message_id (str) – Required. The message id.

Keyword Arguments
  • content – Chat message content

  • str] metadata (dict[str,) – Message metadata.

Returns

None

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Updating an already sent message.
c 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:
    # set `message_id` to an existing message id
    previous_content = (await chat_thread_client.get_message(message_id)).content.message

    content = "updated message content"
    await chat_thread_client.update_message(self._message_id, content=content)

    current_content = (await chat_thread_client.get_message(message_id)).content.message

    print("Chat Message Updated: Previous value: ", previous_content, ", Current value: ", current_content)
async update_topic(topic: str = None, **kwargs)None[source]

Updates a thread’s properties.

Parameters

topic (str) – Thread topic. If topic is not specified, the update will succeed but chat thread properties will not be changed.

Returns

None

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Updating chat thread.
t `thread_id` to an existing thread id
c with chat_client:
chat_thread_client = chat_client.get_chat_thread_client(thread_id=thread_id)

async with chat_thread_client:
    chat_thread_properties = await chat_thread_client.get_properties()
    previous_topic = chat_thread_properties.topic

    topic = "updated thread topic"
    await chat_thread_client.update_topic(topic=topic)

    chat_thread_properties = await chat_thread_client.get_properties()
    updated_topic = chat_thread_properties.topic

    print("Chat Thread Topic Update: Previous value: ", previous_topic, ", Current value: ", updated_topic)
property thread_id

Gets the thread id from the client.

Return type

str

class azure.communication.chat.aio.CommunicationTokenCredential(token: str, **kwargs: Any)[source]

Credential type used for authenticating to an Azure Communication service. :param str token: The token used to authenticate to an Azure Communication service :keyword token_refresher: The async token refresher to provide capacity to fetch fresh token :raises: TypeError

async close()None[source]
async get_token(*scopes, **kwargs)[source]

The value of the configured token. :rtype: ~azure.core.credentials.AccessToken