azure-communication-chat-java について
azure-communication-chat-java は、Azure Communication Chat Java SDK を使ったリアルタイムチャットアプリ開発のスキルです。スレッドや参加者の管理に加え、メッセージ、既読レシート、入力通知を扱います。
主な機能
- 01チャットスレッドの作成と管理
- 02メッセージの送信、一覧、更新、削除
- 03参加者の一覧と管理
- 04既読レシートの送信と取得
- 05入力通知の送信
活用シーン
- 01Javaリアルタイムチャットアプリの構築
- 02会話と参加者の管理
- 03スレッド内のメッセージ既読状況の追跡
- 04チャットへの入力インジケーター追加
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-communication-chat-javaインストール後、Claude Code で/azure-communication-chat-javaを入力して読み込まれたか確認します。
詳細
Azure Communication Chat(Java)
スレッド管理、メッセージング、参加者、既読通知機能を備えたリアルタイムチャットアプリケーションを構築します。
プライバシーと書き込みの範囲
サンプルは独立した SDK のコード断片であり、テスト済みの完全なアプリケーションではありません。パッケージのバージョンを固定し、コンパイルする前に、そのバージョンに対してインポートと API シグネチャを確認してください。承認済みのテスト参加者と最小権限のユーザートークンを使用してください。メッセージの送信、既読通知や入力イベントの送信、履歴の表示範囲の変更、スレッドの削除には、それぞれ対応するユーザーの指示が必要です。ページネーションは最小限に抑え、共有ログに本番環境のメッセージ本文、トークン、参加者識別子を出力しないでください。受信した HTML を表示する場合は、適切なサニタイザーを使用してください。サーバーが受け入れたからといって、安全な UI マークアップであるとは限りません。
インストール
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-chat</artifactId>
<version>1.6.0</version>
</dependency>
クライアントの作成
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();
主な概念
| クラス | 用途 |
|---|---|
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;
// 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 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);
メッセージの取得
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 message
UpdateChatMessageOptions updateOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
threadClient.updateMessage(messageId, updateOptions);
// Delete message
threadClient.deleteMessage(messageId);
参加者の管理
// 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);
既読通知
// 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());
}
入力通知
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();
スレッドの操作
// 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 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());
}
ページネーション
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()));
});
エラー処理
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());
}
}
メッセージの種類
| 種類 | 説明 |
|---|---|
TEXT | 通常のチャットメッセージ |
HTML | HTML 形式のメッセージ |
TOPIC_UPDATED | システムメッセージ — トピックが変更されました |
PARTICIPANT_ADDED | システムメッセージ — 参加者が参加しました |
PARTICIPANT_REMOVED | システムメッセージ — 参加者が退出しました |
環境変数
AZURE_COMMUNICATION_ENDPOINT=https://<resource>.communication.azure.com
AZURE_COMMUNICATION_USER_TOKEN=<user-access-token>
ベストプラクティス
- トークン管理 - ユーザートークンには有効期限があります。
CommunicationTokenRefreshOptionsを使用して更新ロジックを実装してください - ページネーション - 大きなスレッドでは、
maxPageSizeを指定してlistMessages(options)を使用してください - 履歴の共有 - 参加者を追加する際に
shareHistoryTimeを設定し、メッセージの表示範囲を制御してください - メッセージの種類 - システムメッセージ(
PARTICIPANT_ADDEDなど)をユーザーメッセージから除外してください - 既読通知 - ユーザーが実際にメッセージを閲覧した場合にのみ通知を送信してください
トリガーフレーズ
- 「チャットアプリケーション Java」、「リアルタイムメッセージング Java」
- 「チャットスレッド」、「チャット参加者」、「チャットメッセージ」
- 「既読通知」、「入力通知」
- 「Azure Communication Services チャット」
使用するタイミング
このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適用できます。
制限事項
- タスクが上記の範囲に明確に合致する場合にのみ、このスキルを使用してください。
- 出力を、環境固有の検証、テスト、専門家によるレビューの代わりとして扱わないでください。
- 必要な入力、権限、安全上の境界、成功基準が不足している場合は、作業を中止して確認を求めてください。
コメント
Markdown 対応