ChatThreadClient Class
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
Constructor
ChatThreadClient(endpoint: str, credential: CommunicationTokenCredential, thread_id: str, **kwargs: Any)
Parameters
Name | Description |
---|---|
endpoint
Required
|
The endpoint of the Azure Communication resource. |
credential
Required
|
The credentials with which to authenticate. The value contains a User Access Token |
thread_id
Required
|
The unique thread id. |
Examples
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)
Variables
Name | Description |
---|---|
thread_id
|
Chat thread id. |
Methods
add_participants |
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 |
close | |
delete_message |
Deletes a message. |
get_message |
Gets a message by id. |
get_properties |
Gets the properties of the chat thread. |
list_messages |
Gets a list of messages from a thread. |
list_participants |
Gets the participants of a thread. |
list_read_receipts |
Gets read receipts for a thread. |
remove_participant |
Remove a participant from a thread. |
send_message |
Sends a message to a thread. |
send_read_receipt |
Posts a read receipt event to a chat thread, on behalf of a user. |
send_typing_notification |
Posts a typing event to a thread, on behalf of a user. |
update_message |
Updates a message. |
update_topic |
Updates a thread's properties. |
add_participants
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
async add_participants(thread_participants: List[ChatParticipant], **kwargs) -> List[Tuple[ChatParticipant, ChatError]]
Parameters
Name | Description |
---|---|
thread_participants
Required
|
Thread participants to be added to the thread. |
Returns
Type | Description |
---|---|
List[Tuple[ChatParticipant, ChatError]] |
Exceptions
Type | Description |
---|---|
Examples
Adding participants to chat thread.
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)
close
async close() -> None
delete_message
Deletes a message.
async delete_message(message_id: str, **kwargs) -> None
Parameters
Name | Description |
---|---|
message_id
Required
|
Required. The message id. |
Returns
Type | Description |
---|---|
None |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Deleting a message.
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:
# set `message_id` to an existing message id
await chat_thread_client.delete_message(message_id)
get_message
Gets a message by id.
async get_message(message_id: str, **kwargs) -> ChatMessage
Parameters
Name | Description |
---|---|
message_id
Required
|
Required. The message id. |
Returns
Type | Description |
---|---|
ChatMessage |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Retrieving a message by message id.
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:
# 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)
get_properties
Gets the properties of the chat thread.
async get_properties(**kwargs) -> ChatThreadProperties
Returns
Type | Description |
---|---|
ChatThreadProperties |
Exceptions
Type | Description |
---|---|
Examples
Retrieving chat thread properties by chat thread id.
from azure.communication.chat.aio import ChatClient, CommunicationTokenCredential
# set `endpoint` to an existing ACS endpoint
chat_client = ChatClient(endpoint, CommunicationTokenCredential(token))
async 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
Gets a list of messages from a thread.
list_messages(**kwargs: Any) -> AsyncItemPaged[ChatMessage]
Keyword-Only Parameters
Name | Description |
---|---|
results_per_page
|
The maximum number of messages to be returned per page. |
start_time
|
The start time where the range query. |
Returns
Type | Description |
---|---|
An iterator like instance of ChatMessage |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Listing messages of a chat thread.
from datetime import datetime, timedelta
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:
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)
for attachment in chat_message.content.attachments:
if attachment.type == "image":
print("image attachment: ", attachment.name, " with ID: ", attachment.id, "received.")
# render `attachment.preview_url` as the thumbnail
# render `attachment.url` as the full image
elif attachment.type == "file":
print("file attachment: ", attachment.name, " with ID: ", attachment.id, "received.")
# render a button that will navigate user to the URL provided in `attachment.preview_url`
list_participants
Gets the participants of a thread.
list_participants(**kwargs: Any) -> AsyncItemPaged[ChatParticipant]
Keyword-Only Parameters
Name | Description |
---|---|
results_per_page
|
The maximum number of participants to be returned per page. |
skip
|
Skips participants up to a specified position in response. |
Returns
Type | Description |
---|---|
An iterator like instance of ChatParticipant |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Listing participants of chat thread.
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:
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
Gets read receipts for a thread.
list_read_receipts(**kwargs: Any) -> AsyncItemPaged[ChatMessageReadReceipt]
Keyword-Only Parameters
Name | Description |
---|---|
results_per_page
|
The maximum number of chat message read receipts to be returned per page. |
skip
|
Skips chat message read receipts up to a specified position in response. |
Returns
Type | Description |
---|---|
An iterator like instance of ChatMessageReadReceipt |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Listing read receipts.
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:
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)
remove_participant
Remove a participant from a thread.
async remove_participant(identifier: CommunicationIdentifier, **kwargs) -> None
Parameters
Name | Description |
---|---|
identifier
Required
|
Required. Identifier of the thread participant to remove from the thread. |
Returns
Type | Description |
---|---|
None |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
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...")
send_message
Sends a message to a thread.
async send_message(content: str, *, metadata: Dict[str, str] = None, **kwargs) -> SendChatMessageResult
Parameters
Name | Description |
---|---|
content
Required
|
Required. Chat message content. |
Keyword-Only Parameters
Name | Description |
---|---|
chat_message_type
|
The chat message type. Possible values include: "text", "html". Default: ChatMessageType.TEXT |
sender_display_name
|
The display name of the message sender. This property is used to populate sender name for push notifications. |
metadata
|
Message metadata. Default value: None
|
Returns
Type | Description |
---|---|
SendChatMessageResult |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Sending a message.
from azure.communication.chat import ChatMessageType
async 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)
send_read_receipt
Posts a read receipt event to a chat thread, on behalf of a user.
async send_read_receipt(message_id: str, **kwargs) -> None
Parameters
Name | Description |
---|---|
message_id
Required
|
Required. Id of the latest message read by current user. |
Returns
Type | Description |
---|---|
None |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Sending read receipt of a chat message.
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:
# set `message_id` to an existing message id
await chat_thread_client.send_read_receipt(message_id)
send_typing_notification
Posts a typing event to a thread, on behalf of a user.
async send_typing_notification(*, sender_display_name: str | None = None, **kwargs) -> None
Keyword-Only Parameters
Name | Description |
---|---|
sender_display_name
|
The display name of the typing notification sender. This property is used to populate sender name for push notifications. Default value: None
|
Returns
Type | Description |
---|---|
None |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Send typing notification.
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:
await chat_thread_client.send_typing_notification()
update_message
Updates a message.
async update_message(message_id: str, content: str = None, *, metadata: Dict[str, str] = None, **kwargs) -> None
Parameters
Name | Description |
---|---|
message_id
Required
|
Required. The message id. |
content
|
Chat message content Default value: None
|
Keyword-Only Parameters
Name | Description |
---|---|
metadata
|
Message metadata. Default value: None
|
Returns
Type | Description |
---|---|
None |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Updating an already sent message.
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:
# 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)
update_topic
Updates a thread's properties.
async update_topic(topic: str = None, **kwargs) -> None
Parameters
Name | Description |
---|---|
topic
|
Thread topic. If topic is not specified, the update will succeed but chat thread properties will not be changed. Default value: None
|
Returns
Type | Description |
---|---|
None |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Updating chat thread.
# set `thread_id` to an existing thread id
async 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)