Sdílet prostřednictvím


Azure Communication Chat client library for .NET - version 1.3.1

This package contains a C# SDK for Azure Communication Services for chat.

Source code | Package (NuGet) | Product documentation

Getting started

Install the package

Install the Azure Communication Chat client library for .NET with NuGet:

dotnet add package Azure.Communication.Chat

Prerequisites

You need an Azure subscription and a Communication Service Resource to use this package.

To create a new Communication Service, you can use the Azure Portal, the Azure PowerShell, or the .NET management client library.

Authenticate the client

User Access Tokens

User access tokens enable you to build client applications that directly authenticate to Azure Communication Services. For the generation of user access tokens, refer to User Access Tokens.

Using statements

using Azure.Communication.Identity;
using Azure.Communication.Chat;

Create a ChatClient

This will allow you to create, get, or delete chat threads.

ChatClient chatClient = new ChatClient(
    endpoint,
    new CommunicationTokenCredential(userToken));

Create a ChatThreadClient

The ChatThreadClient will allow you to perform operations specific to a chat thread, like update the chat thread topic, send a message, add participants to the chat thread, etc.

You can instantiate a new ChatThreadClient using the GetChatThread operation of the ChatClient with an existing thread id:

ChatThreadClient chatThreadClient = chatClient.GetChatThreadClient(chatThread.Id);

Key concepts

A chat conversation is represented by a thread. Each user in the thread is called a thread participant. Thread participants can chat with one another privately in a 1:1 chat or huddle up in a 1:N group chat. Users also get near-real time updates for when others are typing and when they have read the messages.

Once you initialized a ChatClient class, you can do the following chat operations:

Create a thread

CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(topic: "Hello world!", participants: new ChatParticipant[] { });
ChatThreadProperties chatThread = createChatThreadResult.ChatThread;

Get a thread

ChatThread chatThread = chatClient.GetChatThread(chatThread.Id);

Get all threads for the user

Pageable<ChatThreadItem> threads = chatClient.GetChatThreads();

Delete a thread

chatClient.DeleteChatThread(chatThread.Id);

Once you initialized a ChatThreadClient class, you can do the following chat operations:

Update a thread

chatThreadClient.UpdateTopic(topic: "Launch meeting");

Send a message

SendChatMessageResult sendChatMessageResult = chatThreadClient.SendMessage("Let's meet at 11am");

Update a message

chatThreadClient.UpdateMessage(sendChatMessageResult.Id, content: "Instead of 11am, let's meet at 2pm");

Get a message

ChatMessage message = chatThreadClient.GetMessage(sendChatMessageResult.Id);

Delete a message

chatThreadClient.DeleteMessage(sendChatMessageResult.Id);

Get messages

Pageable<ChatMessage> messages = chatThreadClient.GetMessages();

Get a list of participants

Pageable<ChatParticipant> chatParticipants = chatThreadClient.GetParticipants();

Add participants

chatThreadClient.AddParticipants(participants: new[] { new ChatParticipant(participantIdentifier) });

Remove a participant

chatThreadClient.RemoveParticipant(identifier: participantIdentifier);

Send a typing notification

chatThreadClient.SendTypingNotification();

Get a list of read receipts

Pageable<ChatMessageReadReceipt> readReceipts = chatThreadClient.GetReadReceipts();

Send a read receipt

chatThreadClient.SendReadReceipt(sendChatMessageResult.Id);

Thread safety

We guarantee that all client instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing client instances is always safe, even across threads.

Additional concepts

Client options | Accessing the response | Long-running operations | Handling failures | Diagnostics | Mocking | Client lifetime

Examples

The following sections provide several code snippets covering some of the most common tasks, including:

Thread Operations

Create a thread

Use CreateChatThread to create a chat thread client object.

  • Use topic to give a thread topic.
  • The following are the supported attributes for each thread participant:
    • communicationUser, required, it is the identification for the thread participant.
    • displayName, optional, is the display name for the thread participant
    • shareHistoryTime, optional, time from which the chat history is shared with the participant.

ChatThreadClient is the result returned from creating a thread, you can use it to perform other operations on the chat thread.

ChatClient chatClient = new ChatClient(
    endpoint,
    new CommunicationTokenCredential(userToken));
var chatParticipant = new ChatParticipant(identifier: kimberly)
{
    DisplayName = "Kim"
};
CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(topic: "Hello world!", participants: new[] { chatParticipant });
string threadId = createChatThreadResult.ChatThread.Id;
ChatThreadClient chatThreadClient = chatClient.GetChatThreadClient(threadId);

Get a thread

Use GetChatThread to retrieve a chat thread from the service. threadId is the unique id of the thread.

ChatThreadProperties chatThread = await chatThreadClient.GetPropertiesAsync();

