適用於聊天的 Azure 通訊服務可讓開發人員將聊天功能新增至其應用程式。 使用此客戶端連結庫來管理聊天線程及其使用者,以及傳送和接收聊天訊息。
開始
先決條件
- Azure 訂用帳戶。
- 現有的通訊服務資源。 如果您需要建立資源,您可以使用 Azure 入口網站、Azure PowerShell或 Azure CLI。
- Node.js
安裝
npm install @azure/communication-chat
瀏覽器支援
JavaScript 套件組合
若要在瀏覽器中使用此用戶端連結庫,您必須先使用配套程式。 如需如何執行這項操作的詳細資訊,請參閱我們的 組合檔。
在 rollup.config.js中,在 cjs 外掛程式中新增下列自定義名稱匯出。
cjs({
namedExports: {
events: ["EventEmitter"],
"@azure/communication-signaling": ["CommunicationSignalingClient", "SignalingClient"],
"@opentelemetry/api": ["CanonicalCode", "SpanKind", "TraceFlags"]
}
})
重要概念
聊天交談是由對話表示。 線程中的每個用戶稱為聊天參與者。 聊天參與者可以在 1:1 聊天中私下聊天,或在 1:N 群組聊天中混在一起。 使用者也會在其他人輸入和讀取訊息時,取得近乎即時的更新。
聊天用戶端
ChatClient 是使用此用戶端連結庫的開發人員的主要介面。 它提供異步方法來建立和刪除線程。
ChatThreadClient
ChatThreadClient 提供異步方法,以在聊天對話中執行訊息和聊天參與者作業。
例子
初始化 ChatClient
使用資源 URL 和使用者存取令牌來初始化聊天用戶端。
import { AzureCommunicationTokenCredential } from "@azure/communication-common";
import { ChatClient } from "@azure/communication-chat";
// Your unique Azure Communication service endpoint
const endpointUrl = "<ENDPOINT>";
const userAccessToken = "<USER_ACCESS_TOKEN>";
const tokenCredential = new AzureCommunicationTokenCredential(userAccessToken);
const chatClient = new ChatClient(endpointUrl, tokenCredential);
建立具有兩個用戶的線程
使用 createThread 方法來建立聊天對話。
createChatThreadRequest 用來描述線程要求:
- 使用
topic提供線程主題;
createChatThreadOptions 用來設定選擇性參數來建立線程:
- 使用
participants列出要新增至線程的聊天參與者; - 使用
idempotencyToken來指定可重複的要求
createChatThreadResult 是建立線程所傳回的結果。 它包含 chatThread,這是已建立的線程,以及 errors 屬性,如果參與者無法新增至線程,則會包含無效參與者的相關信息。
import { AzureCommunicationTokenCredential } from "@azure/communication-common";
import { ChatClient } from "@azure/communication-chat";
// Your unique Azure Communication service endpoint
const endpointUrl = "<ENDPOINT>";
const userAccessToken = "<USER_ACCESS_TOKEN>";
const tokenCredential = new AzureCommunicationTokenCredential(userAccessToken);
const chatClient = new ChatClient(endpointUrl, tokenCredential);
const createChatThreadRequest = {
topic: "Hello, World!",
};
const createChatThreadOptions = {
participants: [
{
id: { communicationUserId: "<USER_ID>" },
displayName: "<USER_DISPLAY_NAME>",
},
],
};
const createChatThreadResult = await chatClient.createChatThread(
createChatThreadRequest,
createChatThreadOptions,
);
const threadId = createChatThreadResult?.chatThread?.id;
建立 ChatThreadClient
ChatThreadClient 可讓您執行聊天對話特定的作業,例如更新聊天對話主題、傳送訊息、將參與者新增至聊天對話等等。
您可以使用具有現有線程標識符的 ChatClient getChatThreadClient 方法,初始化新的 ChatThreadClient:
import { AzureCommunicationTokenCredential } from "@azure/communication-common";
import { ChatClient } from "@azure/communication-chat";
// Your unique Azure Communication service endpoint
const endpointUrl = "<ENDPOINT>";
const userAccessToken = "<USER_ACCESS_TOKEN>";
const tokenCredential = new AzureCommunicationTokenCredential(userAccessToken);
const chatClient = new ChatClient(endpointUrl, tokenCredential);
const chatThreadClient = chatClient.getChatThreadClient("<threadId>");
將訊息傳送至線程
使用 sendMessage 方法,將訊息傳送至 threadId 所識別的線程。
sendMessageRequest 用來描述訊息要求:
- 使用
content提供聊天訊息內容;
sendMessageOptions 用來描述作業選擇性參數:
- 使用
senderDisplayName來指定寄件人的顯示名稱; - 使用
type來指定訊息類型,例如 'text' 或 'html' ;
sendChatMessageResult 是從傳送訊息傳回的結果,其中包含標識符,這是訊息的唯一標識符。
import { AzureCommunicationTokenCredential } from "@azure/communication-common";
import { ChatClient, SendMessageOptions } from "@azure/communication-chat";
// Your unique Azure Communication service endpoint
const endpointUrl = "<ENDPOINT>";
const userAccessToken = "<USER_ACCESS_TOKEN>";
const tokenCredential = new AzureCommunicationTokenCredential(userAccessToken);
const chatClient = new ChatClient(endpointUrl, tokenCredential);
const chatThreadClient = chatClient.getChatThreadClient("<threadId>");
const sendMessageRequest = {
content: "Hello Geeta! Can you share the deck for the conference?",
};
const sendMessageOptions: SendMessageOptions = {
senderDisplayName: "Jack",
type: "text",
};
const sendChatMessageResult = await chatThreadClient.sendMessage(
sendMessageRequest,
sendMessageOptions,
);
const messageId = sendChatMessageResult.id;
從線程接收訊息
使用即時訊號,您可以訂閱接聽新的傳入訊息,並據以更新記憶體中的目前訊息。
import { AzureCommunicationTokenCredential } from "@azure/communication-common";
import { ChatClient } from "@azure/communication-chat";
// Your unique Azure Communication service endpoint
const endpointUrl = "<ENDPOINT>";
const userAccessToken = "<USER_ACCESS_TOKEN>";
const tokenCredential = new AzureCommunicationTokenCredential(userAccessToken);
const chatClient = new ChatClient(endpointUrl, tokenCredential);
// open notifications channel
await chatClient.startRealtimeNotifications();
// subscribe to new notification
chatClient.on("chatMessageReceived", (e) => {
console.log("Notification chatMessageReceived!");
// your code here
});
或者,您可以在指定的間隔輪詢 listMessages 方法來擷取聊天訊息。
import { AzureCommunicationTokenCredential } from "@azure/communication-common";
import { ChatClient } from "@azure/communication-chat";
// Your unique Azure Communication service endpoint
const endpointUrl = "<ENDPOINT>";
const userAccessToken = "<USER_ACCESS_TOKEN>";
const tokenCredential = new AzureCommunicationTokenCredential(userAccessToken);
const chatClient = new ChatClient(endpointUrl, tokenCredential);
const chatThreadClient = chatClient.getChatThreadClient("<threadId>");
for await (const chatMessage of chatThreadClient.listMessages()) {
// your code here
}
將使用者新增至線程
建立線程之後,您就可以從該線程新增和移除使用者。 藉由新增使用者,您可以授與他們能夠將訊息傳送至線程的存取權。 您必須從取得該使用者的新存取令牌和身分識別開始。 使用者需要該存取令牌,才能初始化其聊天用戶端。 如需令牌的詳細資訊,請參閱這裡:向 Azure 通訊服務驗證
import { AzureCommunicationTokenCredential } from "@azure/communication-common";
import { ChatClient } from "@azure/communication-chat";
// Your unique Azure Communication service endpoint
const endpointUrl = "<ENDPOINT>";
const userAccessToken = "<USER_ACCESS_TOKEN>";
const tokenCredential = new AzureCommunicationTokenCredential(userAccessToken);
const chatClient = new ChatClient(endpointUrl, tokenCredential);
const chatThreadClient = chatClient.getChatThreadClient("<threadId>");
const addParticipantsRequest = {
participants: [
{
id: { communicationUserId: "<NEW_PARTICIPANT_USER_ID>" },
displayName: "Jane",
},
],
};
await chatThreadClient.addParticipants(addParticipantsRequest);
從線程移除使用者
與上述類似,您也可以從線程中移除使用者。 若要移除,您必須追蹤您已新增之參與者的標識碼。
import { AzureCommunicationTokenCredential } from "@azure/communication-common";
import { ChatClient } from "@azure/communication-chat";
// Your unique Azure Communication service endpoint
const endpointUrl = "<ENDPOINT>";
const userAccessToken = "<USER_ACCESS_TOKEN>";
const tokenCredential = new AzureCommunicationTokenCredential(userAccessToken);
const chatClient = new ChatClient(endpointUrl, tokenCredential);
const chatThreadClient = chatClient.getChatThreadClient("<threadId>");
await chatThreadClient.removeParticipant({ communicationUserId: "<MEMBER_ID>" });
訂閱即時通知的連線狀態
事件訂閱 realTimeNotificationConnected 和 realTimeNotificationDisconnected 可讓您知道呼叫伺服器的連線何時作用中。
import { AzureCommunicationTokenCredential } from "@azure/communication-common";
import { ChatClient } from "@azure/communication-chat";
// Your unique Azure Communication service endpoint
const endpointUrl = "<ENDPOINT>";
const userAccessToken = "<USER_ACCESS_TOKEN>";
const tokenCredential = new AzureCommunicationTokenCredential(userAccessToken);
const chatClient = new ChatClient(endpointUrl, tokenCredential);
// subscribe to realTimeNotificationConnected event
chatClient.on("realTimeNotificationConnected", () => {
console.log("Real time notification is now connected!");
// your code here
});
// subscribe to realTimeNotificationDisconnected event
chatClient.on("realTimeNotificationDisconnected", () => {
console.log("Real time notification is now disconnected!");
// your code here
});
故障排除
森林伐木業
啟用記錄可能有助於找出有關失敗的實用資訊。 若要查看 HTTP 要求和回應的記錄,請將 AZURE_LOG_LEVEL 環境變數設定為 info。 或者,您可以在運行時間啟用記錄,方法是在 setLogLevel中呼叫 @azure/logger:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
後續步驟
在本快速入門中,您已瞭解如何:
- 建立聊天用戶端
- 建立具有 2 個用戶的線程
- 將訊息傳送至線程
- 從線程接收訊息
- 從線程移除使用者
貢獻
如果您想要參與此連結庫,請閱讀 參與指南,以深入瞭解如何建置和測試程序代碼。