Azure Communication Chat client library for .NET
Server Version: Chat client: 2020-09-21-preview2
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 --version 1.0.0-beta.1
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 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.Administration;
using Azure.Communication.Administration.Models;
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(
new Uri(endpoint),
new CommunicationUserCredential(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 members to the chat thread, etc.
You can instantiate a new ChatThreadClient instance using the ChatClient:
ChatThreadClient chatThreadClient1 = chatClient.CreateChatThread("Thread topic", members);
// Alternatively, if you have created a chat thread before and you have its threadId, you can create a ChatThreadClient instance using:
ChatThreadClient chatThreadClient2 = chatClient.GetChatThreadClient("threadId");
Key concepts
A chat conversation is represented by a thread. Each user in the thread is called a thread member. Thread members 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
To create a thread, see 'Create a ChatThreadClient' section
Get a thread
ChatThread chatThread = chatClient.GetChatThread(threadId);
Get all threads for the user
Pageable<ChatThreadInfo> threads = chatClient.GetChatThreadsInfo();
Delete a thread
chatClient.DeleteChatThread(threadId);
Once you initialized a ChatThreadClient
class, you can do the following chat operations:
Update a thread
chatThreadClient.UpdateThread("Updated topic - C# sdk");
Send a message
SendChatMessageResult sendChatMessageResult = chatThreadClient.SendMessage("This is message 1 content", ChatMessagePriority.High, displayNameMessage);
Get messages
ChatMessage message = chatThreadClient.GetMessage(messageId);
Pageable<ChatMessage> messages = chatThreadClient.GetMessages();
Update a message
chatThreadClient.UpdateMessage(messageId, "This is message 1 content updated");
Delete a message
chatThreadClient.DeleteMessage(messageId);
Get a list of members
Pageable<ChatThreadMember> chatThreadMembers = chatThreadClient.GetMembers();
Add members
chatThreadClient.AddMembers(members: new[] { newMember });
Remove a member
chatThreadClient.RemoveMember(user: memberToBeRemoved);
Send a typing notification
chatThreadClient.SendTypingNotification();
Get a list of read receipts
Pageable<ReadReceipt> readReceipts = chatThreadClient.GetReadReceipts();
Send a read receipt
chatThreadClient.SendReadReceipt(messageId);
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 member:
communicationUser
, required, it is the identification for the thread member.displayName
, optional, is the display name for the thread membershareHistoryTime
, optional, time from which the chat history is shared with the member.
ChatThreadClient
is the result returned from creating a thread, you can use it to perform other operations on the chat thread.
Important: Make sure the user creating the chat thread is explicitely added to the list of members, otherwise the creation call will fail.
ChatClient chatClient = new ChatClient(
new Uri(endpoint),
new CommunicationUserCredential(userToken));
var chatThreadMember = new ChatThreadMember(new CommunicationUser(threadCreatorId))
{
DisplayName = "UserDisplayName"
};
ChatThreadClient chatThreadClient = await chatClient.CreateChatThreadAsync(topic: "Hello world!", members: new[] { chatThreadMember });
string threadId = chatThreadClient.Id;
Get a thread
Use GetChatThread
to retrieve a chat thread from the service.
threadId
is the unique id of the thread.
ChatThread chatThread = await chatClient.GetChatThreadAsync(threadId);
Get threads (for a member)
Use GetChatThreadsInfo
to get the list of chat threads for the member that instantiated the chatClient.
AsyncPageable<ChatThreadInfo> chatThreadsInfo = chatClient.GetChatThreadsInfoAsync();
await foreach (ChatThreadInfo chatThreadInfo in chatThreadsInfo)
{
Console.WriteLine($"{ chatThreadInfo.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 UpdateChatThread
to update the chat thread properties.
topic
is used to describe the updated topic for the thread.
var topic = "new topic";
await chatThreadClient.UpdateThreadAsync(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
priority
to specify the message priority level, such as 'Normal' or 'High'.If not speficied, 'Normal' will be set. - Use
senderDisplayName
to specify the display name of the sender. If not specified, empty name will be set.
SendChatMessageResult
is the response returned from sending a message, it contains an id, which is the unique id of the message.
var content = "hello world";
var priority = ChatMessagePriority.Normal;
var senderDisplayName = "sender name";
SendChatMessageResult sendMessageResult = await chatThreadClient.SendMessageAsync(content, priority, senderDisplayName);
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.Sender.Id}:{message.Content}");
}
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 Member Operations
Get thread members
Use GetMembers
to retrieve the members of the chat thread.
AsyncPageable<ChatThreadMember> allMembers = chatThreadClient.GetMembersAsync();
await foreach (ChatThreadMember member in allMembers)
{
Console.WriteLine($"{member.User.Id}:{member.DisplayName}:{member.ShareHistoryTime}");
}
Add thread members
Use AddMembers
to add members to the chat thread. The following are the supported attributes for each thread member:
communicationUser
, required, it is the identification for the thread member.displayName
, optional, is the display name for the thread member.shareHistoryTime
, optional, time from which the chat history is shared with the member.
var members = new[]
{
new ChatThreadMember(new CommunicationUser(memberId1)) { DisplayName ="display name member 1"},
new ChatThreadMember(new CommunicationUser(memberId2)) { DisplayName ="display name member 2"},
new ChatThreadMember(new CommunicationUser(memberId3)) { DisplayName ="display name member 3"}
};
await chatThreadClient.AddMembersAsync(members);
Remove thread member
Use RemoveMember
to remove a thread member from the thread.
communicationUser
is the identification of the chat member.
await chatThreadClient.RemoveMemberAsync(new CommunicationUser(memberId));
Events Operations
Send typing notification
Use SendTypingNotification
to post a typing notification event to a chat thread, on behalf of a chat member.
await chatThreadClient.SendTypingNotificationAsync();
Send read receipt
Use SendReadReceipt
to post a read receipt event to a chat thread, on behalf of a chat member.
await chatThreadClient.SendReadReceiptAsync(messageId);
Get read receipts
Use GetReadReceipts
to retrieve a list of read receipts for a chat thread.
AsyncPageable<ReadReceipt> allReadReceipts = chatThreadClient.GetReadReceiptsAsync();
await foreach (ReadReceipt readReceipt in allReadReceipts)
{
Console.WriteLine($"{readReceipt.ChatMessageId}:{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
{
ChatThreadClient chatThreadClient_ = await chatClient.CreateChatThreadAsync(topic: "Hello world!", members: new[] { chatThreadMember });
}
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.