你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 JavaScript 的 Azure 通信聊天客户端库 - 版本 1.6.0

适用于聊天的 Azure 通信服务允许开发人员向其应用添加聊天功能。 使用此客户端库管理聊天线程及其用户,以及发送和接收聊天消息。

在此处阅读有关 Azure 通信服务 的详细信息

开始

先决条件

安装

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 允许你执行特定于聊天线程的操作,例如更新聊天线程主题、发送消息、将参与者添加到聊天线程等。

可以使用具有现有线程 ID 的 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 是发送消息返回的结果,它包含 ID,这是消息的唯一 ID。

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);

从线程中删除用户

与上述类似,还可以从线程中删除用户。 若要删除,需要跟踪已添加的参与者的 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);

const chatThreadClient = chatClient.getChatThreadClient("<threadId>");

await chatThreadClient.removeParticipant({ communicationUserId: "<MEMBER_ID>" });

订阅实时通知的连接状态

订阅事件 realTimeNotificationConnectedrealTimeNotificationDisconnected 允许知道与呼叫服务器的连接何时处于活动状态。

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 个用户的线程
  • 向线程发送消息
  • 从线程接收消息
  • 从线程中删除用户

贡献

若要参与此库,请阅读 贡献指南 了解有关如何生成和测试代码的详细信息。