azure-communication-chat-java
microsoft/skills
Создавайте приложения для чата в режиме реального времени с функциями управления потоками, обмена сообщениями, управления участниками и подтверждений прочтения с помощью Java SDK для чата Azure Communication Services.
...Расширить всеAzure Communication Chat (Java)
Создавайте приложения для чата в режиме реального времени с управлением нитями, обмен сообщениями, участниками и подтверждениями прочтения.
Установка
com.azure
azure-communication-chat
1.6.0
Создание клиента
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 требуется CommunicationTokenCredential (токен доступа пользователя)
String endpoint = "https://.communication.azure.com";
String userAccessToken = "";
CommunicationTokenCredential credential = new CommunicationTokenCredential(userAccessToken);
ChatClient chatClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
// Асинхронный клиент
ChatAsyncClient chatAsyncClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildAsyncClient();
Основные понятия
| Класс | Назначение |
|---|---|
ChatClient |
Создание/удаление чат-потоков, получение клиентов потока |
ChatThreadClient |
Операции внутри потока (сообщения, участники, подтверждения получения) |
ChatParticipant |
Пользователь в ветке чата с отображаемым именем |
ChatMessage |
Содержимое сообщения, тип, информация об отправителе, временные метки |
ChatMessageReadReceipt |
Отслеживание подтверждений прочтения по участникам |
Создать ветку чата
import com.azure.communication.chat.models.*;
import com.azure.communication.common.CommunicationUserIdentifier;
import java.util.ArrayList;
import java.util.List;
// Определение участников
List participants = new ArrayList<>();
ChatParticipant participant1 = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier(""))
.setDisplayName("Alice");
ChatParticipant participant2 = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier(""))
.setDisplayName("Bob");
participants.add(participant1);
participants.add(participant2);
// Создать ветку
CreateChatThreadOptions options = new CreateChatThreadOptions("Обсуждение проекта")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(options);
String threadId = result.getChatThread().getId();
// Получить клиент ветки для операций
ChatThreadClient threadClient = chatClient.getChatThreadClient(threadId);
Отправка сообщений
// Отправка текстового сообщения
SendChatMessageOptions messageOptions = new SendChatMessageOptions()
.setContent("Привет, команда!")
.setSenderDisplayName("Алиса")
.setType(ChatMessageType.TEXT);
SendChatMessageResult sendResult = threadClient.sendMessage(messageOptions);
String messageId = sendResult.getId();
// Отправить HTML-сообщение
SendChatMessageOptions htmlOptions = new SendChatMessageOptions()
.setContent("Важно: встреча в 15:00")
.setType(ChatMessageType.HTML);
threadClient.sendMessage(htmlOptions);
Получение сообщений
import com.azure.core.util.paging.PagedIterable;
// Список всех сообщений
PagedIterable messages = threadClient.listMessages();
for (ChatMessage message : messages) {
System.out.println("ID: " + message.getId());
System.out.println("Тип: " + message.getType());
System.out.println("Содержимое: " + message.getContent().getMessage());
System.out.println("Отправитель: " + message.getSenderDisplayName());
System.out.println("Создано: " + message.getCreatedOn());
// Проверить, было ли сообщение отредактировано или удалено
if (message.getEditedOn() != null) {
System.out.println("Отредактировано: " + message.getEditedOn());
}
if (message.getDeletedOn() != null) {
System.out.println("Удалено: " + message.getDeletedOn());
}
}
// Получить конкретное сообщение
ChatMessage message = threadClient.getMessage(messageId);
Обновление и удаление сообщений
// Обновление сообщения
UpdateChatMessageOptions updateOptions = new UpdateChatMessageOptions()
.setContent("Обновлённое содержание сообщения");
threadClient.updateMessage(messageId, updateOptions);
// Удаление сообщения
threadClient.deleteMessage(messageId);
Управление участниками
// Список участников
PagedIterable participants = threadClient.listParticipants();
for (ChatParticipant participant : participants) {
CommunicationUserIdentifier user =
(CommunicationUserIdentifier) participant.getCommunicationIdentifier();
System.out.println("Пользователь: " + user.getId());
System.out.println("Отображаемое имя: " + participant.getDisplayName());
}
// Добавление участников
List newParticipants = new ArrayList<>();
newParticipants.add(new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier(""))
.setDisplayName("Charlie")
.setShareHistoryTime(OffsetDateTime.now().minusDays(7))); // Поделиться историей за последние 7 дней
threadClient.addParticipants(newParticipants);
// Удалить участника
CommunicationUserIdentifier userToRemove = new CommunicationUserIdentifier("");
threadClient.removeParticipant(userToRemove);
Подтверждения прочтения
// Отправить подтверждение прочтения
threadClient.sendReadReceipt(messageId);
// Получить подтверждения прочтения
PagedIterable receipts = threadClient.listReadReceipts();
for (ChatMessageReadReceipt receipt : receipts) {
System.out.println("Идентификатор сообщения: " + receipt.getChatMessageId());
System.out.println("Прочитано: " + receipt.getSenderCommunicationIdentifier());
System.out.println("Прочитано: " + receipt.getReadOn());
}
Уведомления о вводе текста
import com.azure.communication.chat.models.TypingNotificationOptions;
// Отправить уведомление о наборе текста
TypingNotificationOptions typingOptions = new TypingNotificationOptions()
.setSenderDisplayName("Alice");
threadClient.sendTypingNotificationWithResponse(typingOptions, Context.NONE);
// Простое уведомление о вводе текста
threadClient.sendTypingNotification();
Операции с потоком
// Получение свойств темы
ChatThreadProperties properties = threadClient.getProperties();
System.out.println("Тема: " + properties.getTopic());
System.out.println("Создано: " + properties.getCreatedOn());
// Обновление темы
threadClient.updateTopic("Новая тема обсуждения проекта");
// Удаление темы
chatClient.deleteChatThread(threadId);
Список тем
// Список всех тем чата для пользователя
PagedIterable threads = chatClient.listChatThreads();
for (ChatThreadItem thread : threads) {
System.out.println("Идентификатор темы: " + thread.getId());
System.out.println("Тема: " + thread.getTopic());
System.out.println("Последнее сообщение: " + thread.getLastMessageReceivedOn());
}
Пагинация
import com.azure.core.http.rest.PagedResponse;
// Пагинация сообщений
int maxPageSize = 10;
ListChatMessagesOptions listOptions = new ListChatMessagesOptions()
.setMaxPageSize(maxPageSize);
PagedIterable pagedMessages = threadClient.listMessages(listOptions);
pagedMessages.iterableByPage().forEach(page -> {
System.out.println("Код состояния страницы: " + page.getStatusCode());
page.getElements().forEach(msg ->
System.out.println("Сообщение: " + msg.getContent().getMessage()));
});
Обработка ошибок
import com.azure.core.exception.HttpResponseException;
try {
threadClient.sendMessage(messageOptions);
} catch (HttpResponseException e) {
switch (e.getResponse().getStatusCode()) {
case 401:
System.out.println("Неавторизован — проверьте токен");
break;
case 403:
System.out.println("Запрещено — пользователь не входит в поток");
break;
case 404:
System.out.println("Поток не найден");
break;
default:
System.out.println("Ошибка: " + e.getMessage());
}
}
Типы сообщений
| Тип | Описание |
|---|---|
TEXT |
Обычное сообщение в чате |
HTML |
Сообщение в формате HTML |
TOPIC_UPDATED |
Системное сообщение — тема изменена |
PARTICIPANT_ADDED |
Системное сообщение — участник присоединился |
PARTICIPANT_REMOVED |
Системное сообщение — участник вышел |
Переменные среды
AZURE_COMMUNICATION_ENDPOINT=https://.communication.azure.com
AZURE_COMMUNICATION_USER_TOKEN=
Рекомендации
- Управление токенами — срок действия токенов пользователей истекает; реализуйте логику обновления с помощью
CommunicationTokenRefreshOptions - Пагинация — для больших цепочек сообщений используйте
listMessages(options)спараметром maxPageSize - История обмена — при добавлении участников задайте
параметр shareHistoryTime, чтобы контролировать видимость сообщений - Типы сообщений — фильтруйте системные сообщения (
PARTICIPANT_ADDEDи т. д.) из пользовательских сообщений - Подтверждения прочтения — отправляйте подтверждения только тогда, когда сообщения действительно просмотрены пользователем
Фразы-триггеры
- «приложение для чата на Java», «обмен сообщениями в реальном времени на Java»
- «ветка чата», «участники чата», «сообщения в чате»
- «подтверждения прочтения», «уведомления о вводе текста»
- «чат в Azure Communication Services»
---
name: azure-communication-chat-java
description: Build real-time chat applications with thread management, messaging, participants, and read receipts using the Azure Communication Services Chat Java SDK.
license: MIT
---
# Azure Communication Chat (Java)
Build real-time chat applications with thread management, messaging, participants, and read receipts.
## Installation
```xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-chat</artifactId>
<version>1.6.0</version>
</dependency>
```
## Client Creation
```java
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
```java
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
```java
// 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
```java
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
```java
// Update message
UpdateChatMessageOptions updateOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
threadClient.updateMessage(messageId, updateOptions);
// Delete message
threadClient.deleteMessage(messageId);
```
## Manage Participants
```java
// 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
```java
// 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
```java
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
```java
// 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
```java
// 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
```java
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
```java
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
```bash
AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.com
AZURE_COMMUNICATION_USER_TOKEN=<user-access-token>
```
## Best Practices
1. **Token Management** - User tokens expire; implement refresh logic with `CommunicationTokenRefreshOptions`
2. **Pagination** - Use `listMessages(options)` with `maxPageSize` for large threads
3. **Share History** - Set `shareHistoryTime` when adding participants to control message visibility
4. **Message Types** - Filter system messages (`PARTICIPANT_ADDED`, etc.) from user messages
5. **Read 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"
Все файлы
0 файловУстановить azure-communication-chat-java
Скачайте файлы навыков и распакуйте их в каталог .claude/skills/.
Скачать ZIPКлонируйте репозиторий и скопируйте файлы навыка в свой проект.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-communication-chat-java # Copy SKILL.md to your .claude/skills/ directory
Копировать





Дом
