azure.communication.chat package

class azure.communication.chat.ChatClient(endpoint: str, credential: CommunicationUserCredential, **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 by id, list chat threads, create chat thread client.

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

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

Example:

Creating the ChatClient from a URL and token.
from azure.communication.chat import ChatClient, CommunicationUserCredential
chat_client = ChatClient(self.endpoint, CommunicationUserCredential(self.token))
close()None[source]
create_chat_thread(topic: str, thread_members: list[ChatThreadMember], **kwargs: Any) → ChatThreadClient[source]

Creates a chat thread.

Parameters
  • topic (str) – Required. The thread topic.

  • thread_members (list[ChatThreadMember]) – Required. Members to be added to the thread.

Returns

ChatThreadClient

Return type

ChatThreadClient

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Creating ChatThreadClient by creating a new chat thread.
from datetime import datetime
from azure.communication.chat import(
    ChatClient,
    ChatThreadMember,
    CommunicationUser,
    CommunicationUserCredential
)

chat_client = ChatClient(self.endpoint, CommunicationUserCredential(self.token))

topic = "test topic"
members = [ChatThreadMember(
    user=self.user,
    display_name='name',
    share_history_time=datetime.utcnow()
)]
chat_thread_client = chat_client.create_chat_thread(topic, members)
delete_chat_thread(thread_id: str, **kwargs: Any)None[source]

Deletes a thread.

Parameters

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

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

None, or the result of cls(response)

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

deleting chat thread.
from azure.communication.chat import ChatClient, CommunicationUserCredential

chat_client = ChatClient(self.endpoint, CommunicationUserCredential(self.token))
chat_client.delete_chat_thread(self._thread_id)
get_chat_thread(thread_id: str, **kwargs: Any) → ChatThread[source]

Gets a chat thread.

Parameters

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

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

ChatThread, or the result of cls(response)

Return type

ChatThread

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Getting a chat thread by thread id.
from azure.communication.chat import ChatClient, CommunicationUserCredential

chat_client = ChatClient(self.endpoint, CommunicationUserCredential(self.token))
chat_thread = chat_client.get_chat_thread(self._thread_id)
get_chat_thread_client(thread_id: str, **kwargs: Any) → 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:

Creating the ChatThreadClient from an existing chat thread id.
from azure.communication.chat import ChatClient, CommunicationUserCredential

chat_client = ChatClient(self.endpoint, CommunicationUserCredential(self.token))
chat_thread_client = chat_client.get_chat_thread_client(self._thread_id)
list_chat_threads(**kwargs) → ItemPaged[ChatThreadInfo][source]

Gets the list of chat threads of a user.

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

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

  • cls (callable) – A custom type or function that will be passed the direct response

Returns

ItemPaged[ChatThreadInfo]

Return type

ItemPaged

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

listing chat threads.
from azure.communication.chat import ChatClient, CommunicationUserCredential
from datetime import datetime, timedelta
import pytz

chat_client = ChatClient(self.endpoint, CommunicationUserCredential(self.token))
start_time = datetime.utcnow() - timedelta(days=2)
start_time = start_time.replace(tzinfo=pytz.utc)
chat_thread_infos = 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.")
for info in chat_thread_infos:
    print("thread id:", info.id)
class azure.communication.chat.ChatThreadClient(endpoint: str, credential: CommunicationUserCredential, thread_id: str, **kwargs: Any)[source]

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

This client provides operations to add member to chat thread, remove member 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 (CommunicationUserCredential) – 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 import (
    ChatClient,
    ChatThreadMember,
    CommunicationUser,
    CommunicationUserCredential
)
chat_client = ChatClient(self.endpoint, CommunicationUserCredential(self.token))
topic = "test topic"
members = [ChatThreadMember(
    user=self.user,
    display_name='name',
    share_history_time=datetime.utcnow()
)]
chat_thread_client = chat_client.create_chat_thread(topic, members)
add_members(thread_members: list[ChatThreadMember], **kwargs: Any)None[source]

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

Parameters

thread_members (list[ChatThreadMember]) – Required. Thread members to be added to the thread.

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

None, or the result of cls(response)

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Adding members to chat thread.
from azure.communication.chat import ChatThreadMember
from datetime import datetime
new_member = ChatThreadMember(
        user=self.new_user,
        display_name='name',
        share_history_time=datetime.utcnow())
thread_members = [new_member]
chat_thread_client.add_members(thread_members)
close()None[source]
delete_message(message_id: str, **kwargs: Any)None[source]

Deletes a message.

Parameters

message_id (str) – Required. The message id.

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

None, or the result of cls(response)

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Deleting a messages.
chat_thread_client.delete_message(self._message_id)
get_message(message_id: str, **kwargs: Any) → ChatMessage[source]

Gets a message by id.

Parameters

message_id (str) – Required. The message id.

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

ChatMessage, or the result of cls(response)

Return type

ChatMessage

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Getting a message by message id.
chat_message = chat_thread_client.get_message(self._message_id)
list_members(**kwargs: Any) → ItemPaged[ChatThreadMember][source]

Gets the members of a thread.

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

ItemPaged[ChatThreadMember]

Return type

ItemPaged

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Listing members of chat thread.
chat_thread_members = chat_thread_client.list_members()
print("list_chat_members succeeded, members: ")
for chat_thread_member in chat_thread_members:
    print(chat_thread_member)
list_messages(**kwargs: Any) → ItemPaged[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.

  • cls (callable) – A custom type or function that will be passed the direct response

Returns

ItemPaged[ChatMessage]

Return type

ItemPaged

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Listing messages of a chat thread.
from datetime import datetime, timedelta
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():
    l = list(chat_message_page)
    print("page size: ", len(l))
list_read_receipts(**kwargs: Any) → ItemPaged[ReadReceipt][source]

Gets read receipts for a thread.

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

ItemPaged[ReadReceipt]

Return type

ItemPaged

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Listing read receipts.
read_receipts = chat_thread_client.list_read_receipts()
print("list_read_receipts succeeded, receipts:")
for read_receipt in read_receipts:
    print(read_receipt)
remove_member(user: CommunicationUser, **kwargs: Any)None[source]

Remove a member from a thread.

Parameters

user (CommunicationUser) – Required. User identity of the thread member to remove from the thread.

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

None, or the result of cls(response)

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Removing member from chat thread.
chat_thread_client.remove_member(self.new_user)
send_message(content: str, **kwargs: Any) → SendChatMessageResult[source]

Sends a message to a thread.

Parameters

content (str) – Required. Chat message content.

Keyword Arguments
  • priority (str or ChatMessagePriority) – Message priority.

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

  • cls (callable) – A custom type or function that will be passed the direct response

Returns

SendChatMessageResult, or the result of cls(response)

Return type

SendChatMessageResult

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Sending a message.
from azure.communication.chat import ChatMessagePriority

priority = ChatMessagePriority.NORMAL
content = 'hello world'
sender_display_name = 'sender name'

send_message_result = chat_thread_client.send_message(
    content,
    priority=priority,
    sender_display_name=sender_display_name)
send_read_receipt(message_id: str, **kwargs: Any)None[source]

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

Parameters

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

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

None, or the result of cls(response)

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Sending read receipt of a chat message.
chat_thread_client.send_read_receipt(self._message_id)
send_typing_notification(**kwargs: Any)None[source]

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

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

None, or the result of cls(response)

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Sending typing notification.
chat_thread_client.send_typing_notification()
update_message(message_id: str, content: Optional[str] = None, **kwargs: Any)None[source]

Updates a message.

Parameters
  • message_id (str) – Required. The message id.

  • content (str) – Chat message content.

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

None, or the result of cls(response)

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Updating a sent messages.
content = "updated content"
chat_thread_client.update_message(self._message_id, content=content)
update_thread(topic: Optional[str] = None, **kwargs: Any)None[source]

Updates a thread’s properties.

Parameters

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

Keyword Arguments

cls (callable) – A custom type or function that will be passed the direct response

Returns

None, or the result of cls(response)

Return type

None

Raises

~azure.core.exceptions.HttpResponseError, ValueError

Example:

Updating chat thread.
topic = "updated thread topic"
chat_thread_client.update_thread(topic=topic)
property thread_id

Gets the thread id from the client.

Return type

str

class azure.communication.chat.ChatMessage(**kwargs)[source]

ChatMessage.

Variables are only populated by the server, and will be ignored when sending a request.

Variables
  • id (str) – The id of the chat message. This id is server generated.

  • version (str) – Version of the chat message.

  • created_on (datetime) – The timestamp when the chat message arrived at the server. The timestamp is in ISO8601 format: yyyy-MM-ddTHH:mm:ssZ.

  • sender (CommunicationUser) – The chat message sender.

Parameters
  • type (str) – Type of the chat message. Possible values include: “Text”, “ThreadActivity/TopicUpdate”, “ThreadActivity/AddMember”, “ThreadActivity/DeleteMember”.

  • priority (str or ChatMessagePriority) – The chat message priority. Possible values include: “Normal”, “High”.

  • content (str) – Content of the chat message.

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

  • deleted_on (datetime) – The timestamp when the chat message was deleted. The timestamp is in ISO8601 format: yyyy-MM-ddTHH:mm:ssZ.

  • edited_on (datetime) – The timestamp when the chat message was edited. The timestamp is in ISO8601 format: yyyy-MM-ddTHH:mm:ssZ.

class azure.communication.chat.ChatMessagePriority[source]

The chat message priority.

HIGH = 'High'
NORMAL = 'Normal'
class azure.communication.chat.ReadReceipt(**kwargs)[source]

A read receipt indicates the time a chat message was read by a recipient.

Variables are only populated by the server, and will be ignored when sending a request.

Variables
  • sender – Read receipt sender.

  • chat_message_id (str) – Id for the chat message that has been read. This id is generated by the server.

  • read_on (datetime) – Read receipt timestamp. The timestamp is in ISO8601 format: yyyy-MM- ddTHH:mm:ssZ.

class azure.communication.chat.SendChatMessageResult(**kwargs)[source]

Result of the send message operation.

Variables are only populated by the server, and will be ignored when sending a request.

Variables

id (str) – A server-generated message id.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionaly use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod is_xml_model()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

validate()

Validate this model recursively and return a list of ValidationError.

Returns

A list of validation error

Return type

list

class azure.communication.chat.ChatThread(**kwargs)[source]

ChatThread.

Variables are only populated by the server, and will be ignored when sending a request.

Variables
  • id (str) – Chat thread id.

  • created_on (datetime) – The timestamp when the chat thread was created. The timestamp is in ISO8601 format: yyyy-MM-ddTHH:mm:ssZ.

  • created_by (CommunicationUser) – the chat thread owner.

Parameters
class azure.communication.chat.ChatThreadInfo(*, topic: Optional[str] = None, is_deleted: Optional[bool] = None, **kwargs)[source]

ChatThreadInfo.

Variables are only populated by the server, and will be ignored when sending a request.

Variables
  • id (str) – Chat thread id.

  • last_message_received_on (datetime) – The timestamp when the last message arrived at the server. The timestamp is in ISO8601 format: yyyy-MM-ddTHH:mm:ssZ.

Parameters
  • topic (str) – Chat thread topic.

  • is_deleted (bool) – Flag if a chat thread is soft deleted.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionaly use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod is_xml_model()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

validate()

Validate this model recursively and return a list of ValidationError.

Returns

A list of validation error

Return type

list

class azure.communication.chat.CommunicationUserCredential[source]

Credential type used for authenticating to an Azure Communication service. :param str token: The token used to authenticate to an Azure Communication service :raises: TypeError

get_token()[source]

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

ON_DEMAND_REFRESHING_INTERVAL_MINUTES = 2
class azure.communication.chat.ChatThreadMember(**kwargs)[source]

A member of the chat thread.

All required parameters must be populated in order to send to Azure.

Parameters
  • user (CommunicationUser) – Required. The CommunicationUser.

  • display_name (str) – Display name for the chat thread member.

  • share_history_time (datetime) – Time from which the chat history is shared with the member. The timestamp is in ISO8601 format: yyyy-MM-ddTHH:mm:ssZ.

class azure.communication.chat.CommunicationUser(identifier)[source]

Represents a user in Azure Communication Service. :ivar identifier: Communication user identifier. :vartype identifier: str :param identifier: Identifier to initialize CommunicationUser. :type identifier: str