Azure.Communication.Chat 1.3.0-beta.1

Prefix Reserved
This is a prerelease version of Azure.Communication.Chat.
There is a newer version of this package available.
See the version list below for details.
dotnet add package Azure.Communication.Chat --version 1.3.0-beta.1                
NuGet\Install-Package Azure.Communication.Chat -Version 1.3.0-beta.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Azure.Communication.Chat" Version="1.3.0-beta.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Azure.Communication.Chat --version 1.3.0-beta.1                
#r "nuget: Azure.Communication.Chat, 1.3.0-beta.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Azure.Communication.Chat as a Cake Addin
#addin nuget:?package=Azure.Communication.Chat&version=1.3.0-beta.1&prerelease

// Install Azure.Communication.Chat as a Cake Tool
#tool nuget:?package=Azure.Communication.Chat&version=1.3.0-beta.1&prerelease                

Azure Communication Chat client library for .NET

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

CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions("Hello world!");

createChatThreadOptions.Metadata.Add("MetadataKey1", "MetadataValue1");
createChatThreadOptions.Metadata.Add("MetadataKey2", "MetadataValue2");

createChatThreadOptions.RetentionPolicy = new ThreadCreationDateRetentionPolicy(40);

CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(createChatThreadOptions);
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

UpdateChatThreadPropertiesOptions updateChatThreadPropertiesOptions = new UpdateChatThreadPropertiesOptions();
updateChatThreadPropertiesOptions.Topic = "Launch meeting";
updateChatThreadPropertiesOptions.Metadata.Add("UpdateMetadataKey", "UpdateMetadataValue");
updateChatThreadPropertiesOptions.RetentionPolicy = new NoneRetentionPolicy();
await chatThreadClient.UpdatePropertiesAsync(updateChatThreadPropertiesOptions);

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"
};

chatParticipant.Metadata.Add("MetadataKey1", "MetadataValue1");
chatParticipant.Metadata.Add("MetadataKey2", "MetadataValue2");

CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions("Hello world!");

createChatThreadOptions.Participants.Add(chatParticipant);

createChatThreadOptions.Metadata.Add("MetadataKey1", "MetadataValue1");
createChatThreadOptions.Metadata.Add("MetadataKey2", "MetadataValue2");

createChatThreadOptions.RetentionPolicy = new ThreadCreationDateRetentionPolicy(60);

CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(createChatThreadOptions);
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 UpdatePropertiesAsync to update the chat thread topic or metadata.

UpdateChatThreadPropertiesOptions updateChatThreadPropertiesOptions = new UpdateChatThreadPropertiesOptions();
updateChatThreadPropertiesOptions.Topic = "new topic !";
updateChatThreadPropertiesOptions.Metadata.Add("UpdateMetadataKey", "UpdateMetadataValue");
updateChatThreadPropertiesOptions.RetentionPolicy = new ThreadCreationDateRetentionPolicy(60);
await chatThreadClient.UpdatePropertiesAsync(updateChatThreadPropertiesOptions);

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.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Azure.Communication.Chat:

Package Downloads
ToolsLibrary1

Package Description

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on Azure.Communication.Chat:

Repository Stars
Azure-Samples/communication-services-AI-customer-service-sample
A sample app for the customer support center running in Azure, using Azure Communication Services and Azure OpenAI for text and voice bots.
Version Downloads Last updated
1.3.1 14,920 9/19/2024
1.3.0 127,821 4/15/2024
1.3.0-beta.1 432 4/17/2024
1.2.0 71,843 12/4/2023
1.2.0-beta.1 7,424 8/15/2023
1.1.2 63,961 6/19/2023
1.1.1 256,769 9/16/2022
1.1.0 143,981 9/16/2021
1.1.0-beta.1 744 7/26/2021
1.0.1 39,986 5/11/2021
1.0.0 30,064 3/29/2021
1.0.0-beta.5 324 3/10/2021
1.0.0-beta.4 697 2/10/2021
1.0.0-beta.3 4,524 11/16/2020
1.0.0-beta.2 14,966 10/6/2020
1.0.0-beta.1 1,901 9/22/2020