JavaScript용 Azure Communication Chat 클라이언트 라이브러리 - 버전 1.5.0
채팅용 Azure Communication Services 개발자는 앱에 채팅 기능을 추가할 수 있습니다. 이 클라이언트 라이브러리를 사용하여 채팅 스레드 및 해당 사용자를 관리하고 채팅 메시지를 보내고 받습니다.
Azure Communication Services 대한 자세한 내용은 여기를 참조하세요.
시작
필수 구성 요소
- Azure 구독.
- 기존 Communication Services 리소스입니다. 리소스를 만들어야 하는 경우 Azure Portal, 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
ChatClient
는 이 클라이언트 라이브러리를 사용하는 개발자를 위한 기본 인터페이스입니다. 스레드를 만들고 삭제하는 비동기 메서드를 제공합니다.
ChatThreadClient
ChatThreadClient
는 채팅 스레드 내에서 메시지 및 채팅 참가자 작업을 수행하는 비동기 메서드를 제공합니다.
예제
ChatClient 초기화
리소스 URL 및 사용자 액세스 토큰을 사용하여 채팅 클라이언트를 초기화합니다.
import { ChatClient } from '@azure/communication-chat';
import { AzureCommunicationTokenCredential } from "@azure/communication-common";
// 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
는 스레드를 만들 때 반환된 결과입니다. 여기에는 생성된 errors
스레드인 와 스레드에 추가하지 못한 경우 잘못된 참가자에 대한 정보가 포함된 속성이 포함 chatThread
됩니다.
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를 초기화할 수 있습니다.
const chatThreadClient = chatClient.getChatThreadClient(threadId);
스레드에 메시지 보내기
sendMessage
메서드를 사용하여 threadId로 식별되는 스레드에 메시지를 보냅니다.
sendMessageRequest
는 메시지 요청을 설명하는 데 사용됩니다.
content
를 사용하여 채팅 메시지 콘텐츠를 제공합니다.
sendMessageOptions
는 작업 선택적 매개 변수를 설명하는 데 사용됩니다.
senderDisplayName
을 사용하여 보낸 사람의 표시 이름을 지정합니다.type
을 사용하여 메시지 유형(예: 'text' 또는 'html')을 지정합니다.
sendChatMessageResult
는 메시지를 보낸 후 반환된 결과이며, 메시지의 고유 ID인 ID를 포함합니다.
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;
스레드에서 메시지 받기
실시간 신호를 통해, 새로 들어오는 메시지를 수신 대기하도록 구독하고 메모리의 현재 메시지를 적절하게 업데이트할 수 있습니다.
// open notifications channel
await chatClient.startRealtimeNotifications();
// subscribe to new notification
chatClient.on("chatMessageReceived", (e) => {
console.log("Notification chatMessageReceived!");
// your code here
});
또는 지정된 간격으로 listMessages
메서드를 폴링하여 채팅 메시지를 가져올 수 있습니다.
for await (const chatMessage of chatThreadClient.listMessages()) {
// your code here
}
스레드에 사용자 추가
스레드가 만들어지면 해당 스레드에서 사용자를 추가하고 제거할 수 있습니다. 사용자를 추가하면 사용자에게 스레드에 메시지를 보낼 수 있는 액세스 권한을 부여합니다. 먼저 해당 사용자에 대한 새 액세스 토큰 및 ID를 가져옵니다. 사용자가 채팅 클라이언트를 초기화하려면 액세스 토큰이 필요합니다. 토큰에 대한 자세한 내용은 다음을 참조하세요. Azure Communication Services 인증
const addParticipantsRequest =
{
participants: [
{
id: { communicationUserId: '<NEW_PARTICIPANT_USER_ID>' },
displayName: 'Jane'
}
]
};
await chatThreadClient.addParticipants(addParticipantsRequest);
스레드에서 사용자 제거
위와 마찬가지로 스레드에서 사용자를 제거할 수도 있습니다. 제거하려면 추가한 참가자의 ID를 추적해야 합니다.
await chatThreadClient.removeParticipant({ communicationUserId: '<MEMBER_ID>' });
실시간 알림 연결 상태 구독
이벤트 realTimeNotificationConnected
및 realTimeNotificationDisconnected
에 대한 구독을 통해 호출 서버에 대한 연결이 활성 상태인지 알 수 있습니다.
// 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
});
문제 해결
다음 단계
이 빠른 시작에서는 다음을 수행하는 방법을 알아보았습니다.
- 채팅 클라이언트 만들기
- 사용자가 2명인 스레드 만들기
- 스레드에 메시지 보내기
- 스레드에서 메시지 받기
- 스레드에서 사용자 제거
참여
이 라이브러리에 기여하려면 기여 가이드 를 참조하여 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.
Azure SDK for JavaScript
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기