Azure Web PubSub Chat 用戶端函式庫讓伺服器應用程式能管理聊天角色、使用者、聊天室、主題、聊天室成員資格、對話以及 Azure Web PubSub 聊天中心中的訊息。 利用它將討論整理成房間主題、探索使用者及其房間,並從您的伺服器應用程式管理聊天資源。
主要連結:
入門指南
目前支援的環境
如需詳細資訊,請參閱我們的支援原則。
先決條件
- Azure 訂用帳戶。
- 一個現有嘅 Azure Web PubSub 資源。
- 一個配置為支援聊天功能且具持久儲存功能的集線器。
安裝 @azure/web-pubsub-chat 套件
安裝 Azure WebPubSubChatService JavaScript 客戶端庫,使用:npm
npm install @azure/web-pubsub-chat
設定 TypeScript
此套件包含 TypeScript 宣告。 對於使用 TypeScript 撰寫的 Node.js 應用程式,請安裝 Node.js 類型定義:
npm install --save-dev @types/node
不需要額外的套件專屬編譯器設定。
建立和驗證 WebPubSubChatServiceClient
它WebPubSubChatServiceClient支援使用 連接字串、Microsoft Entra 憑證或 AzureKeyCredential.
使用 連接字串 進行認證
你可以在 Azure 入口網站 找到你 Azure Web PubSub 資源的 連接字串。 由於 連接字串 包含存取金鑰,請安全儲存,且不包含在原始碼中。
使用 Microsoft Entra 識別碼驗證
要使用 Microsoft Entra ID 認證,你需要endpoint你的 Azure Web PubSub 資源和一個憑證。 你可以在 Azure 入口網站 找到端點。
你可以用 @azure/identity 函式庫的憑證或現有的 Microsoft Entra 令牌來驗證 Microsoft Entra ID。
若要使用如下所示的 DefaultAzureCredential 提供者,或 Azure SDK 所提供的其他認證提供者,請安裝 @azure/identity 套件:
npm install @azure/identity
DefaultAzureCredential支援多種 Microsoft Entra 身份。 在本地開發期間,它可以使用透過支援的開發工具登入的開發者身份。 在 Azure 中,它可以使用管理身份。 它也能在為環境設定時,驗證服務主體或工作負載身份。
你使用的身份必須被指派一個適當的 Azure Web PubSub 資料平面角色。 Azure 資源管理角色例如 do Owner not grant data-plane permissions.
建立客戶端時,包含 連接字串、Microsoft Entra 憑證(例如 DefaultAzureCredential,或 AzureKeyCredential)。
import { WebPubSubChatServiceClient, AzureKeyCredential } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const connectionStringClient = new WebPubSubChatServiceClient("<connectionString>", "<hubName>");
const tokenCredentialClient = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
const keyCredentialClient = new WebPubSubChatServiceClient(
"<endpoint>",
new AzureKeyCredential("<accessKey>"),
"<hubName>",
);
關鍵概念
樞紐
集線器是一組邏輯上的 WebSocket 連線集合。 聊天中心新增內建聊天室、成員管理、訊息持續化以及專屬聊天 API。
此 SDK 僅適用於聊天中心。 必須在目標集線器啟用聊天功能,SDK 才能管理角色、使用者、聊天室、成員、對話或訊息。
角色與權限
角色是一組具名的聊天權限集合。 使用者角色名稱以 user.開頭,房間角色名稱以 room.開頭。 請勿將使用者權限與房間權限合併在同一個角色中。
使用者角色控制如建立房間等操作。 房間角色控制成員在特定房間中能做的事,例如發佈訊息或閱讀訊息歷史。
User
使用者代表參與聊天的身份,例如人類終端使用者或應用程式。 用戶端存取憑證會將 WebSocket 連線與使用者 ID 關聯起來。
房間
房間將使用者分組,是聊天互動的主要組織單位。 每個房間都有自動建立的預設對話。
房間成員
房間成員代表新增至房間的使用者。 成員資格控制哪些使用者可以在會議室中接收和傳送訊息。 在服務 API 中,每個房間成員都會被指派一個房間角色。
對話與訊息歷史
對話是房間內有序的訊息串流。 每個房間都有預設對話,且可透過主題建立更多命名對話。
發送到對話中的訊息會即時傳送給該房間已連接的成員。 聊天服務負責管理排序與持續管理,讓成員在重新連線或稍後加入後,仍能載入訊息歷史。 服務用戶端可以列出、更新及刪除持久化的訊息。
Topic
主題代表房間內的一個命名對話。 主題可以獨立於聊天室預設對話內容而建立、重新命名、封存及軟刪除。
範例
設定角色、使用者和房間
建立使用者角色和房間角色,建立一個人類使用者和一個房間,然後將使用者加入房間。
import { WebPubSubChatServiceClient, KnownChatPermission } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
const userRoleName = "user.contoso_member";
const roomRoleName = "room.contoso_member";
const userId = "alice";
const roomId = "general";
await client.createOrReplaceRole(userRoleName, {
permissions: [KnownChatPermission.UserCreateRoom],
});
await client.createOrReplaceRole(roomRoleName, {
permissions: [KnownChatPermission.RoomPublishMessage, KnownChatPermission.RoomHistory],
});
await client.createOrReplaceUser(userId, {
kind: "Human",
nickname: "Alice",
roleName: userRoleName,
});
const room = await client.createOrReplaceRoom(roomId, { title: "General" });
await client.createOrReplaceRoomMember(roomId, userId, { roleName: roomRoleName });
console.log(`Created room ${room.id} with conversation ${room.defaultConversation}`);
使用內建角色與已知權限
BuiltInChatRoles用於指派服務定義角色及KnownChatPermission建立自訂角色時。 允許超出已知值的權限字串也被接受,以確保前向相容性。
import {
WebPubSubChatServiceClient,
BuiltInChatRoles,
KnownChatPermission,
} from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
await client.createOrReplaceUser("alice", {
kind: "Human",
nickname: "Alice",
roleName: BuiltInChatRoles.UserNormal,
});
await client.createOrReplaceRole("room.moderator", {
permissions: [
KnownChatPermission.RoomHistory,
KnownChatPermission.RoomRemoveUser,
KnownChatPermission.RoomPublishMessage,
],
});
管理角色
建立一個自訂角色,取回它,並在集線器中列出角色,完成後刪除自訂角色。
import { WebPubSubChatServiceClient, KnownChatPermission } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
const roleName = "user.contoso_member";
try {
const role = await client.createOrReplaceRole(roleName, {
permissions: [KnownChatPermission.UserCreateRoom, KnownChatPermission.UserFetchAllRooms],
});
console.log(`Created role: ${role.name}`);
const fetchedRole = await client.getRole(roleName);
console.log(`Fetched role: ${fetchedRole.name}`);
for await (const listedRole of client.listRoles()) {
console.log(`Role: ${listedRole.name}`);
}
} finally {
await client.deleteRole(roleName);
}
管理一間房間
建立一個房間,取得其當前狀態,然後刪除它。
import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
const roomId = "general";
const room = await client.createOrReplaceRoom(roomId, { title: "General" });
console.log(`Created room ${room.id} with conversation ${room.defaultConversation}`);
const fetchedRoom = await client.getRoom(roomId);
console.log(`Fetched room: ${fetchedRoom.id}, title: ${fetchedRoom.title}`);
await client.deleteRoom(roomId);
管理使用者
建立一個內建角色的使用者,取回該個人檔案並刪除。
請求接受 HumanChatUserCreateOrReplace,這需要 kind: "Human"、 nickname、 roleName和 。 回傳的設定檔會保留資源欄位,並可能代表未知的使用者類型。
import { WebPubSubChatServiceClient, BuiltInChatRoles } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
const userId = "alice";
const user = await client.createOrReplaceUser(userId, {
kind: "Human",
nickname: "Alice",
roleName: BuiltInChatRoles.UserNormal,
});
console.log(`Created user: ${user.id}, nickname: ${user.nickname}`);
const fetchedUser = await client.getUser(userId);
console.log(`Fetched user: ${fetchedUser.id}, nickname: ${fetchedUser.nickname}`);
await client.deleteUser(userId);
更新訊息
在更新訊息時, ChatMessageUpdate.createdBy 以及 content 是可選的。
只提供要變更的欄位;省略的欄位保留其當前值。
在對話中列出訊息
使用非同步迭代來讀取對話中所有結果頁面的訊息,從最新到最早。 訊息 ID 是分頁游標:迭代器會跟隨服務的 nextLink,該服務包含下一個訊息 ID 游標。 若要稍後繼續,請儲存頁面並 continuationToken 傳給; byPage({ continuationToken })請使用不更改的回傳令牌,而非傳出純訊息 ID。
import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
for await (const message of client.listMessages("<conversationId>")) {
console.log(`${message.createdBy}: ${message.content.text}`);
}
產生一個用戶端存取權杖
產生一個 URL,讓聊天客戶端以特定使用者身份連接到 Web PubSub 服務。
import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
const accessToken = await client.getClientAccessToken({ userId: "alice" });
在樞紐中列出房間
import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
for await (const room of client.listRooms({ maxPageSize: 20 })) {
console.log(`${room.id}: ${room.title}`);
}
在樞紐中列出使用者
import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
for await (const user of client.listUsers({ maxPageSize: 20 })) {
console.log(`${user.id}: ${user.nickname}`);
}
列出使用者的房間
import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
for await (const room of client.listRoomsForUser("alice", { maxPageSize: 20 })) {
console.log(`${room.id}: ${room.title}`);
}
建立主題
在現有房間中建立主題。 該服務會建立其關聯的對話。
import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
const topic = await client.createOrReplaceTopic(
"general",
"announcements",
{
title: "Announcements",
},
{ ifNoneMatch: "*" },
);
console.log(`Topic conversation: ${topic.conversationId}`);
找個主題
import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
const topic = await client.getTopic("general", "announcements");
console.log(`${topic.title}: ${topic.state}, ETag: ${topic.etag}`);
更新主題
在不更改標題的情況下,存檔現有主題。 請替換 <etag> 為目前的實體標籤。
import { WebPubSubChatServiceClient, KnownChatTopicState } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
const topic = await client.updateTopic(
"general",
"announcements",
{
state: KnownChatTopicState.Archived,
},
{ ifMatch: "<etag>" },
);
console.log(`Topic state: ${topic.state}`);
在房間中列出主題
import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
for await (const topic of client.listTopics("general", { maxPageSize: 20 })) {
console.log(`${topic.id}: ${topic.title} (${topic.state})`);
}
履歷主題分頁
列表操作接受透過 byPage({ continuationToken })的延續符號,而非透過列表方法的選項。 將返回的權杖傳入頁面時保持不變。
import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
const pages = client.listTopics("general", { maxPageSize: 20 }).byPage();
const firstPage = await pages.next();
if (!firstPage.done) {
console.log(firstPage.value);
const continuationToken = firstPage.value.continuationToken;
if (continuationToken) {
const resumedPages = client
.listTopics("general", { maxPageSize: 20 })
.byPage({ continuationToken });
const nextPage = await resumedPages.next();
console.log(nextPage.value);
}
}
刪除主題
軟刪除現有主題。 請替換 <etag> 為目前的實體標籤。
import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";
const client = new WebPubSubChatServiceClient(
"<endpoint>",
new DefaultAzureCredential(),
"<hubName>",
);
await client.deleteTopic("general", "announcements", { ifMatch: "<etag>" });
Troubleshooting
服務錯誤與條件請求
服務失敗拋出 RestError 時會以 statusCode. HTTP 404 表示缺少資源,包括已刪除的主題。 HTTP 412 表示某ifNoneMatch個ifMatch或前置條件失敗。 擷取目前資源並檢視其實體標籤,然後再嘗試條件寫入。 僅在建立資源時使用該資源尚未存在時使用 ifNoneMatch: "*" 。
森林伐木業
啟用記錄可能有助於找出有關失敗的實用資訊。 若要查看 HTTP 要求和回應的記錄,請將 AZURE_LOG_LEVEL 環境變數設定為 info。 或者,您可以在運行時間啟用記錄,方法是在 setLogLevel中呼叫 @azure/logger:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
如需如何啟用記錄的詳細指示,請參閱
下一步
探索 JavaScript 與 TypeScript 範例 以及 API 參考。
Contributing
如果您想要參與此連結庫,請閱讀 參與指南,以深入瞭解如何建置和測試程序代碼。