azure-communication-chat-java
microsoft/skills
Azure Communication Services Chat Java SDK を使用して、スレッド管理、メッセージング、参加者、既読通知機能を備えたリアルタイムチャットアプリケーションを構築します。
...すべて拡張します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("Project Discussion")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(options);
String threadId = result.getChatThread().getId();
// 操作用のスレッドクライアントを取得
ChatThreadClient threadClient = chatClient.getChatThreadClient(threadId);
メッセージの送信
// テキストメッセージを送信
SendChatMessageOptions messageOptions = new SendChatMessageOptions()
.setContent("Hello, team!")
.setSenderDisplayName("Alice")
.setType(ChatMessageType.TEXT);
SendChatMessageResult sendResult = threadClient.sendMessage(messageOptions);
String messageId = sendResult.getId();
// HTMLメッセージの送信
SendChatMessageOptions htmlOptions = new SendChatMessageOptions()
.setContent("重要:午後3時にミーティング")
.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("メッセージID: " + 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("スレッド ID: " + 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("Unauthorized - トークンを確認してください");
break;
case 403:
System.out.println("Forbidden - ユーザーがスレッドに存在しません");
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を使用して更新ロジックを実装してください。 - ページネーション- 大規模なスレッドでは、
maxPageSize を指定してlistMessages(options)を使用してください - 共有履歴- 参加者を追加する際は、
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
コピー





家
