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
- Inheritance
-
builtins.objectChatThreadClient
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 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)
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
add_participants(thread_participants: List[ChatParticipant], **kwargs: Any) -> 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.
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)
close
delete_message
Deletes a message.
delete_message(message_id: str, **kwargs: Any) -> 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.
# 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)
get_message
Gets a message by id.
get_message(message_id: str, **kwargs: Any) -> 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.
# 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)
get_properties
Gets the properties of the chat thread.
get_properties(**kwargs: Any) -> ChatThreadProperties
Returns
Type | Description |
---|---|
ChatThreadProperties |
Exceptions
Type | Description |
---|---|
Examples
Retrieving chat thread properties by chat thread id.
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)
list_messages
Gets a list of messages from a thread.
list_messages(**kwargs: Any) -> ItemPaged[ChatMessage]
Keyword-Only Parameters
Name | Description |
---|---|
results_per_page
|
The maximum number of messages to be returned per page. |
start_time
|
The earliest point in time to get messages up to.
The timestamp should be in RFC3339 format: |
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
# 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)
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) -> ItemPaged[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.
# 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("ChatParticipant: ", chat_thread_participant)
list_read_receipts
Gets read receipts for a thread.
list_read_receipts(**kwargs: Any) -> ItemPaged[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.
# 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)
remove_participant
Remove a participant from a thread.
remove_participant(identifier: CommunicationIdentifier, **kwargs: Any) -> 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()
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...")
send_message
Sends a message to a thread.
send_message(content: str, **kwargs: Any) -> 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. |
Returns
Type | Description |
---|---|
SendChatMessageResult |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Sending a 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)
send_read_receipt
Posts a read receipt event to a chat thread, on behalf of a user.
send_read_receipt(message_id: str, **kwargs: Any) -> 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.
# 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)
send_typing_notification
Posts a typing event to a thread, on behalf of a user.
send_typing_notification(**kwargs: Any) -> 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. |
Returns
Type | Description |
---|---|
None |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
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()
update_message
Updates a message.
update_message(message_id: str, content: str | None = None, **kwargs: Any) -> None
Parameters
Name | Description |
---|---|
message_id
Required
|
Required. The message id. |
content
Required
|
Chat message content. |
Keyword-Only Parameters
Name | Description |
---|---|
metadata
|
Message metadata. |
Returns
Type | Description |
---|---|
None |
Exceptions
Type | Description |
---|---|
<xref:azure.core.exceptions.HttpResponseError>, <xref:ValueError>
|
Examples
Updating an already sent 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)
update_topic
Updates a thread's properties.
update_topic(topic: str | None = None, **kwargs: Any) -> None
Parameters
Name | Description |
---|---|
topic
Required
|
Thread topic. If topic is not specified, the update will succeed but chat thread properties will not be changed. |
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
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)
Attributes
thread_id
Azure SDK for Python
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for