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("專案討論")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(options);
String threadId = result.getChatThread().getId();
// 取得用於操作的討論串客戶端
ChatThreadClient threadClient = chatClient.getChatThreadClient(threadId);
傳送訊息
// 傳送文字訊息
SendChatMessageOptions messageOptions = new SendChatMessageOptions()
.setContent("大家好,團隊!")
.setSenderDisplayName("Alice")
.setType(ChatMessageType.TEXT);
SendChatMessageResult 傳送結果 = 對話串客戶端.sendMessage(訊息選項);
String 訊息 ID = 傳送結果.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.getTopic());
// 更新主題
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);
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_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
複製





首頁