Get threads (for a participant)

Use GetChatThreads to get the list of chat threads for the participant that instantiated the chatClient.

AsyncPageable<ChatThreadItem> chatThreadItems = chatClient.GetChatThreadsAsync();
await foreach (ChatThreadItem chatThreadItem in chatThreadItems)
{
    Console.WriteLine($"{ chatThreadItem.Id}");
}

Delete a thread

Use DeleteChatThread to delete a thread. threadId is the unique id of the thread.

await chatClient.DeleteChatThreadAsync(threadId);

Update a thread

Use UpdateTopic to update the chat thread topic.

  • topic is used to describe the updated topic for the thread.
await chatThreadClient.UpdateTopicAsync(topic: "new topic !");

Message Operations

Send a message

Use SendMessage to send a message to a thread.

  • Use content to provide the content for the message, it is required.
  • Use type for the content type of the message such as 'Text' or 'Html'. If not specified, 'Text' will be set.
  • Use senderDisplayName to specify the display name of the sender. If not specified, empty string will be set.
SendChatMessageResult sendChatMessageResult = await chatThreadClient.SendMessageAsync(content:"hello world");
var messageId = sendChatMessageResult.Id;

Get a message

Use GetMessage to retrieve a message from the service. messageId is the unique id of the message.

ChatMessage is the response returned from getting a message, it contains an id, which is the unique identifier of the message, among other fields. Please refer to Azure.Communication.Chat.ChatMessage

ChatMessage chatMessage = await chatThreadClient.GetMessageAsync(messageId);

Get messages

Use GetMessages to retrieve all messages for the chat thread.

AsyncPageable<ChatMessage> allMessages = chatThreadClient.GetMessagesAsync();
await foreach (ChatMessage message in allMessages)
{
    Console.WriteLine($"{message.Id}:{message.Content.Message}");
}

Update a message

Use UpdateMessage to update a message.

  • messageId is the unique identifier of the message.
  • content is the message content to be updated.
await chatThreadClient.UpdateMessageAsync(messageId, "updated message content");

Delete a message

Use DeleteMessage to delete a message.

  • messageId is the unique identifier of the message.
await chatThreadClient.DeleteMessageAsync(messageId);

Thread Participant Operations

Get thread participants

Use GetParticipants to retrieve the participants of the chat thread.

AsyncPageable<ChatParticipant> allParticipants = chatThreadClient.GetParticipantsAsync();
await foreach (ChatParticipant participant in allParticipants)
{
    Console.WriteLine($"{((CommunicationUserIdentifier)participant.User).Id}:{participant.DisplayName}:{participant.ShareHistoryTime}");
}

Add thread participants

Use AddParticipants to add one or more participants to the chat thread. The following are the supported attributes for each thread participant(s):

  • communicationUser, required, it is the identification for the thread participant.
  • displayName, optional, is the display name for the thread participant.
  • shareHistoryTime, optional, time from which the chat history is shared with the participant.
var participants = new[]
{
    new ChatParticipant(josh) { DisplayName = "Josh" },
    new ChatParticipant(gloria) { DisplayName = "Gloria" },
    new ChatParticipant(amy) { DisplayName = "Amy" }
};

await chatThreadClient.AddParticipantsAsync(participants);

Remove thread participant

Use RemoveParticipant to remove a thread participant from the thread. communicationUser is the identification of the chat participant.

await chatThreadClient.RemoveParticipantAsync(gloria);

Events Operations

Send typing notification

Use SendTypingNotification to indicate that the user is typing a response in the thread.

await chatThreadClient.SendTypingNotificationAsync();

Send read receipt

Use SendReadReceipt to notify other participants that the message is read by the user.

await chatThreadClient.SendReadReceiptAsync(messageId);

Get read receipts

Use GetReadReceipts to check the status of messages to see which ones are read by other participants of a chat thread.

AsyncPageable<ChatMessageReadReceipt> allReadReceipts = chatThreadClient.GetReadReceiptsAsync();
await foreach (ChatMessageReadReceipt readReceipt in allReadReceipts)
{
    Console.WriteLine($"{readReceipt.ChatMessageId}:{((CommunicationUserIdentifier)readReceipt.Sender).Id}:{readReceipt.ReadOn}");
}

Troubleshooting

Service Responses

A RequestFailedException is thrown as a service response for any unsuccessful requests. The exception contains information about what response code was returned from the service.

try
{
    CreateChatThreadResult createChatThreadErrorResult = await chatClient.CreateChatThreadAsync(topic: "Hello world!", participants: new[] { josh });
}
catch (RequestFailedException ex)
{
    Console.WriteLine(ex.Message);
}

Next steps

Read more about Chat in Azure Communication Services

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit cla.microsoft.com.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.