Azure Communication Chat Java
MicrosoftOfficialCreated by Microsoft
- Skill
- Tool integration
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The Azure Communication Chat Java SDK provides a comprehensive set of tools for developers to build real-time chat functionality into their Java applications. It supports core messaging features including thread management, participant handling, read receipts, and typing notifications. The SDK offers both synchronous and asynchronous client patterns, allowing for flexible integration into various application architectures.
What it does
- Create and manage chat threads and their properties
- Send and receive text and HTML-formatted messages
- Manage chat participants, including adding and removing users
- Implement read receipts to track message status
- Send and receive typing notifications for real-time engagement
- List and paginate through chat history and thread metadata
When to use it
- When building real-time messaging features in a Java-based application
- When you need to manage chat threads and participant access control
- When implementing advanced chat features like read receipts or typing indicators
- When integrating Azure Communication Services into a backend service
Advantages
- Provides both synchronous and asynchronous client options
- Supports robust error handling for API interactions
- Includes built-in support for pagination of large message histories
- Offers granular control over participant history visibility
Usage examples
- “How do I create a new chat thread with two participants using the Java SDK?”
- The agent provides code to instantiate a ChatClient, define ChatParticipant objects with identifiers, and use CreateChatThreadOptions to initialize the thread.
- “Show me how to send a text message to an existing chat thread.”
- The agent demonstrates using the ChatThreadClient to send a SendChatMessageOptions object containing the message content and sender display name.
- “How can I list all messages in a chat thread with pagination?”
- The agent explains using ListChatMessagesOptions with a defined maxPageSize and iterating through the PagedIterable results.
- “How do I handle errors when sending a message?”
- The agent provides a try-catch block example using HttpResponseException to handle specific status codes like 401, 403, and 404.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/microsoft/azure-communication-chat-java/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip azure-communication-chat-java.zip -d .agents/skills
Documentation by Microsoft
Azure Communication Chat (Java)
Build real-time chat applications with thread management, messaging, participants, and read receipts.
Installation
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-chat</artifactId>
<version>1.6.0</version>
</dependency>Client Creation
import com.azure.communication.chat.ChatClient;
import com.azure.communication.chat.ChatClientBuilder;
import com.azure.communication.chat.ChatThreadClient;
import com.azure.communication.common.CommunicationTokenCredential;
// ChatClient requires a CommunicationTokenCredential (user access token)
String endpoint = "https://<resource>.communication.azure.com";
String userAccessToken = "<user-access-token>";
CommunicationTokenCredential credential = new CommunicationTokenCredential(userAccessToken);
ChatClient chatClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
// Async client
ChatAsyncClient chatAsyncClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildAsyncClient();Key Concepts
| Class | Purpose |
|---|---|
ChatClient | Create/delete chat threads, get thread clients |
ChatThreadClient | Operations within a thread (messages, participants, receipts) |
ChatParticipant | User in a chat thread with display name |
ChatMessage | Message content, type, sender info, timestamps |
ChatMessageReadReceipt | Read receipt tracking per participant |
Create Chat Thread
import com.azure.communication.chat.models.*;
import com.azure.communication.common.CommunicationUserIdentifier;
import java.util.ArrayList;
import java.util.List;
// Define participants
List<ChatParticipant> participants = new ArrayList<>();
ChatParticipant participant1 = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier("<user-id-1>"))
.setDisplayName("Alice");
ChatParticipant participant2 = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier("<user-id-2>"))
.setDisplayName("Bob");
participants.add(participant1);
participants.add(participant2);
// Create thread
CreateChatThreadOptions options = new CreateChatThreadOptions("Project Discussion")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(options);
String threadId = result.getChatThread().getId();
// Get thread client for operations
ChatThreadClient threadClient = chatClient.getChatThreadClient(threadId);Send Messages
// Send text message
SendChatMessageOptions messageOptions = new SendChatMessageOptions()
.setContent("Hello, team!")
.setSenderDisplayName("Alice")
.setType(ChatMessageType.TEXT);
SendChatMessageResult sendResult = threadClient.sendMessage(messageOptions);
String messageId = sendResult.getId();
// Send HTML message
SendChatMessageOptions htmlOptions = new SendChatMessageOptions()
.setContent("<strong>Important:</strong> Meeting at 3pm")
.setType(ChatMessageType.HTML);
threadClient.sendMessage(htmlOptions);Get Messages
import com.azure.core.util.paging.PagedIterable;
// List all messages
PagedIterable<ChatMessage> messages = threadClient.listMessages();
for (ChatMessage message : messages) {
System.out.println("ID: " + message.getId());
System.out.println("Type: " + message.getType());
System.out.println("Content: " + message.getContent().getMessage());
System.out.println("Sender: " + message.getSenderDisplayName());
System.out.println("Created: " + message.getCreatedOn());
// Check if edited or deleted
if (message.getEditedOn() != null) {
System.out.println("Edited: " + message.getEditedOn());
}
if (message.getDeletedOn() != null) {
System.out.println("Deleted: " + message.getDeletedOn());
}
}
// Get specific message
ChatMessage message = threadClient.getMessage(messageId);Update and Delete Messages
// Update message
UpdateChatMessageOptions updateOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
threadClient.updateMessage(messageId, updateOptions);
// Delete message
threadClient.deleteMessage(messageId);Manage Participants
// List participants
PagedIterable<ChatParticipant> participants = threadClient.listParticipants();
for (ChatParticipant participant : participants) {
CommunicationUserIdentifier user =
(CommunicationUserIdentifier) participant.getCommunicationIdentifier();
System.out.println("User: " + user.getId());
System.out.println("Display Name: " + participant.getDisplayName());
}
// Add participants
List<ChatParticipant> newParticipants = new ArrayList<>();
newParticipants.add(new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier("<new-user-id>"))
.setDisplayName("Charlie")
.setShareHistoryTime(OffsetDateTime.now().minusDays(7))); // Share last 7 days
threadClient.addParticipants(newParticipants);
// Remove participant
CommunicationUserIdentifier userToRemove = new CommunicationUserIdentifier("<user-id>");
threadClient.removeParticipant(userToRemove);Read Receipts
// Send read receipt
threadClient.sendReadReceipt(messageId);
// Get read receipts
PagedIterable<ChatMessageReadReceipt> receipts = threadClient.listReadReceipts();
for (ChatMessageReadReceipt receipt : receipts) {
System.out.println("Message ID: " + receipt.getChatMessageId());
System.out.println("Read by: " + receipt.getSenderCommunicationIdentifier());
System.out.println("Read at: " + receipt.getReadOn());
}Typing Notifications
import com.azure.communication.chat.models.TypingNotificationOptions;
// Send typing notification
TypingNotificationOptions typingOptions = new TypingNotificationOptions()
.setSenderDisplayName("Alice");
threadClient.sendTypingNotificationWithResponse(typingOptions, Context.NONE);
// Simple typing notification
threadClient.sendTypingNotification();Thread Operations
// Get thread properties
ChatThreadProperties properties = threadClient.getProperties();
System.out.println("Topic: " + properties.getTopic());
System.out.println("Created: " + properties.getCreatedOn());
// Update topic
threadClient.updateTopic("New Project Discussion Topic");
// Delete thread
chatClient.deleteChatThread(threadId);List Threads
// List all chat threads for the user
PagedIterable<ChatThreadItem> threads = chatClient.listChatThreads();
for (ChatThreadItem thread : threads) {
System.out.println("Thread ID: " + thread.getId());
System.out.println("Topic: " + thread.getTopic());
System.out.println("Last message: " + thread.getLastMessageReceivedOn());
}Pagination
import com.azure.core.http.rest.PagedResponse;
// Paginate through messages
int maxPageSize = 10;
ListChatMessagesOptions listOptions = new ListChatMessagesOptions()
.setMaxPageSize(maxPageSize);
PagedIterable<ChatMessage> pagedMessages = threadClient.listMessages(listOptions);
pagedMessages.iterableByPage().forEach(page -> {
System.out.println("Page status code: " + page.getStatusCode());
page.getElements().forEach(msg ->
System.out.println("Message: " + msg.getContent().getMessage()));
});Error Handling
import com.azure.core.exception.HttpResponseException;
try {
threadClient.sendMessage(messageOptions);
} catch (HttpResponseException e) {
switch (e.getResponse().getStatusCode()) {
case 401:
System.out.println("Unauthorized - check token");
break;
case 403:
System.out.println("Forbidden - user not in thread");
break;
case 404:
System.out.println("Thread not found");
break;
default:
System.out.println("Error: " + e.getMessage());
}
}Message Types
| Type | Description |
|---|---|
TEXT | Regular chat message |
HTML | HTML-formatted message |
TOPIC_UPDATED | System message - topic changed |
PARTICIPANT_ADDED | System message - participant joined |
PARTICIPANT_REMOVED | System message - participant left |
Environment Variables
AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.com
AZURE_COMMUNICATION_USER_TOKEN=<user-access-token>Best Practices
Token Management - User tokens expire; implement refresh logic with
CommunicationTokenRefreshOptionsPagination - Use
listMessages(options)withmaxPageSizefor large threadsShare History - Set
shareHistoryTimewhen adding participants to control message visibilityMessage Types - Filter system messages (
PARTICIPANT_ADDED, etc.) from user messagesRead Receipts - Send receipts only when messages are actually viewed by user
Trigger Phrases
"chat application Java", "real-time messaging Java"
"chat thread", "chat participants", "chat messages"
"read receipts", "typing notifications"
"Azure Communication Services chat"
Files
- ATTRIBUTION.mdAdded by AutoGineer994 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md9.3 KiB
- references/examples.md11.3 KiB
references/examples.md
Azure Communication Chat SDK for Java - Examples
Comprehensive code examples for the Azure Communication Chat SDK for Java.
Table of Contents
Maven Dependency
Client Creation
Creating Chat Threads
Sending Messages
Listing Messages
Adding and Removing Participants
Updating Thread Topic
Typing Notifications
Read Receipts
Async Client Patterns
Error Handling
Maven Dependency
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-chat</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-common</artifactId>
<version>1.3.8</version>
</dependency>Using Azure SDK BOM:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-sdk-bom</artifactId>
<version>{bom_version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-chat</artifactId>
</dependency>
</dependencies>Client Creation
Synchronous ChatClient
import com.azure.communication.chat.ChatClient;
import com.azure.communication.chat.ChatClientBuilder;
import com.azure.communication.common.CommunicationTokenCredential;
String endpoint = "https://<RESOURCE_NAME>.communication.azure.com";
String userAccessToken = "<USER_ACCESS_TOKEN>";
CommunicationTokenCredential credential = new CommunicationTokenCredential(userAccessToken);
ChatClient chatClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();Asynchronous ChatAsyncClient
import com.azure.communication.chat.ChatAsyncClient;
import com.azure.communication.chat.ChatClientBuilder;
ChatAsyncClient chatAsyncClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildAsyncClient();Get ChatThreadClient
import com.azure.communication.chat.ChatThreadClient;
String chatThreadId = "19:[email protected]";
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);Creating Chat Threads
import com.azure.communication.chat.models.ChatParticipant;
import com.azure.communication.chat.models.CreateChatThreadOptions;
import com.azure.communication.chat.models.CreateChatThreadResult;
import com.azure.communication.common.CommunicationUserIdentifier;
String userId1 = "<USER_Id1>";
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier(userId1))
.setDisplayName("Display Name 1");
String userId2 = "<USER_Id2>";
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier(userId2))
.setDisplayName("Display Name 2");
CreateChatThreadOptions createOptions = new CreateChatThreadOptions("Topic")
.addParticipant(firstParticipant)
.addParticipant(secondParticipant);
CreateChatThreadResult result = chatClient.createChatThread(createOptions);
String chatThreadId = result.getChatThread().getId();
// Get thread client
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);Using setParticipants
import java.util.ArrayList;
import java.util.List;
List<ChatParticipant> participants = new ArrayList<>();
participants.add(firstParticipant);
participants.add(secondParticipant);
CreateChatThreadOptions createOptions = new CreateChatThreadOptions("Topic")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(createOptions);Sending Messages
Send Text Message
import com.azure.communication.chat.models.ChatMessageType;
import com.azure.communication.chat.models.SendChatMessageOptions;
import com.azure.communication.chat.models.SendChatMessageResult;
SendChatMessageOptions sendOptions = new SendChatMessageOptions()
.setContent("Message content")
.setType(ChatMessageType.TEXT)
.setSenderDisplayName("Sender Display Name");
SendChatMessageResult sendResult = chatThreadClient.sendMessage(sendOptions);
String chatMessageId = sendResult.getId();Send Message with Metadata
import java.util.HashMap;
import java.util.Map;
Map<String, String> metadata = new HashMap<>();
metadata.put("hasAttachment", "true");
metadata.put("attachmentUrl", "https://contoso.com/files/attachment.docx");
SendChatMessageOptions sendOptions = new SendChatMessageOptions()
.setType(ChatMessageType.TEXT)
.setContent("Please take a look at the attachment")
.setSenderDisplayName("Sender")
.setMetadata(metadata);
SendChatMessageResult sendResult = chatThreadClient.sendMessage(sendOptions);Listing Messages
List All Messages
import com.azure.communication.chat.models.ChatMessage;
chatThreadClient.listMessages().forEach(message -> {
System.out.printf("Message id: %s%n", message.getId());
System.out.printf("Content: %s%n", message.getContent().getMessage());
});List with Pagination
import com.azure.core.http.rest.PagedIterable;
PagedIterable<ChatMessage> messages = chatThreadClient.listMessages();
messages.iterableByPage().forEach(page -> {
System.out.printf("Status: %d%n", page.getStatusCode());
page.getElements().forEach(message ->
System.out.printf("Message: %s%n", message.getId()));
});Get Specific Message
ChatMessage message = chatThreadClient.getMessage(chatMessageId);
System.out.printf("Content: %s%n", message.getContent().getMessage());Update Message
import com.azure.communication.chat.models.UpdateChatMessageOptions;
UpdateChatMessageOptions updateOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
chatThreadClient.updateMessage(chatMessageId, updateOptions);Delete Message
chatThreadClient.deleteMessage(chatMessageId);Check Message Status
chatThreadClient.listMessages().forEach(message -> {
// Check if deleted
if (message.getDeletedOn() != null) {
System.out.println("Deleted at: " + message.getDeletedOn());
}
// Check if edited
if (message.getEditedOn() != null) {
System.out.println("Edited at: " + message.getEditedOn());
}
// Message type
System.out.println("Type: " + message.getType());
});Adding and Removing Participants
Add Participants
import java.util.ArrayList;
import java.util.List;
List<ChatParticipant> participants = new ArrayList<>();
ChatParticipant newParticipant = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier("<USER_Id3>"))
.setDisplayName("Display Name 3");
participants.add(newParticipant);
chatThreadClient.addParticipants(participants);Add Participant with History Sharing
import java.time.OffsetDateTime;
ChatParticipant newParticipant = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier("<USER_ID>"))
.setDisplayName("New Participant")
.setShareHistoryTime(OffsetDateTime.MIN); // Share from beginning
List<ChatParticipant> participants = new ArrayList<>();
participants.add(newParticipant);
chatThreadClient.addParticipants(participants);Remove Participant
CommunicationUserIdentifier user = new CommunicationUserIdentifier("<USER_ID>");
chatThreadClient.removeParticipant(user);List Participants
import com.azure.communication.chat.models.ChatParticipant;
chatThreadClient.listParticipants().forEach(participant -> {
System.out.println("Participant: " + participant.getDisplayName());
});Updating Thread Topic
chatThreadClient.updateTopic("New Topic");Typing Notifications
Send Typing Notification
chatThreadClient.sendTypingNotification();Send with Options
import com.azure.communication.chat.models.TypingNotificationOptions;
TypingNotificationOptions options = new TypingNotificationOptions()
.setSenderDisplayName("Sender Name");
chatThreadClient.sendTypingNotificationWithResponse(options, null);Read Receipts
Send Read Receipt
chatThreadClient.sendReadReceipt(chatMessageId);List Read Receipts
import com.azure.communication.chat.models.ChatMessageReadReceipt;
chatThreadClient.listReadReceipts().forEach(receipt -> {
System.out.printf("Message ID: %s, Read by: %s at %s%n",
receipt.getChatMessageId(),
receipt.getSenderCommunicationIdentifier().getRawId(),
receipt.getReadOn());
});Async Client Patterns
Create Thread Async
chatAsyncClient.createChatThread(createOptions)
.subscribe(
result -> System.out.println("Thread ID: " + result.getChatThread().getId()),
error -> System.err.println("Error: " + error.getMessage())
);Send Message Async
ChatThreadAsyncClient asyncThreadClient = chatAsyncClient.getChatThreadClient(chatThreadId);
asyncThreadClient.sendMessage(sendOptions)
.subscribe(
result -> System.out.println("Message ID: " + result.getId()),
error -> System.err.println("Error: " + error.getMessage())
);List Messages Async
asyncThreadClient.listMessages()
.subscribe(
message -> System.out.println("Message: " + message.getId()),
error -> System.err.println("Error: " + error.getMessage())
);Chain Operations Async
chatAsyncClient.createChatThread(createOptions)
.flatMap(result -> {
String threadId = result.getChatThread().getId();
return chatAsyncClient.getChatThreadClient(threadId).sendMessage(sendOptions);
})
.subscribe(
sendResult -> System.out.println("Message sent: " + sendResult.getId()),
error -> System.err.println("Error: " + error.getMessage())
);Error Handling
Sync Error Handling
import com.azure.core.exception.HttpResponseException;
try {
chatThreadClient.sendMessage(sendOptions);
} catch (HttpResponseException e) {
System.err.println("HTTP Status: " + e.getResponse().getStatusCode());
System.err.println("Error: " + e.getMessage());
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}Async Error Handling
asyncThreadClient.sendMessage(sendOptions)
.subscribe(
result -> System.out.println("Success"),
error -> {
if (error instanceof HttpResponseException) {
HttpResponseException httpError = (HttpResponseException) error;
System.err.println("HTTP error: " + httpError.getResponse().getStatusCode());
} else {
System.err.println("Error: " + error.getMessage());
}
}
);Common Error Scenarios
| Status Code | Cause |
|---|---|
| 401 | Invalid or expired token |
| 403 | User not in thread |
| 404 | Thread or message not found |
| 429 | Rate limited |
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- Microsoft
- Publisher
- Microsoft (Official)
- Source
- microsoft/skills · .github/plugins/azure-sdk-java/skills/azure-communication-chat-java · commit 0696600
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Microsoft or Microsoft.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download azure-communication-chat-java.zip