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: azure.communication.chat._shared.user_credential_async.CommunicationTokenCredential, thread_id: str, **kwargs: Any)
Parameters
- credential
- CommunicationTokenCredential
The credentials with which to authenticate. The value contains a User Access Token
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
- thread_id
- str
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[azure.communication.chat._models.ChatParticipant], **kwargs) -> List[Tuple[azure.communication.chat._models.ChatParticipant, azure.communication.chat._generated.models._models_py3.ChatError]]
Parameters
- thread_participants
- <xref:List>[ChatParticipant]
Thread participants to be added to the thread.
Returns
List[Tuple[ChatParticipant, ChatError]]
Return type
Exceptions
Examples
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)
close
delete_message
Deletes a message.
async delete_message(message_id: str, **kwargs) -> None
Parameters
Returns
None
Return type
Exceptions
Examples
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)
get_message
Gets a message by id.
async get_message(message_id: str, **kwargs) -> azure.communication.chat._models.ChatMessage
Parameters
Returns
ChatMessage
Return type
Exceptions
Examples
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)
get_properties
Gets the properties of the chat thread.
async get_properties(**kwargs) -> azure.communication.chat._models.ChatThreadProperties
Returns
ChatThreadProperties
Return type
Exceptions
Examples
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
Gets a list of messages from a thread.
list_messages(**kwargs: Any) -> azure.core.async_paging.AsyncItemPaged[azure.communication.chat._models.ChatMessage]
Parameters
- 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
Exceptions
Examples
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
Gets the participants of a thread.
list_participants(**kwargs: Any) -> azure.core.async_paging.AsyncItemPaged[azure.communication.chat._models.ChatParticipant]
Parameters
- 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
Exceptions
Examples
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
Gets read receipts for a thread.
list_read_receipts(**kwargs: Any) -> azure.core.async_paging.AsyncItemPaged[azure.communication.chat._models.ChatMessageReadReceipt]
Parameters
- 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
Exceptions
Examples
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)
remove_participant
Remove a participant from a thread.
async remove_participant(identifier: azure.communication.chat._shared.models.CommunicationIdentifier, **kwargs) -> None
Parameters
- identifier
- CommunicationIdentifier
Required. Identifier of the thread participant to remove from the thread.
Returns
None
Return type
Exceptions
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) -> azure.communication.chat._generated.models._models_py3.SendChatMessageResult
Parameters
- chat_message_type
- <xref: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[<xref:str,>
Message metadata.
Returns
SendChatMessageResult
Return type
Exceptions
Examples
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)
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
Returns
None
Return type
Exceptions
Examples
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)
send_typing_notification
Posts a typing event to a thread, on behalf of a user.
async send_typing_notification(*, sender_display_name: Optional[str] = None, **kwargs) -> None
Parameters
- 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
Exceptions
Examples
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()
update_message
Updates a message.
async update_message(message_id: str, content: str = None, *, metadata: Dict[str, str] = None, **kwargs) -> None
Parameters
- content
Chat message content
- str] metadata
- dict[<xref:str,>
Message metadata.
Returns
None
Return type
Exceptions
Examples
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)
update_topic
Updates a thread's properties.
async update_topic(topic: str = None, **kwargs) -> None
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
Exceptions
Examples
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)
Attributes
thread_id
Feedback
Submit and view feedback for