# Overview

Game Chat은 게임에 실시간 채팅 및 메시지 시스템, 여러 사용자가 대화할 수 있는 채널을 구현할 수 있는 서비스입니다. 쉽고 간단하게 게임 내 채팅 서비스를 구축할 수 있도록 다양한 SDK와 API를 제공합니다. 네이버 클라우드 플랫폼의 Game Chat 서비스를 활용하면 로그인 환경이나 운영 도구를 개발할 필요가 없고, 인프라 관리 및 사용자 관리를 위해 별도의 시스템을 구축하지 않아도 됩니다. 직관적이고 편리한 Game Chat 대시보드에서 통계 분석, 서비스 운영 및 관리가 가능하며 네이버 클라우드 플랫폼의 다양한 서비스와의 연동을 통해 강력한 채팅 환경을 구축할 수 있습니다.

### Game Chat이 제공하는 다양한 기능 <a href="#gamechat" id="gamechat"></a>

* 편리한 대시보드: 모바일에서도 접속할 수 있는 Game Chat 대시 보드 화면에서 메시지 통계, 채팅 채널(길드) 관리, 악성 사용자 차단, 욕설 및 비속어 필터링, 채팅 메시지 다운로드 및 검색이 가능합니다.
* 1:1 채팅: 특정 사용자에게 알림 메시지를 전달할 수 있고 사용자 간 1:1 채팅 시스템을 안정적으로 지원합니다.
* 다국어 메시지 실시간 자동 번역: 다양한 나라의 사람들과 편하게 대화할 수 있도록 네이버의 강력한 AI 번역 솔루션인 파파고와의 연동 기능을 제공합니다. 자동 번역 기능을 활용하여 글로벌 사용자와 쉽게 커뮤니티를 구축할 수 있습니다.
* 비속어 차단 및 악성 사용자 차단: 건강한 채팅 환경 구성을 위해 욕실 및 비속어가 포함된 메시지를 필터링하고 삭제할 수 있으며, 악성 사용자(플레이어)는 일정 기간 동안 채팅을 이용할 수 없도록 설정할 수 있습니다.
* 실시간 분석 지표: 사용자 접속 현황, 메시지 전달 현황 등을 분석할 수 있도록 다양한 분석 지표를 제공합니다.

Game Chat is a service that enables real-time chat and messaging systems within games, allowing multiple users to communicate through channels. It offers a variety of SDKs and APIs to help developers easily and efficiently implement in-game chat services. By leveraging Naver Cloud Platform’s Game Chat service, you can avoid building separate login environments, management tools, infrastructure, or user management systems. The intuitive and user-friendly Game Chat dashboard enables statistics analysis, service operation, and management. Furthermore, integration with various Naver Cloud services allows you to build a powerful chat environment.

**Key Features Provided by Game Chat**

* **User-Friendly Dashboard**: The Game Chat dashboard, accessible from mobile devices, allows you to view message statistics, manage chat channels (such as guilds), block abusive users, filter offensive language, and search or download chat messages.
* **1:1 Chat**: You can send alert messages to specific users and provide a stable 1:1 chat system between users.
* **Real-Time Multilingual Message Translation**: To facilitate smooth communication between users from different countries, Game Chat integrates with Naver’s powerful AI translation service, Papago. This automatic translation feature helps build global communities effortlessly.
* **Profanity Filtering and Abusive User Blocking**: To maintain a healthy chat environment, messages containing profanity or offensive language can be filtered and removed. Malicious users (players) can also be restricted from using the chat service for a set period.
* **Real-Time Analytics**: The service provides various analytical indicators such as user connection status and message delivery statistics to help monitor and manage performance effectively.


# Game Chat (V2)


# Game Chat(한국어)

Game Chat은 게임에 실시간 채팅 및 메시지 시스템, 여러 사용자가 대화할 수 있는 채널을 구현할 수 있는 서비스입니다. 쉽고 간단하게 게임 내 채팅 서비스를 구축할 수 있도록 다양한 SDK와 API를 제공합니다.

## Game Chat이 제공하는 다양한 기능

* 효과적인 운영을 돕는 대시보드\
  모바일에서도 접근 가능한 대시보드는 직관적인 디자인으로 편리하게 사용할 수 있습니다. \
  메시지 통계 확인, 채팅 채널 관리, 유저 차단, 비속어 필터링, 채팅 메시지 검색 및 다운로드 등 다양한 기능을 지원하여 언제 어디서든 게임을 관리할 수 있습니다.
* 1:1 프라이빗 메시지\
  특정 사용자에게 알림 메시지를 전달할 수 있고 사용자 간 1:1 채팅 시스템을 안정적으로 지원합니다.
* 다국어 메시지 실시간 자동 번역\
  다양한 나라의 사람들과 편하게 대화할 수 있도록 네이버의 강력한 AI 번역 솔루션인 파파고와의 연동 기능을 제공합니다. 자동 번역 기능을 활용하여 글로벌 사용자와 쉽게 커뮤니티를 구축할 수 있습니다.
* 비속어 및 악성 사용자 차단\
  건강한 채팅 환경 구성을 위해 욕설 및 비속어가 포함된 메시지를 필터링하고 삭제할 수 있으며, 악성 사용자(플레이어)는 일정 기간 동안 채팅을 이용할 수 없도록 설정할 수 있습니다.
* 실시간 분석 지표\
  사용자 접속 현황, 메시지 전달 현황 등을 분석할 수 있도록 다양한 분석 지표를 제공합니다.

## Game Chat 사용 가이드 안내

Game Chat 사용 가이드는 효과적으로 Game Chat를 이용할 수 있도록 다음과 같은 주제로 구성되어 있습니다.

* Game Chat 개요: Game Chat의 소개 및 기능 안내
* [Game Chat 사용 준비](/basics/game-chat-v2/quickstart/game-chat): Game Chat 사용 전 미리 준비할 사항 안내
* [Game Chat 시작](/basics/game-chat-v2/quickstart/publish-your-docs): Game Chat 서비스 이용 신청 방법 안내
* Game Chat 사용: Game Chat 사용자가 이용할 수 있는 기능에 대한 사용 방법 안내
  * [Game Chat 운영 및 관리](/basics/game-chat-v2/quickstart/publish-your-docs/game-chat): Dashboard 접속 방법 및 Dashboard 사용 방법 안내
  * [Game Chat Unity SDK](/basics/game-chat-v2/quickstart/publish-your-docs/unity-sdk): Unity용 Game Chat SDK를 사용하는 방법 안내


# Game Chat 사용 준비

Game Chat의 원활한 이용을 위한 서비스 사양 및 준비 사항, 요금 정보를 설명합니다.

## 서비스 사양

Game Chat에서 제공하는 SDK는 아래와 같은 환경에서 사용할 수 있습니다.

<table><thead><tr><th width="145">개발 환경</th><th width="213">요구 사양</th></tr></thead><tbody><tr><td>Unity</td><td>Unity 2018.4.0 이상</td></tr></tbody></table>

## 이용 요금

프로젝트 생성 시 무료 프로젝트로 생성되며, 유료 전환 시 비용이 발생합니다.

<table><thead><tr><th width="125">타입</th><th width="153">과금 구간</th><th width="98">과금 기준</th><th width="93">요금</th><th width="257">비고</th></tr></thead><tbody><tr><td>무료</td><td>200 CCU 이하</td><td>일</td><td>무료</td><td>유료 전환 시, 과금 시작<br>네트워크 사용량 100GB 포함</td></tr><tr><td>유료 기본료</td><td>2,000 CCU 이하</td><td>일</td><td>7,333원</td><td>네트워크 전송량 2TB 포함</td></tr></tbody></table>

* Game Chat 서비스는 개발 무료 구간으로 200 CCU가 제공됩니다.
* CCU는 동시접속사용자로 채팅 채널에 동시에 접속된 활성 사용자 수로 집계됩니다.

## 추가 요금

<table><thead><tr><th width="185">타입</th><th width="213">과금 구간</th><th width="100">과금 기준</th><th width="100">요금</th><th width="100">비고</th></tr></thead><tbody><tr><td>추가 CCU</td><td>2,000 초과 ~ 10,000 이하</td><td>CCU</td><td>150원</td><td></td></tr><tr><td>추가 CCU</td><td>10,000 초과</td><td>CCU</td><td>100원</td><td></td></tr><tr><td>추가 네트워크 사용량</td><td>2TB 초과</td><td>GB</td><td>100원</td><td></td></tr></tbody></table>

* 기본요금 구간에서 CCU가 초과 시 추가 요금이 과금됩니다.
* 요금 예시\
  \- 11월 1일부터 11월 30일간 2,500 CCU 사용 고객(500 CCU 초과)\
  \- (7,333 원 \* 30일) + (500CCU \* 150 원) = 219,990 원 + 75,000 원 = 294,990 원


# Game Chat 시작

Game Chat 이용 신청 및 프로젝트 생성 방법, 프로젝트 관리 방법을 설명합니다.

## Game Chat 서비스 신청 및 프로젝트 생성

Game Chat 서비스 신청 및 프로젝트 생성을 위해서는 <cs@nbase.io> 메일 주소로 사용하고자 하시는 프로젝트명을 적어 신청해 주시기 바랍니다.

## 프로젝트 관리

프로젝트의 이름 변경, 관리자 계정 비밀번호 초기화, 프로젝트 삭제 등과 같은 부분은 <cs@nbase.io> 메일을 통해 요청해 주세요.

> 주의\
> 프로젝트를 삭제 할 경우, 프로젝트에서 보유한 모든 데이터가 삭제되므로 주의해 주세요.

## 프로젝트 유료 전환

프로젝트 생성 시 하루 최대 200 CCU 사용할 수 있는 무료 개발용 프로젝트로 생성됩니다. 200 CCU 이상 사용하려면 유료로 전환해야 합니다. 프로젝트 유료 전환 방법은 다음과 같습니다.

1. Game Chat 관리 페이지(대시보드)에 로그인을 해주세요.
2. 관리 페이지 하단에 나타난 **\[유료전환]** 버튼을 클릭해 주세요.
3. 알림 창을 확인하고 **\[확인]** 버튼을 클릭해 주세요.

> 주의\
> 무료 환경에서 유료 환경으로 전환한 후에는 다시 무료 환경으로 전환할 수 없으므로 주의해 주세요.


# Game Chat 운영 및 관리

Game Chat 대시보드에서 채팅을 운영하고 관리하는 방법, 채팅과 관련된 통계를 확인하는 방법을 설명합니다.

## 대시보드 메뉴

대시보드에서는 접속 현황, 메시지, 통계 등 채팅의 운영 상황을 한 눈에 파악할 수 있습니다. 날짜를 선택하여 그래프를 확인할 수 있습니다.

대시보드 메뉴는 다음과 같습니다.

<figure><img src="/files/KRRPnuk0gdrW0kRlW8sv" alt=""><figcaption></figcaption></figure>

<table><thead><tr><th width="100">번호</th><th width="100">메뉴</th><th width="459">설명</th></tr></thead><tbody><tr><td>1</td><td>대시보드</td><td>접속자 통계 확인</td></tr><tr><td>2</td><td>회원</td><td>회원 확인 및 이용 정지 회원 관리</td></tr><tr><td>3</td><td>채팅</td><td>채팅 채널 추가 및 채널 관리</td></tr><tr><td>4</td><td>검색</td><td>회원 검색</td></tr><tr><td>5</td><td>설정</td><td>프로젝트 설정 및 대시보드 사용자 설정, Unity SDK 다운로드</td></tr><tr><td>6</td><td>작업관리</td><td>검색 메뉴에서 데이터 내보내기 한 내역 확인</td></tr><tr><td>7</td><td>DOCS</td><td>Unity: 게임챗 Unity 사용 가이드로 이동</td></tr><tr><td>8</td><td>언어 설정</td><td>대시보드 언어 변경 가능. 한국어, 영어 제공</td></tr><tr><td>9</td><td>회원 정보</td><td>회원정보 수정 및 로그아웃</td></tr></tbody></table>

## 회원

회원 메뉴에서는 대시보드에 등록되 회원(게임 플레이어)의 정보를 확인하고, 특정 회원의 채팅 이용을 정지하거나 모든 채팅에서 탈퇴시킬 수 있습니다.

### 회원 정보 확인

Game Chat 대시보드에 등록된 회원의 정보를 확인하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **회원** > **목록** 메뉴를 클릭해 주십시오.
2. 회원의 상세 정보를 확인하려면 사용자 ID를 클릭해 주십시오.
3. 화면 우측에서 상세 정보를 확인해 주십시오.
   * 사용자의 이름, 프로필 URL, 접속 국가, ID, 모델, 디바이스 ID 가입일, 마지막 로그인 날짜 등 확인 가능

<figure><img src="/files/nXsrHOwBe67faheyBqa7" alt=""><figcaption></figcaption></figure>

4. 회원 정보를 수정하려면 이름 또는 프로필 URL을 수정한 후 **\[저장]** 버튼을 클릭해 주십시오.
   * 이름, 프로필 이미지 URL만 수정 가능

### 회원 탈퇴

특정 회원을 탈퇴시키는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **회원** > **목록** 메뉴를 클릭해 주십시오.
2. 탈퇴시킬 회원 ID를 클릭해 주십시오.
3. 화면 우측에 회원 상세 정보가 나타나면 **\[탈퇴]** 버튼을 클릭해 주십시오.
4. 팝업 확인 창이 나타나면 **\[예]** 버튼을 클릭해 주십시오.

### 회원 검색

Game Chat 대시보드에 등록된 회원을 검색하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **회원** > **목록** 메뉴를 클릭해 주십시오.
2. 검색 조건을 설정하고 **\[검색]** 버튼을 클릭해 주십시오.
   * 사용자 ID 생성일, 사용자 ID, 닉네임, 국가, 아이피를 조건으로 검색 가능
3. 검색 결과를 확인해 주십시오.

### 회원 이용 정지

특정 회원이 일정 기간 동안 채팅을 사용할 수 없도록 설정할 수 있습니다. 이용 정지 메뉴에서는 이용 정지 중인 회원을 확인하고 검색할 수 있습니다.\
특정 회원의 채팅 이용을 정지하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **회원** > **이용 정지** 메뉴를 클릭해 주십시오.
2. 화면 우측에 있는 **\[추가]** 버튼을 클릭해 주십시오.
3. 이용 정지 등록 창이 나타나면 **\[상태]** 아이콘을 클릭하여 활성 상태로 변경해 주십시오.
4. 이용 정지하려는 회원을 모든 채널에서도 내보내려면 **채팅 내보내기** 체크 박스를 클릭해 주십시오.
5. 사용자 ID와 이용 정지 사유, 이용 정지 기간을 설정하고 **\[저장]** 버튼을 클릭해 주십시오.

## 채팅

채팅 메뉴에서는 채널을 확인하고 채팅 메시지를 전송할 수 있습니다.

### 채팅 채널 추가

새로운 채팅 채널을 추가하는 방법은 다음과 같습니다

1. Game Chat 대시보드에서 **채널** 메뉴를 클릭해 주십시오.
2. **\[채널 추가]** 버튼을 클릭해 주십시오.
3. 채널 추가 창이 나타나면 채널과 Unique ID를 입력하고 **\[등록]** 버튼을 클릭해 주십시오.
   * Unique ID 입력 시 SDK에서 해당 값을 이용하여 채널에 접속 가능
4. 채널이 생성되었는지 확인해 주십시오.

### 채팅 채널 설정

특정 채팅 채널에 참여 중인 사용자를 확인하거나 채널 정보를 수정하거나 삭제하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **채널** 메뉴를 클릭해 주십시오.
2. 채널을 선택한 후, 채널 화면 우측 상단에 있는 : 아이콘를 클릭해 주십시오.
3. 컨텍스트 메뉴가 나타나면 원하는 작업을 선택해 주십시오.

<figure><img src="/files/03dY1jvQGnZavyal5gHe" alt=""><figcaption></figcaption></figure>

* 채팅 채널에 참여한 사용자 목록을 확인하려면 **\[참여 목록]** 메뉴를 클릭해 주십시오.
* 채팅 채널 정보를 수정하려면 **\[채널 수정]** 메뉴를 클릭해 주십시오.
* 채팅 채널을 삭제하려면 **\[삭제]** 메뉴를 클릭해 주십시오.

## 검색

검색 메뉴에서는 프로젝트의 모든 채널에서 주고 받은 메시지를 확인하고 검색할 수 있습니다. \
아이디, 닉네임, 메시지, 채널 ID, 메시지 발송 일시를 기준으로 검색할 수 있고, 메시지 목록을 CSV 파일로 다운로드할 수 있습니다.

<figure><img src="/files/TyAtCdQqRSEj1m9yZpWL" alt=""><figcaption></figcaption></figure>

### 메시지 검색 및 메시지 상세 정보 확인

메시지의 상세 정보(메시지가 작성된 채널 ID, 메시지 ID, 메시지, 메시지 발송 시각)를 확인하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **검색** 메뉴를 클릭해 주십시오.
2. 검색 조건을 설정하고 **\[검색]** 버튼을 클릭해 주십시오.
   * 메시지 발송일, 회원 ID, 채널 ID, 닉네임, 메시지를 조건으로 검색 가능
3. 상세 정보를 확인할 메시지의 보기 아이콘을 클릭해 주십시오.
4. 해당 메시지가 등록된 채널 ID, 메시지 ID, 메시지, 메시지 발송 시각을 확인할 수 있습니다.

### 메시지 삭제

특정 메시지를 검색하여 삭제할 수 있습니다. 검색 메뉴에서 삭제한 메시지는 해당 채팅 채널에서도 삭제됩니다.

1. Game Chat 대시보드에서 **검색** 메뉴를 클릭해 주십시오.
2. 삭제할 메시지의 삭제 아이콘을 클릭해 주십시오.
3. 삭제 확인 창이 나타나면 **\[예]** 버튼을 클릭해 주십시오.

## 설정

설정 메뉴에서는 Game Chat 프로젝트 정보를 설정하거나 채팅 금칙어 및 메시지 자동 번역 여부를 설정하는 방법, 사용자 정보를 변경하거나 특정 사용자에게 관리자 권한을 부여할 수 있습니다.

### 프로젝트 설정 <a href="#undefined" id="undefined"></a>

프로젝트 정보 확인 및 수정, 금칙어 설정, 채팅 자동 번역 기능을 사용하는 방법을 설명합니다.

#### **프로젝트 정보 확인**

네이버클라우드 ID, 프로젝트 ID, API Key, 프로젝트명, 메시지 제한 길이를 확인할 수 있고, 프로젝트명, 메시지 제한 길이, 금칙어를 설정할 수 있습니다.\
프로젝트 정보를 확인하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **설정** > **프로젝트 설정** 메뉴를 클릭해 주십시오.
2. 프로젝트 정보를 확인해 주십시오.
   * 프로젝트명, 메시지 길이 제한만 수정 가능

#### **금칙어 설정**

채팅에서 사용할 수 없는 문자(욕설 및 비속어 등)를 금칙어로 설정하여 건전한 채팅 환경을 제공할 수 있습니다.\
금칙어를 설정하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **설정** > **프로젝트 설정** 메뉴를 클릭해 주십시오.
2. 금칙어 제한 타입을 선택해 주십시오.
   * 제한 안함: 금칙어로 지정된 단어도 그대로 노출
   * \*로 치환: 금칙어로 지정된 단어는 채팅창에 \*로 노출
   * 메시지 전달 차단: 금칙어로 지정된 단어는 전송하지 않음
3. 금칙어 예시를 자동으로 가져오려면 **\[기본 금칙어 사용]** 버튼을 클릭해 주십시오.
4. **\[저장]** 버튼을 클릭해 주십시오.

#### **채팅 메시지 자동 번역**

네이버 클라우드 플랫폼에서 제공하는 서비스인 Papago Translation와 연동하여 채팅에 입력되는 메시지를 자동으로 번역할 수 있습니다.\
채팅 메시지를 자동 번역하도록 설정하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **설정** > **프로젝트 설정** 메뉴를 클릭해 주십시오.
2. Papago 영역의 활성화 아이콘을 클릭해 주십시오.
3. Client ID와 Client Secret을 입력하고 **\[저장]** 버튼을 클릭해 주십시오.

> 참고
>
> Papago Translation 연동을 위한 Client ID와 Client Secret을 확인하는 방법은 [Application 사용 가이드](https://guide.ncloud-docs.com/docs/naveropenapiv3-application)를 참고해 주십시오.

### 사용자 설정 <a href="#undefined" id="undefined"></a>

프로젝트의 사용자를 확인하고 사용자 정보를 수정할 수 있습니다. 단, 현재 접속 중인 계정의 상세 정보는 회원정보 수정 메뉴에서 수정할 수 있습니다.\
사용자 정보를 수정하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **설정** > **사용자 설정** 메뉴를 클릭해 주십시오.
2. 사용자 정보를 수정할 사용자의 ![](/files/Y3z4bjcMoCuAWp7H0xk6) > **상세보기** 메뉴를 클릭해 주십시오.
3. 사용자 이름, 비밀번호, 사용자 상태를 설정하고 **\[저장]** 버튼을 클릭해 주십시오.
4. 특정 사용자를 대시보드의 관리자로 설정하려면 관리자 권한 아이콘을 활성화 상태로 변경하고 **\[저장]** 버튼을 클릭해 주십시오.
5. 사용자 정보를 삭제하려면 **\[삭제]** 버튼을 클릭해 주십시오.

### SDK 다운로드 <a href="#sdk" id="sdk"></a>

Unity SDK를 다운로드할 수 있습니다.

## 작업 관리 <a href="#undefined" id="undefined"></a>

작업 관리 메뉴에서는 검색 메뉴에서 csv로 내보내기한 결과를 30일 간 다운로드할 수 있습니다.

## 회원정보 수정 <a href="#undefined" id="undefined"></a>

회원정보 메뉴에서는 계정 정보를 수정하고 로그아웃 할 수 있습니다.

### 내 정보 수정 <a href="#undefined" id="undefined"></a>

로그인한 계정의 정보를 확인하고 이름과 프로필 URL, 대시보드 시간대를 변경할 수 있습니다. 프로필 URL은 채팅 시 사용됩니다.\
내 정보를 수정하는 방법은 다음과 같습니다.

1. Game Chat 대시보드 우측 상단의 사용자 아이콘을 클릭한 후 회원정보 수정 메뉴를 클릭해 주십시오.
2. 내 정보 수정 메뉴에서 이름 또는 프로필 URL, 시간대를 설정하고 **\[저장]** 버튼을 클릭해 주십시오.

### 비밀번호 변경 <a href="#undefined" id="undefined"></a>

비밀번호를 변경하는 방법은 다음과 같습니다.

1. Game Chat 대시보드 우측 상단의 사용자 아이콘을 클릭한 후 **회원정보 수정** 메뉴를 클릭해 주십시오.
2. 비밀번호 변경 메뉴를 클릭한 후, 현재 비밀 번호와 변경할 비밀번호를 입력하고 **\[저장]** 버튼을 클릭해 주십시오.

## 대시보드 로그아웃

Game Chat 대시보드에서 로그아웃하려면 Game Chat 대시보드 우측 상단의 사용자 아이콘을 클릭한 후 **로그아웃** 메뉴를 클릭해 주십시오.<br>


# Unity SDK

Game Chat Unity SDK 사용 방법에 대해 설명합니다.

## 요구 사양 <a href="#undefined" id="undefined"></a>

Game Chat Unity SDK를 사용하기 위한 요구 사양은 다음과 같습니다.

* 최소 사양: 2018.4.0 이상\
  (하위 버전의 Unity 지원이 필요할 경우 '<cs@nbase.io>' 이메일로 문의해 주십시오. )
* 2019.4.X / 2020.3.X / 2021.1.X 버전의 Unity 에디터 사용자는 2019.4.29f1 이상 / 2020.3.15f2 이상 / 2021.1.16f1 이상 버전을 사용해 주십시오(AAB 버전 빌드 시 Unity 에디터 버그 수정 버전).

## SDK 설치 및 환경 구성 <a href="#sdk" id="sdk"></a>

Game Chat Unity SDK를 다운로드하고 Unity에서 프로젝트를 구성하는 방법은 다음과 같습니다.

1. **Game Chat 대시보드 > 설정** > **SDK 다운로드** 메뉴를 차례대로 클릭한 후 **Unity SDK 다운로드**를 클릭해 주십시오.
2. Unity 프로그램을 실행한 후 프로젝트를 생성해 주십시오.
3. Unity에서 **Assets** > **Import Package** > **Custom Package...** 메뉴를 차례대로 클릭해 주십시오.
4. 대시보드에서 다운로드한 'GameChatUnitySDK\_xxxxxxxx' 파일을 불러와 주십시오.
5. 패키지에 있는 모든 파일을 선택한 후 **\[Import]** 버튼을 클릭해 주십시오.
6. 프로젝트를 저장해 주십시오.

## 인증

### Game Chat 인스턴스 초기화 <a href="#game-chat" id="game-chat"></a>

Game Chat 프로젝트 아이디를 활용하여 GameChat 인스턴스를 초기화하려면 아래 코드를 사용해 주십시오.

```csharp
GameChat.initialize(PROJECT_ID);

// 싱가폴 리전 사용 시
GameChat.setRegion("sg");
GameChat.initialize(PROJECT_ID);
```

| ID          | type   | desc     |
| ----------- | ------ | -------- |
| PROJECT\_ID | string | 프로젝트 아이디 |

### Game Chat 소켓 서버 연결 <a href="#gamechat" id="gamechat"></a>

Game Chat 소켓 서버에 연결하는 방법은 다음과 같습니다.

1. 채팅 사용자 아이디를 사용하여 Game Chat 소켓 서버에 접속해 주십시오.
   * Game Chat 프로젝트에서 채팅 사용자 아이디는 고유한 값입니다.
2. API를 사용하기 위한 토큰값을 획득해 주십시오.
   * GameChat.connect 이후에 갱신된 토큰값을 확인할 수 있습니다.
3. 토큰값을 획득한 후 현재 접속 디바이스에 대한 채팅 사용자 정보가 갱신되었는지 확인해 주십시오.
   * GameChat.connect의 콜백으로 전달받는 Member는 갱신된 데이터입니다.

GameChat 소켓 서버에 연결하려면 아래 코드를 사용해 주십시오.

```csharp
GameChat.connect(USER_ID,  (Member User, GameChatException Exception)=> 
{

    if(Exception != null)
    {
        // Error 핸들링
        return;
    }
});
```

| ID       | type   | desc          |
| -------- | ------ | ------------- |
| USER\_ID | string | 채팅 사용자 고유 아이디 |

### Game Chat 서버 연결 해제

Game Chat 소켓 서버와의 연결을 해제하려면 아래 코드를 사용해 주십시오.

```csharp
GameChat.disconnect();
```

### 채팅 사용자 정보 업데이트

connect 성공이 후 채팅 사용자 정보를 저장하고 업데이트하려면 아래 코드를 사용해 주십시오.

#### **닉네임 수정**

```csharp
GameChat.setNickname(USER_ID, NickName, (member, exception) =>
{
    if (exception != null)
    {
        // Error 핸들링
        return;
    }
    
});
```

| ID       | type   | desc          |
| -------- | ------ | ------------- |
| USER\_ID | string | 채팅 사용자 고유 아이디 |
| NickName | string | 채팅 사용자 닉네임    |

#### **Profile URL 수정**

```csharp
GameChat.setProfileUrl(USER_ID, ProfileUrl, (member, exception) =>
{
    if (exception != null)
    {
        // Error 핸들링
        return;
    }
    
});
```

| ID         | type   | desc              |
| ---------- | ------ | ----------------- |
| USER\_ID   | string | 채팅 사용자 고유 아이디     |
| ProfileUrl | string | 채팅 사용자 ProfileUrl |

## 채널 구독 및 구독 해제 <a href="#undefined" id="undefined"></a>

특정 채널에 Subscribe하거나 Unsubscribe하려면 아래 코드를 사용해 주십시오.

```csharp
GameChat.subscribe(CHANNEL_ID);

GameChat.unsubscribe(CHANNEL_ID);
```

| ID          | type   | desc   |
| ----------- | ------ | ------ |
| CHANNEL\_ID | string | 채널 아이디 |

## 메시지 송신 <a href="#undefined" id="undefined"></a>

특정 채널에 메시지를 보내려면 아래 코드를 사용해 주십시오.

```csharp
GameChat.sendMessage(CHANNEL_ID, MESSAGE);
```

| ID          | type   | desc       |
| ----------- | ------ | ---------- |
| CHANNEL\_ID | string | 채널 아이디     |
| MESSAGE     | string | 전송 메시지 텍스트 |

MESSAGE 파라미터에 @\[유저아이디] 공백 \[메시지 내용]으로 입력 시

```csharp
@user_id 메시지본문
```

위 케이스에서 유저아이디가 로그인된 이력이 있는 경우에 메시지 상세 정보 중 mentions의 정보는 유저아이디입니다.

## 이벤트 등록 및 해제 <a href="#undefined" id="undefined"></a>

Game Chat 소켓 서버로부터 수신되는 이벤트에 대해, 커스텀 핸들러를 등록하거나 해제하려면 아래 코드를 사용해 주십시오.

```csharp
GameChat.dispatcher.(EVENT_NAME) += (CALLBACK_FUNCTION);
```

```csharp
public delegate void onConnectedCallback(string data);
public onConnectedCallback onConnected;
//'connect' Event에 대한, callback

public delegate void onDisconnectedCallback(string reason);
public onDisconnectedCallback onDisconnected;
//'disconnect' Event에 대한, callback

public delegate void onMessageReceivedCallback(Message message);
public onMessageReceivedCallback onMessageReceived;
//'message' Event에 대한, callback

public delegate void onUserAddedCallback(UserInfo userinfo);
public onUserAddedCallback onUserAdded;
//'userAdded' Event에 대한, callback

public delegate void onUserRemovedCallback(Message message);
public onUserRemovedCallback onUserRemoved;
//'userRemoved' Event에 대한, callback

public delegate void onErrorReceivedCallback(string result, GameChatException exception);
public onErrorReceivedCallback onErrorReceived;
//'error' Event에 대한, callback
```

## 예외 사항 <a href="#undefined" id="undefined"></a>

Game Chat API 사용 중에 발생하는 Exception에 대한 공통 처리 Class는 다음과 같습니다.

```csharp
public class GameChatException
{
    // Detail Error Code
   
    // 알 수 없는 Error
    public static readonly int CODE_UNKNOWN_ERROR           = 0;
    // 초기화 실패
    public static readonly int CODE_NOT_INITALIZE           = 1;
    // 파라미터가 올바르지 않은 경우
    public static readonly int CODE_INVAILD_PARAM           = 2;  
    // 소켓서버로부터 발생한 오류
    public static readonly int CODE_SOCKET_SERVER_ERROR     = 500;
    //소켓으로부터 발생한 오류
    public static readonly int CODE_SOCKET_ERROR = -501;
    // 네트워크 연결 오류 및 타임아웃 발생 시
    public static readonly int CODE_SERVER_NETWORK_ERROR    = 4002;
    // 서버에서 받은 데이터를 파싱할 때 오류
    public static readonly int CODE_SERVER_PARSING_ERROR    = 4003;

    // HTTP 에러의 경우, 해당 상태코드가 응답코드로 전달됩니다. (400, 403 ...)

    // Error Code
    public int code { get; set; }
    // Error Message
    public string message { get; set; }
}
```

## Client API <a href="#clientapi" id="clientapi"></a>

### 채널 구독 <a href="#undefined" id="undefined"></a>

**Subscription Data Class (per Unit)**

```csharp
public class Subscription
{
    public string id;
    public string channel_id;
    public string user_id;
    public string created_at;
}
```

| ID          | type   | desc          |
| ----------- | ------ | ------------- |
| id          | string | 유니크 아이디       |
| channel\_id | string | 채널 아이디        |
| user\_id    | string | 채팅 사용자 고유 아이디 |
| created\_at | string | 생성 일자         |

#### **채널 Subscription 목록 가져오기**

특정 채널의 Subscription 데이터를 목록 형태로 가져오려면 아래 코드를 사용해 주십시오.

```csharp
GameChat.getSubscriptions(CHANNEL_ID, OFFSET, LIMIT, (List<Subscription> Subscriptions, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error 핸들링
        return;
    }

    foreach(Subscription elem in Subscriptions)
    {
        //handling each subscription instance
    }
}));
```

### 채널 <a href="#undefined" id="undefined"></a>

**Channel Data Class (per Unit)**

```csharp
public class Channel
{
    public string id;
    public string project_id;
    public string unique_id;
    public string name;
    public string user_id;
    public string created_at;
    public string updated_at;
}
```

<table><thead><tr><th width="158">ID</th><th width="137">type</th><th>desc</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>채널 아이디(unique)</td></tr><tr><td>project_id</td><td>string</td><td>프로젝트 아이디</td></tr><tr><td>unique_id</td><td>string</td><td>개발사에서 설정 가능한 채널 아이디 (unique)</td></tr><tr><td>name</td><td>string</td><td>채널 이름</td></tr><tr><td>user_id</td><td>string</td><td>(채널 생성한) 채팅 사용자 아이디</td></tr><tr><td>created_at</td><td>string</td><td>생성 일자</td></tr><tr><td>updated_at</td><td>string</td><td>갱신 일자</td></tr></tbody></table>

#### **채널 목록 가져오기**

프로젝트의 채널 데이터를 목록 형태로 가져오려면 아래 코드를 사용해 주십시오.

```csharp
GameChat.getChannels(OFFSET, LIMIT, (List<Channel> Channels, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error 핸들링
        return;
    }

    foreach(Channel elem in Channels)
    {
        //handling each channelInfo instance
    }
});
```

<table><thead><tr><th width="162">ID</th><th width="163">type</th><th>desc</th></tr></thead><tbody><tr><td>OFFSET</td><td>int</td><td>전체 채널 목록에서 가져올 채널의 시작 위치 (index)</td></tr><tr><td>LIMIT</td><td>int</td><td>가져올 채널 개수</td></tr></tbody></table>

#### **채널 데이터 가져오기**

채널 ID 및 UniqueID를 활용하여 채널 데이터를 가져오려면 아래 코드를 사용해 주십시오.

```csharp
//CHANNEL_ID로만 Search 할 경우, CHANNEL_UNIQUE_ID 파라미터에 null을 넣어 주십시오.

//CHANNEL_ID와 CHANNEL_UNIQUE_ID값이 함께 존재하면 CHANNEL_UNIQUE_ID 값을 우선으로 Search합니다.

GameChat.getChannel(CHANNEL_ID, CHANNEL_UNIQUE_ID,  (Channel Channel, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error 핸들링
        return;
    }

    //handling channelInfo instance
});
```

```csharp
GameChat.getChannel(CHANNEL_UNIQUE_ID, (Channel Channel, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error 핸들링
        return;
    }

    //handling channelInfo instance
});
```

<table><thead><tr><th width="222">ID</th><th width="150">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>채널 아이디 (auto generated)</td></tr><tr><td>CHANNEL_UNIQUE_ID</td><td>string</td><td>채널 (고유) 아이디 (customizing available)</td></tr></tbody></table>

### 채널 생성 및 삭제 <a href="#undefined" id="undefined"></a>

프로젝트 내 새로운 채널을 생성 및 삭제하려면 Open API를 활용해야 합니다. 보안 문제로 인해 채널 생성, 업데이트 등을 Open API를 활용하여 Server to Server로 직접 생성 하시는걸 추천 드립니다. 자세한 내용은 [Game Chat API 가이드](https://api.ncloud-docs.com/docs/game-gamechat){target="\_blank"}를 참고해 주십시오.

### 메시지 <a href="#undefined" id="undefined"></a>

**(Received) Message Data Class (per Unit)**

```csharp
public class Message
{
    public class User
    {
        public string id;
        public string name;
        public string profile;
    }

    public string message_id;
    public string channel_id;
    public string message_type;
    public string content;

    public string[] mentions;
    public bool mentions_everyone;
    public User sender;
    public string created_at;
}
```

<table><thead><tr><th width="181">ID</th><th width="116">type</th><th>desc</th></tr></thead><tbody><tr><td>message_id</td><td>string</td><td>메시지 유니크 아이디</td></tr><tr><td>channel_id</td><td>string</td><td>채널 아이디</td></tr><tr><td>message_type</td><td>string</td><td>메시지 타입</td></tr><tr><td>content</td><td>string</td><td>메시지 내용 (json string)</td></tr><tr><td>mentions</td><td>string</td><td>멘션(태그)</td></tr><tr><td>created_at</td><td></td><td>string</td></tr></tbody></table>

#### **메시지 목록 가져오기**

특정 채널에 대한 메시지 데이터를 목록 형태로 가져오려면 아래 코드를 사용해 주십시오.

```csharp
GameChat.getMessages(CHANNEL_ID, OFFSET, LIMIT, SEARCH, QUERY, SORT, (List<Message> Messages, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error 핸들링
        return;
    }

    foreach(Message elem in Messages)
    {
        //handling each message instance
    }
});
```

<table><thead><tr><th width="164">ID</th><th width="118">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>채널 아이디</td></tr><tr><td>OFFSET</td><td>string</td><td>전체 메시지 목록에서 가져올 메시지의 시작 위치</td></tr><tr><td>LIMIT</td><td>string</td><td>가져올 메시지 개수</td></tr><tr><td>SEARCH</td><td>string</td><td>메시지 검색 기준 key. &#x3C;예시> content.text<br>빈 문자열 전달 시, full scan</td></tr><tr><td>QUERY</td><td>string</td><td><p>메시지 검색 value. 완전 일치만 검색 가능. 빈 문자열 전달 시, </p><p>full scan</p></td></tr><tr><td>SORT</td><td>string</td><td>메시지 정렬 순서 (default : desc - 가장 최근 순) (optional : asc)</td></tr></tbody></table>

#### **메시지 번역**

자동 번역 기능이 활성화되어 있을 경우, 임의의 텍스트를 지정한 언어로 번역할 수 있습니다. 자동 번역 기능은 [Papago Translation](https://www.ncloud.com/product/aiService/papagoTranslation){target="\_blank"} 서비스와 연동한 후에 사용할 수 있습니다.

**(Received) Translation Data Class (per Unit)**

```csharp
public class Translation
{
    public string detectLang = "";
    public string lang = "";
    public bool translated = false;
    public string message = "";
}
```

<table><thead><tr><th width="192">ID</th><th width="149">type</th><th>desc</th></tr></thead><tbody><tr><td>detectLang</td><td>string</td><td>출발 언어 코드</td></tr><tr><td>lang</td><td>string</td><td>도착 언어 코드</td></tr><tr><td>translated</td><td>bool</td><td>번역 성공 여부</td></tr><tr><td>message</td><td>string</td><td>결과 메시지 내용 (json string)</td></tr></tbody></table>

> 참고
>
> 출발 언어 코드와 도착 언어 코드에 대한 설명은 [Papago Text Translation API 가이드](https://api.ncloud-docs.com/docs/ai-naver-papagonmt-translation){target="\_blank"}를 참고해 주십시오.&#x20;

```csharp
GameChat.translateMessage(CHANNEL_ID, SORCE_LANG, TARTGET_LANG, TEXT, (List<Translation> Translations, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error 핸들링
        return;
    }

    foreach(Translation elem in Translations)
    {
        //handling each Translation instance
    }
});

GameChat.translateMessage(SORCE_LANG, TARTGET_LANG, TEXT, (List<Translation> Translations, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error 핸들링
        return;
    }

    foreach(Translation elem in Translations)
    {
        //handling each Translation instance
    }
});
```

<table><thead><tr><th width="178">ID</th><th width="102">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>채널 아이디</td></tr><tr><td>SORCE_LANG</td><td>string</td><td>송신할 텍스트 언어명 (auto: 자동감지)<br><a href="https://api.ncloud-docs.com/docs/ai-naver-papagonmt-translation">API Guide</a>{target="_blank"} 참고</td></tr><tr><td>TARTGET_LANG</td><td>string</td><td>(번역 수신할) 텍스트 언어 코드<br>(","로 구분하여 복수 입력 가능. &#x3C;예시> "en, fr, th")<br><a href="https://api.ncloud-docs.com/docs/ai-naver-papagonmt-translation">Papago Text Translation API 가이드 </a>{target="blank"} 참고</td></tr><tr><td>TEXT</td><td>string</td><td>송신할 텍스트</td></tr></tbody></table>

### 채팅 사용자 <a href="#undefined" id="undefined"></a>

**(Received) Member Data Class (per Unit)**

```csharp
public class Member
{
    public string id = "";
    public string project_id = "";
    public string nickname = "";
    public string profile_url = "";
    public string country = "";
    public string remoteip = "";
    public string adid = "";
    public string device = "";
    public string network = "";
    public string version = "";
    public string model = "";
    public string logined_at = "";
    public string created_at = "";
    public string updated_at = "";
}
```

<table><thead><tr><th width="191">ID</th><th width="137">type</th><th>desc</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>채팅 사용자 고유 아이디</td></tr><tr><td>project_id</td><td>string</td><td>로그인한 Game Chat 프로젝트 아이디</td></tr><tr><td>nickname</td><td>string</td><td>채팅 사용자 닉네임</td></tr><tr><td>profile_url</td><td>string</td><td>프로필 이미지 URL</td></tr><tr><td>country</td><td>string</td><td>접속 국가</td></tr><tr><td>remoteip</td><td>string</td><td>접속 IP</td></tr><tr><td>adid</td><td>string</td><td>광고 식별자</td></tr><tr><td>device</td><td>string</td><td>접속 디바이스 환경</td></tr><tr><td>network</td><td>string</td><td>접속 네트워크 타입(CELLULAR, WIFI)</td></tr><tr><td>version</td><td>string</td><td>접속 앱 버전</td></tr><tr><td>model</td><td>string</td><td>접속 디바이스 모델</td></tr><tr><td>logined_at</td><td>string</td><td>로그인한 일자</td></tr><tr><td>created_at</td><td>string</td><td>채팅 사용자 생성 일자</td></tr><tr><td>updated_at</td><td>string</td><td>채팅 사용자 정보 갱신 일자</td></tr></tbody></table>

#### **채팅 사용자 정보 업데이트**

채팅 서버의 사용자 정보를 업데이트할 수 있습니다.

```csharp

// 채팅 사용자 닉네임 업데이트
// 닉네임 허용 문자열은 whitespace(spaces, tabs, line breaks)를 포함하지 않는 2~128자입니다.
GameChat.setName(MEMBER_ID, NAME, (Member member, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error 핸들링
        return;
    }
    //handling updated Member instance
});

//채팅 사용자 프로필 이미지 url 업데이트
GameChat.setProfileUrl(MEMBER_ID, PROFILE_URL, (Member member, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error 핸들링
        return;
    }
    //handling updated Member instance
});

```

<table><thead><tr><th width="183">ID</th><th width="138">type</th><th>desc</th></tr></thead><tbody><tr><td>MEMBER_ID</td><td>string</td><td>채팅 사용자 고유 아이디</td></tr><tr><td>NAME</td><td>string</td><td>채팅 사용자 닉네임 혹은 이름</td></tr><tr><td>PROFILE</td><td>string</td><td>프로필 이미지 URL</td></tr></tbody></table>

## GameChatExtension (Emoji, HyperLink) <a href="#gamechatextensionemojihyperlink" id="gamechatextensionemojihyperlink"></a>

수신 메시지에 포함된 Emoji와 HyperLink 텍스트를 쉽게 다룰 수 있도록 도와주는 Helper Class 입니다.

* TMP\_GameChatTextUGUI는 Unity Built-In Asset인 TextMeshPro를 확장한 클래스이므로 먼저 Package Manager를 이용하여 TextMeshPro를 설치해야 합니다.
* TextMeshPro Asset의 경우, Unity 2018.2 이상의 버전부터 Built-In Asset으로 포함됩니다.
* Emoji Sprite Sheet의 경우, Emoji version 13(Android)를 기준으로 기본 출력되며 Sprite Sheet를 변경하여 커스터마이징이 가능합니다.

```csharp
namespace GameChatUnity.Extension
{
    public class TMP_GameChatTextUGUI : TextMeshProUGUI
    {
        public bool isHyperLinked { get; set; }    // link 형태 주소를 hyperlink 처리 여부 (append html tag)
        public string LinkTextColor { get; set; }  // hyperlink text color
    }
}
```

**<예시>**

```csharp
using GameChatUnity.Extension;

TMP_GameChatTextUGUI message = msgObject.GetComponent<TMP_GameChatTextUGUI>();

//hyperlink 인식 및 처리를 위해, text는 setMessage를 통해 넣어 주십시오.
message.setMessage(MESSAGE_CONTENT);
message.color = Color.green;
message.isHyperLinked = true;

...

msgObject = Instantiate(msgObject) as GameObject;

...

// hyperlink에 대한 click event listener는, 직접 구현해 주십시오.

//Handling with TMP_LinkInfo
TMP_LinkInfo linkInfoArr = message.textInfo.linkInfo[LINK_INDEX];

...
```


# OpenAPI

Game Chat의 몇몇 기능을 규정된 API로 호출할 수 있는 기능입니다.

> 참고
>
> 대시보드에서 발급한 허용된 API Key를 사용해야 호출이 가능합니다.

## API Key 확인 <a href="#apikey" id="apikey"></a>

API Key는 **대시보드** > **설정** > **프로젝트 설정** > **API Key**에서 생성할 수 있습니다.

> 주의
>
> **\[재발급]** 버튼을 클릭하면 키가 재발급되며, 이전 키는 사용할 수 없으니 주의해 주십시오.

## Open API 사용하기 <a href="#openapi" id="openapi"></a>

### Base URL <a href="#baseurl" id="baseurl"></a>

```curl
https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}
- {projectId}부분에는 Game Chat의 project id를 적용
```

<table><thead><tr><th width="185">Region</th><th>URL</th></tr></thead><tbody><tr><td>kr</td><td>https://dashboard-api.gamechat.naverncp.com/v1</td></tr><tr><td>sg</td><td>https://sg-dashboard-api.gamechat.naverncp.com/v1</td></tr><tr><td>jp</td><td>https://jp-dashboard-api.gamechat.naverncp.com/v1</td></tr></tbody></table>

### 공통 오류 코드 <a href="#undefined" id="undefined"></a>

Open API 요청 시 발생하는 공통 에러코드는 다음과 같습니다.

<table><thead><tr><th width="177">Code</th><th>Description</th></tr></thead><tbody><tr><td>-1</td><td>대시보드에 없는 키를 사용한 경우</td></tr><tr><td>-2</td><td>대시보드의 키와 헤더의 키가 다른경우</td></tr><tr><td>-3</td><td>대시보드에서 삭제한 키를 사용한 경우</td></tr><tr><td>-4</td><td>대시보드에서 미사용으로 처리된 키를 사용한 경우</td></tr><tr><td>-5</td><td>키가 만료된 경우</td></tr><tr><td>-6</td><td>프로젝트 아이디가 없는 경우</td></tr></tbody></table>


# 채널 생성

채널을 생성합니다.

## 요청 <a href="#undefined" id="undefined"></a>

* Method : POST
* URI : /channel

```
POST
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel
Header : 'x-api-key: {API Key}'
Header : 'content-type: application/json'
data: '{
    "name":"#All"
}'
```

<table><thead><tr><th width="146">Header</th><th width="97">Type</th><th width="113">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>대시보드 > 설정 > 프로젝트 설정 > API Key</td></tr></tbody></table>

<table><thead><tr><th width="148">Attribute</th><th width="99">Type</th><th width="109">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>프로젝트 아이디 (대시보드 > 설정 > 프로젝트 설정 > 프로젝트 ID)</td></tr><tr><td>name</td><td>String</td><td>O</td><td>채널 명</td></tr><tr><td>translation</td><td>Boolean</td><td>X</td><td>번역 가능 여부</td></tr><tr><td>uniqueId</td><td>String</td><td>X</td><td>임의로 지정할 수 있는 고유 아이디</td></tr></tbody></table>

## 응답 <a href="#undefined" id="undefined"></a>

```javascript
{
    "status": 1,
    "result": "1a51af0d-f464-4440-8ad6-ce69e0bdaba8"
}
```

<table><thead><tr><th width="137">Attribute</th><th width="134">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>결과값 (1: 성공, 실패는 Error code 참고)</td></tr><tr><td>result</td><td>String</td><td>생성된 채널 아이디</td></tr></tbody></table>

## 오류 코드 <a href="#undefined" id="undefined"></a>

<table><thead><tr><th width="226">Code</th><th>Description</th></tr></thead><tbody><tr><td>-100</td><td>필수 파라미터가 없는 경우</td></tr></tbody></table>


# 채널 수정

채널에 세부 정보를 정보를 수정합니다.

## 요청 <a href="#undefined" id="undefined"></a>

* Method : PUT
* URI : /channel

```
PUT
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel
Header : 'x-api-key: {API Key}'
Header : 'content-type: application/json'
data: '{
    "name":"#All",
}'
```

<table><thead><tr><th width="126">Header</th><th width="111">Type</th><th width="120">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>대시보드 > 설정 > 프로젝트 설정 > API Key</td></tr></tbody></table>

<table><thead><tr><th width="130">Attribute</th><th width="105">Type</th><th width="123">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>프로젝트 아이디 (대시보드 > 설정 > 프로젝트 설정 > 프로젝트 ID)</td></tr><tr><td>name</td><td>String</td><td>O</td><td>채널 명</td></tr><tr><td>translation</td><td>Boolean</td><td>X</td><td>번역 가능 여부</td></tr><tr><td>uniqueId</td><td>String</td><td>X</td><td>임의로 지정할 수 있는 고유 아이디</td></tr><tr><td>limit</td><td>Int</td><td>X</td><td>채널내 최대 참여자 수 ( 0 일 경우 제한 없음 )</td></tr></tbody></table>

## 응답 <a href="#undefined" id="undefined"></a>

```javascript
{
    "status": 1,
    "result": "1a51af0d-f464-4440-8ad6-ce69e0bdaba8"
}
```

<table><thead><tr><th width="168">Attribute</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>결과값 (1: 성공, 실패는 Error code 참고)</td></tr><tr><td>result</td><td>String</td><td>수정된 채널 아이디</td></tr></tbody></table>

## 오류 코드 <a href="#undefined" id="undefined"></a>

<table><thead><tr><th width="235">Code</th><th>Description</th></tr></thead><tbody><tr><td>-100</td><td>필수 파라미터가 없는 경우</td></tr></tbody></table>


# 채널 삭제

채널을 삭제합니다.

## 요청 <a href="#undefined" id="undefined"></a>

* Method : DELETE
* URI : /channel/{channelId}

```
DELETE
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel/{channelId}
Header : 'x-api-key: {API Key}'
```

<table><thead><tr><th width="141">Header</th><th width="114">Type</th><th width="112">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>대시보드 > 설정 > 프로젝트 설정 > API Key</td></tr></tbody></table>

<table><thead><tr><th width="142">Attribute</th><th width="112">Type</th><th width="115">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>프로젝트 아이디 (대시보드 > 설정 > 프로젝트 설정 > 프로젝트 ID)</td></tr><tr><td>channelId</td><td>String</td><td>O</td><td>채널 아이디</td></tr></tbody></table>

## 응답 <a href="#undefined" id="undefined"></a>

성공

```javascript
{
    "status": 1,
    "message": "success"
}
```

<table><thead><tr><th width="136">Attribute</th><th width="124">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>결과값 (1: 성공, 실패는 Error code 참고)</td></tr><tr><td>message</td><td>String</td><td>결과 메시지</td></tr></tbody></table>


# Game Chat 리소스 관리

Game Chat 서비스의 리소스 정보를 확인합니다.

Game Chat 서비스에서 사용자가 수행할 수 있는 모든 활동은 Resource Manager에서 정의한 리소스 유형 및 리소스 유형별 작업 내역(액션)과 매핑됩니다. \
매핑된 값을 기준으로 사용자가 실제 수행한 활동 이력은 Cloud Activity Tracer에서 수집하여, 관리자가 사용자들의 활동을 모니터링하거나 감사 보고서를 작성할 때 활용할 수 있습니다. 또한 리소스 유형은 Sub Account에서 사용자별 사용 권한의 기준으로도 사용됩니다. 리소스와 리소스 유형별 작업 내역에 대한 설명은 다음과 같습니다.

* 리소스
  * 각 서비스에서 관리하는 주요 정보 단위
  * 사용자가 생성하고 변경하고 삭제할 수 있는 객체
  * 네이버 클라우드 플랫폼 서비스별 고유한 값
* 리소스 유형별 작업 내역(액션)
  * 사용자가 콘솔 및 API를 통해 수행한 작업 이력
  * 리소스를 생성하거나 변경하거나 삭제하는 행위

Game Chat 서비스의 리소스 유형과 리소스 유형별 작업 내역 정보는 다음과 같습니다.

| 서비스 이름(상품 코드) | 리소스 유형  | 리소스 유형별 작업 내역          |
| ------------- | ------- | ---------------------- |
| Game Chat     | Project | Change Account         |
|               |         | Change License         |
|               |         | Change Project Name    |
|               |         | Create Project         |
|               |         | Delete Project         |
|               |         | Initialize Password    |
|               |         | Initialized            |
|               |         | Request initialization |

> 참고
>
> * Resource Manager: 네이버 클라우드 플랫폼에서 무료로 제공하는 서비스입니다. 자세한 사용 방법은 [Resource Manager 사용 가이드](https://guide.ncloud-docs.com/docs/resourcemanager-overview)를 참조해 주십시오.
> * Cloud Activity Tracer: 네이버 클라우드 플랫폼에서 무료로 제공하는 서비스입니다. 자세한 사용 방법은 [Cloud Activity Tracer 사용 가이드](https://guide.ncloud-docs.com/docs/cat-overview)를 참조해 주십시오.
> * Sub Account: 네이버 클라우드 플랫폼에서 무료로 제공하는 서비스입니다. Resource Manager 서비스에서 정의한 리소스 유형을 기준으로 권한을 설계하지만, 리소스 유형 그룹과 리소스 유형별 액션은 Sub Account 서비스에서 자체적으로 구성하기 때문에 Resource Manager 서비스에서 정의한 그룹 및 액션 값과 상이합니다.


# Game Chat 릴리즈 노트

Game Chat 사용 가이드에 대한 릴리스 노트입니다. 자세한 내용은 다음과 같습니다.

<table><thead><tr><th width="162">릴리스 날짜</th><th width="208">릴리스 항목</th><th>릴리스 내용</th></tr></thead><tbody><tr><td>2022. 2. 16.</td><td>사용 가이드 개정</td><td>- 콘텐츠 구조 개선<br>- 스타일 가이드 적용</td></tr><tr><td>2022. 7. 21.</td><td>프로젝트 이름 변경 기능</td><td>- 프로젝트 이름 변경 기능 추가</td></tr></tbody></table>


# Game Chat(English)

> Game Chat is a service where you can implement real-time chats, message system, and multi-user chat channels in a game. Various SDKs and APIs are provided, so you can build an in-game chat service easily and simply.

### A variety of features Game Chat offers <a href="#gamechat" id="gamechat"></a>

* Convenient dashboard \
  The mobile-accessible Game Chat dashboard allows you to view message statistics, manage chat channels (guilds), block malicious users, filter swear and vulgar words, and download and search chat messages.
* 1:1 chat \
  This service supports notification message delivery to specific users, as well as a stable 1:1 chat system between users.
* Automatic, real-time multilingual message translations \
  The linkage feature with NAVER's powerful AI translation solution, Papago, is provided so you can easily talk to people from different countries. You can use the automatic translation feature to easily build a community with global users.
* Block profanities and malicious users \
  You can filter and delete messages that contain swears and profanities to build a healthy chat environment. You can also set it so that malicious users (players) are blocked from using chats for a certain period of time.
* Real-time analysis indicators \
  It provides various analysis indicators for you to analyze the users' login and message delivery statuses.

### About Game Chat guide <a href="#gamechat" id="gamechat"></a>

The Game Chat guide consists of the following topics to help you effectively use Game Chat. The content that readers can view in each topic is as follows.

* Game Chat overview: Introduction to Game Chat, features, related resources
* Prerequisites for using Game Chat: Preparations to make before using Game Chat
* Getting started with Game Chat: How to request subscription to the Game Chat service
* Using Game Chat: How to use features available for Game Chat users
  * Game Chat operation and management: How to access and use the dashboard
  * Game Chat Unity SDK: How to use Game Chat SDK for Unity
* Managing Game Chat permissions: How to manage permissions for Game Chat Sub Account and policies
* Game Chat release notes: Update history of Game Chat guides


# Prerequisites for using Game Chat

This page describes service specifications, preparations, and pricing information for smooth use of Game Chat.

## Service specifications <a href="#undefined" id="undefined"></a>

The SDK provided by Game Chat can be used in the following environments.

| Development environments | Required specifications  |
| ------------------------ | ------------------------ |
| Unity                    | Unity 2018.4.0 or higher |

## Usage Fees

When a project is created, it is set up as a free project, but costs will incur if converted to a paid plan.

<table><thead><tr><th width="125">Type</th><th width="130">Billing Tier</th><th width="143">Billing Criteria</th><th width="75">Fees</th><th width="257">Remarks</th></tr></thead><tbody><tr><td>Free</td><td>200 CCU below</td><td>Day</td><td>Free</td><td>When switching to a paid plan, billing begins. Includes 100GB of network usage.</td></tr><tr><td>Paid Basic Fee</td><td>2,000 CCU above</td><td>Day</td><td>7,333 KRW</td><td>Includes 2TB of network transfer.</td></tr></tbody></table>

* The Game Chat service provides 200 CCU in the free development tier.
* CCU is calculated based on the number of active users simultaneously connected to the chat channel.

## Additional Charges

<table><thead><tr><th width="185">Type</th><th width="176">Billing Tier</th><th width="142">Billing Criteria</th><th width="121">Fess</th><th width="100">Remarks</th></tr></thead><tbody><tr><td>Additional CCU</td><td>Over 2,000 ~ 10,000 below</td><td>CCU</td><td>150 KRW</td><td></td></tr><tr><td>Additional CCU</td><td>Over 10,000</td><td>CCU</td><td>100 KRW</td><td></td></tr><tr><td>Additional Network Usage</td><td>Over 2TB</td><td>GB</td><td>100 KRW</td><td></td></tr></tbody></table>

* If the CCU exceeds the basic tier, additional charges will apply.
* Pricing Example\
  \- A customer using 2,500 CCU from November 1st to November 30th (exceeding by 500 CCU)\
  \- (7,333 KRW \* 30 days) + (500 CCU \* 150 KRW) = 219,990 KRW + 75,000 KRW = 294,990 KRW If


# Getting started with Game Chat

This page describes how to request subscription to Game Chat and how to create and manage projects.

### Request subscription to the Game Chat service

To apply for the Game Chat service and create a project, please send an email to <cs@nbase.io> with the desired project name.

### Manage project

For requests such as changing the project name, resetting the admin account password, or deleting the project, please contact us via email at <cs@nbase.io>.

> Caution
>
> Please be careful since all project data will be deleted once the project is deleted.

#### Switch to paid plan

When you create a project, it will be a free development project that can use up to 200 CCUs a day. You must switch to a paid plan to use 200 CCUs or more. The following shows how to switch to a paid plan for your project.

1. Please log in to the Game Chat management page (dashboard).
2. Click the **\[Switch to paid plan]** button appeared at the bottom of the management page.
3. Check the notification window, and then click the **\[Confirm]** button.

   <br>

> Caution
>
> Please note that you can't switch back to the free environment once you've completed the switch from free to paid environment.


# Game Chat operation and management

This page describes how to operate and manage chats from the Game Chat dashboard, how to view chat-related statistics.

## Dashboard menu <a href="#undefined" id="undefined"></a>

The dashboard helps you view the operation status of your chats, including access status, message, and statistics at a glance. Check a graph for a date.

The dashboard menus are listed below.<br>

<figure><img src="/files/lJgjzQuTnO8Dt1JVewzq" alt=""><figcaption></figcaption></figure>

<table><thead><tr><th width="127">Number</th><th width="195">Menu</th><th>Description</th></tr></thead><tbody><tr><td>1</td><td>Dashboard</td><td>View logged-in user statistics</td></tr><tr><td>2</td><td>Member</td><td>View members and manage blocked members</td></tr><tr><td>3</td><td>Chat</td><td>Add and manage chat channels</td></tr><tr><td>4</td><td>Search</td><td>Search members</td></tr><tr><td>5</td><td>Settings</td><td>Project settings and dashboard user settings, download Unity SDK</td></tr><tr><td>6</td><td>Manage jobs</td><td>View the history of data exports from the Search menu</td></tr><tr><td>7</td><td>DOCS</td><td>- Unity: Go to Game Chat Unity Guide</td></tr><tr><td>8</td><td>Language settings</td><td>Dashboard language can be changed. Korean and English supported</td></tr><tr><td>9</td><td>Member information</td><td>Edit member information and logout</td></tr></tbody></table>

## Member <a href="#undefined" id="undefined"></a>

In the Member menu, you can view the information of members (game players) registered on the dashboard, block specific members from using chats, or withdraw them from all chats.

### View member information

The following describes how to view the information of members registered on the Game Chat dashboard.

1. Click the **Member** > **List** menu from the Game Chat dashboard.
2. Click the user ID to view the member's details.
3. Check the details at the right side of the page.
   * You can view the user's name, profile URL, country of access, ID, model, device ID, signed-up date, last logged-in date, etc.

<figure><img src="/files/snhM3RrDgTPCvGaE0KCJ" alt=""><figcaption></figcaption></figure>

6. To edit the member information, edit the name or profile URL and click the **\[Save]** button.
   * Only the name and profile URL can be edited.

### Withdraw from membership <a href="#undefined" id="undefined"></a>

The following describes how you can withdraw a specific member.

1. Click the **Member** > **List** menu from the Game Chat dashboard.
2. Click the member ID to withdraw.
3. When the member's details appear at the right side of the page, click the **\[Withdraw]** button.
4. When a pop-up confirmation window appears, click the **\[Yes]** button.

### Search members <a href="#undefined" id="undefined"></a>

The following describes how to search members registered on the Game Chat dashboard.

1. Click the **Member** > **List** menu from the Game Chat dashboard.
2. Set search conditions, and then click the **\[Search]** button.
   * Search conditions available are user ID creation date, user ID, nickname, country, and IP.
3. Check the search results.

### Block members <a href="#undefined" id="undefined"></a>

You can adjust settings so that a specific member is blocked from using chats for a certain period of time. In the Block menu, you can view and search members who have been blocked.\
The following describes how to block a specific member from using chats.

1. From the NAVER Cloud Platform console, click the **Services** > **Gaming** > **Game Chat** menus, in that order.
2. Click the management page URL for the project to log in to the dashboard.
3. Click the **Member** > **Block** menu from the Game Chat dashboard.
4. Click the **\[Add]** button located on the right side of the screen.
5. When the Block registration window appears, click the **\[Status]** icon and enable it.
6. If you also want to remove the member you're about to block from all channels, then mark the **Remove from chats** checkbox.
7. Set the user ID, reasons for the blocking, and block period, and then click the **\[Save]** button.

## Chat <a href="#undefined" id="undefined"></a>

In the Chat menu, you can view channels and send chat messages.

### Add chat channel <a href="#undefined" id="undefined"></a>

The following describes how to add a new chat channel.

1. Click the **Channel** menu from the Game Chat dashboard.
2. Click the **\[Add channel]** button.
3. When the Add channel window appears, enter the channel and unique ID, and then click the **\[Register]** button.
   * Enter a unique ID to access a channel with the value in the SDK.
4. Check if the channel has been created.

### Chat channel settings <a href="#undefined" id="undefined"></a>

The following describes how to check users participating in a specific chat channel, or edit or delete the channel information.

1. Click the **Channel** menu from the Game Chat dashboard.
2. Select a channel, and then click the : icon at the upper right of the channel page.
3. When the context menu appears, select the job you want.

<figure><img src="/files/wq4NGRA9JJq52F3FfBtQ" alt=""><figcaption></figcaption></figure>

* To view the list of users participating in the chat channel, click the **\[Participant list]** menu.
* To edit the chat channel information, click the **\[Edit channel]** menu.
* To delete the chat channel, click the **\[Delete]** menu.

## Search

In the Search menu, you can view and search messages exchanged in all channels of a project. You can search with ID, nickname, message, channel ID, or date and time the message is sent. You can also download the message list in a CSV file.

<figure><img src="/files/bNOVWe7eQ2Qz8BTf53Dp" alt=""><figcaption></figcaption></figure>

### Search message and view message details <a href="#undefined" id="undefined"></a>

The following describes how to view a message's details (channel ID where the message was composed, message ID, message, time the message was sent).

1. Click the **Search** menu from the Game Chat dashboard.
2. Set search conditions, and then click the **\[Search]** button.
   * You can search with following conditions: date the message was sent, member ID, channel ID, nickname, and message.
3. Click the View icon of the message you want to view the details.
4. You can see the channel ID where the message is registered, message ID, message, and the time the message was sent.

### Delete message <a href="#undefined" id="undefined"></a>

You can search for a specific message and delete it. The message deleted from the Search menu will also be deleted from the chat channel.

1. Click the **Search** menu from the Game Chat dashboard.
2. Click the Delete icon of the message you want to delete.
3. When the Confirm deletion window appears, click the **\[Yes]** button.

## Settings <a href="#undefined" id="undefined"></a>

In the Settings menu, you can set Game Chat project information, change how you handle banned words in chats and automatic message translation status, modify user information, or grant the admin permission to specific users.

### Project settings <a href="#undefined" id="undefined"></a>

The following describes how to view and edit the project information, set banned words, and use the automatic chat translation feature.

#### **View project information**

You can view NAVER Cloud ID, project ID, API key, project name, and the message length limit, and set project name, message length limit, and banned words.\
The following describes how to view project information.

1. Click the **Settings** > **Project settings** menu from the Game Chat dashboard.
2. Check the project information.
   * Only project name and message length limit can be modified.

#### **Banned word settings**

You can set words that are not usable in a chat (swear and vulgar words) as banned words to provide a healthy chat environment.\
The following shows how to set banned words.

1. Click the **Settings** > **Project settings** menu from the Game Chat dashboard.
2. Select the banned word restriction type.
   * No restriction: Display the banned words without any blinding
   * Substitute with \*: Display the words specified as banned words as \* in a chat window
   * Block message delivery: Do not send words specified as banned words
3. Click the **\[Use default banned words]** button to automatically import the banned word examples.
4. Click the **\[Save]** button.

#### **Automatic translation of chat messages**

Messages entered in a chat can be automatically translated by setting up linkage with Papago Translation, a service provided by NAVER Cloud Platform.\
How to set up the automatic translation of chat messages is as follows.

1. Click the **Settings** > **Project settings** menu from the Game Chat dashboard.
2. Click the Activation icon from the Papago area.
3. Enter the client ID and client secret, and then click the **\[Save]** button.

> Note
>
> For how to view the client ID and client secret for setting up linkage with Papago Translation, refer to [Application Guide](https://guide.ncloud-docs.com/docs/en/naveropenapiv3-application).

### User settings <a href="#undefined" id="undefined"></a>

You can view the project's users and or edit the user information. However, the details of the account currently logged in can be edited from the Edit member information menu.\
The following describes how to edit user information.

1. Click the **Settings** > **User settings** menu from the Game Chat dashboard.
2. Click ![game-gamechatmgmt\_icon\_en.png](https://files.document360.io/6998976f-9d95-4df8-b847-d375892b92c2/Images/Documentation/game-gamechatmgmt_icon_en.png) > **View more** menu of the user you want to edit the user information.
3. Set the user name, password, and user status, and then click the **\[Save]** button.
4. If you want to designate a certain user as the dashboard admin, then activate the Admin permission icon, and click the **\[Save]** button.
5. Click the **\[Delete]** button to delete the user information.

### Download SDK <a href="#sdk" id="sdk"></a>

You can download Unity SDK.

## Manage jobs <a href="#undefined" id="undefined"></a>

In the Manage jobs menu, you can download the export result of CSV files from the Search menu for 30 days.

## Edit member information <a href="#undefined" id="undefined"></a>

In the Member information menu, you can edit the account information and log out.

### Edit my information <a href="#undefined" id="undefined"></a>

Check the information of the logged-in account and change the name, profile URL, and dashboard time zone. Profile URL is used in chats.\
The following describes how to edit my information.

1. Click the User icon at the top right of the Game Chat dashboard, and then click the Edit member information menu.
2. From the Edit my information menu, set name, profile URL, or time zone, and then click the **\[Save]** button.

### Change password <a href="#undefined" id="undefined"></a>

The following describes how to change your password.

1. Click the User icon at the top right of the Game Chat dashboard, and then click the **Edit member information** menu.
2. Click the Change password menu, enter the current and new password, and then click the **\[Save]** button.

## Dashboard logout <a href="#undefined" id="undefined"></a>

To log out from the Game Chat dashboard, click the User icon at the top right of the Game Chat dashboard, and then click the **Log out** menu.


# Unity SDK

This page describes how to use the Game Chat Unity SDK.

## Requirements <a href="#undefined" id="undefined"></a>

The specifications required to use the Game Chat Unity SDK are as follows.

* Minimum specifications: 2018.4.0 or later\
  (If you need support for the lower version of Unity, then make an inquiry through [Contact us](https://www.ncloud.com/support/question).)
* If you are a user of Unity editor in the 2019.4.X/2020.3.X/2021.1.X version, then make sure to use a version at or above 2019.4.29f1/2020.3.15f2/2021.1.16f1 respectively (versions where the Unity editor bug is fixed when building the AAB version).

## Install SDK and configure environment <a href="#sdk" id="sdk"></a>

The following describes how to download Game Chat Unity SDK and configure a project in Unity.

1. Click the **Settings** > **Download SDK** menus, in that order, and then click **Download Unity SDK**.
2. Run Unity, and create a project.
3. In Unity, click the **Assets** > **Import Package** > **Custom Package...** menus, in that order.
4. Open the "GameChatUnitySDK\_xxxxxxxx" file downloaded in the dashboard.
5. Select all files in the package, and then click the **\[Import]** button.
6. Save the project.

## Authentication <a href="#undefined" id="undefined"></a>

### Reset Game Chat instance <a href="#gamechat" id="gamechat"></a>

To initialize Game Chat instances using the Game Chat project ID, use the code below.

```csharp
GameChat.initialize(PROJECT_ID);

// When using in the Singapore region
GameChat.setRegion("sg");
GameChat.initialize(PROJECT_ID);
```

| ID          | type   | desc       |
| ----------- | ------ | ---------- |
| PROJECT\_ID | string | Project ID |

### Connect to Game Chat socket server

The following describes how to connect to a Game Chat socket server.

1. Use the chat user ID to access a Game Chat socket server.
   * In a Game Chat project, the chat user ID is a unique value.
2. Get the token value for using the API.
   * The token value renewed can be viewed after GameChat.connect.
3. After acquiring the token value, check if the chat user information is renewed for the currently connected device.
   * The member data received with the GameChat.connect's callback is renewed data.

Use the following code to connect to the Game Chat socket server.

```csharp
GameChat.connect(USER_ID,  (Member User, GameChatException Exception)=> 
{

    if(Exception != null)
    {
        // Error handling
        return;
    }
});
```

| ID       | type   | desc                  |
| -------- | ------ | --------------------- |
| USER\_ID | string | Chat user's unique ID |

### Remove Game Chat server connection

To remove the connection with the Game Chat socket server, use the following code.

```csharp
GameChat.disconnect();
```

### Chat user information update <a href="#undefined" id="undefined"></a>

Use the following code to save and update the chat user information after a successful connect.

**Edit nickname**

```csharp
GameChat.setNickname(USER_ID, NickName, (member, exception) =>
{
    if (exception != null)
    {
        // Error handling
        return;
    }
    
});
```

| ID       | type   | desc                  |
| -------- | ------ | --------------------- |
| USER\_ID | string | Chat user's unique ID |
| NickName | string | Chat user's nickname  |

**Edit profile URL**

```csharp
GameChat.setProfileUrl(USER_ID, ProfileUrl, (member, exception) =>
{
    if (exception != null)
    {
        // Error handling
        return;
    }
    
});
```

| ID         | type   | desc                   |
| ---------- | ------ | ---------------------- |
| USER\_ID   | string | Chat user's unique ID  |
| ProfileUrl | string | Chat user's ProfileUrl |

## Subscribe and unsubscribe to channel

Use the following code to subscribe or unsubscribe to a specific channel.

```csharp
GameChat.subscribe(CHANNEL_ID);

GameChat.unsubscribe(CHANNEL_ID);
```

| ID          | type   | desc       |
| ----------- | ------ | ---------- |
| CHANNEL\_ID | string | Channel ID |

## Send message <a href="#undefined" id="undefined"></a>

Use the following code to send a message to a specific channel.

```csharp
GameChat.sendMessage(CHANNEL_ID, MESSAGE);
```

| ID          | type   | desc                 |
| ----------- | ------ | -------------------- |
| CHANNEL\_ID | string | Channel ID           |
| MESSAGE     | string | Message text to send |

When @\[User ID] space \[Message content] is entered for the MESSAGE parameter

```csharp
@user_id message content
```

In the above case, if the username has a history of being logged in, the "mentions" information from the message details is the user ID.

## Register and remove event

Use the following code to register or remove a custom handler for events received from a Game Chat socket server.

```csharp
GameChat.dispatcher.(EVENT_NAME) += (CALLBACK_FUNCTION);
```

```csharp
public delegate void onConnectedCallback(string data);
public onConnectedCallback onConnected;
//Callback regarding "connect" events

public delegate void onDisconnectedCallback(string reason);
public onDisconnectedCallback onDisconnected;
//Callback regarding "disconnect" events

public delegate void onMessageReceivedCallback(Message message);
public onMessageReceivedCallback onMessageReceived;
//Callback regarding "message" events

public delegate void onUserAddedCallback(UserInfo userinfo);
public onUserAddedCallback onUserAdded;
//Callback regarding "usedAdded" events

public delegate void onUserRemovedCallback(Message message);
public onUserRemovedCallback onUserRemoved;
//Callback regarding "userRemoved" events

public delegate void onErrorReceivedCallback(string result, GameChatException exception);
public onErrorReceivedCallback onErrorReceived;
//Callback regarding "error" events
```

## Exceptions <a href="#undefined" id="undefined"></a>

The public class for exceptions occurring while using the Game Chat API is as follows.

```csharp

public class GameChatException
{
    // Detail Error Code
   
    // Unknown error
    public static readonly int CODE_UNKNOWN_ERROR           = 0;
    // Initialization failed
    public static readonly int CODE_NOT_INITALIZE           = 1;
    // Invalid parameter
    public static readonly int CODE_INVAILD_PARAM           = 2;  
    // Errors occurred from the socket server
    public static readonly int CODE_SOCKET_SERVER_ERROR     = 500;
    //Errors occurred from the socket
    public static readonly int CODE_SOCKET_ERROR = -501;
    // Network connection error or timeout occurred
    public static readonly int CODE_SERVER_NETWORK_ERROR    = 4002;
    // Error occurred when parsing data received from the server
    public static readonly int CODE_SERVER_PARSING_ERROR    = 4003;

    // For HTTP errors, the status code is sent as the response code. (400, 403 ...)

    // Error Code
    public int code { get; set; }
    // Error Message
    public string message { get; set; }
}
```

## Client API

### Subscribe to channel <a href="#undefined" id="undefined"></a>

#### **Subscription Data Class (per Unit)**

```csharp
public class Subscription
{
    public string id;
    public string channel_id;
    public string user_id;
    public string created_at;
}
```

| ID          | type   | desc                  |
| ----------- | ------ | --------------------- |
| id          | string | Unique ID             |
| channel\_id | string | Channel ID            |
| user\_id    | string | Chat user's unique ID |
| created\_at | string | Creation date         |

#### **Import channel subscription list**

Use the following code to import the subscription data of a specific channel in the form of a list.

```csharp
GameChat.getSubscriptions(CHANNEL_ID, OFFSET, LIMIT, (List<Subscription> Subscriptions, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error handling
        return;
    }

    foreach(Subscription elem in Subscriptions)
    {
        //handling each subscription instance
    }
}));
```

### Channel <a href="#undefined" id="undefined"></a>

#### **Channel Data Class (per Unit)**

```csharp
public class Channel
{
    public string id;
    public string project_id;
    public string unique_id;
    public string name;
    public string user_id;
    public string created_at;
    public string updated_at;
}
```

| ID          | type   | desc                                                 |
| ----------- | ------ | ---------------------------------------------------- |
| id          | string | Channel ID (unique)                                  |
| project\_id | string | Project ID                                           |
| unique\_id  | string | Channel ID that can be set by the developer (unique) |
| name        | string | Channel name                                         |
| user\_id    | string | Chat user ID (who created the channel)               |
| created\_at | string | Creation date                                        |
| updated\_at | string | Renewal date                                         |

#### **Import channel list**

Use the following code to import the channel data of a project in the form of a list.

```csharp
GameChat.getChannels(OFFSET, LIMIT, (List<Channel> Channels, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error handling
        return;
    }

    foreach(Channel elem in Channels)
    {
        //handling each channelInfo instance
    }
});
```

| ID     | type | desc                                                                          |
| ------ | ---- | ----------------------------------------------------------------------------- |
| OFFSET | int  | Start location of the channel to import from the list of all channels (index) |
| LIMIT  | int  | Number of channels to import                                                  |

#### **Import channel data**

Use the following code to import channel data using the channel ID and unique ID.

```csharp
//Put null in the CHANNEL_UNIQUE_ID parameter if you want to search only by CHANNEL_ID.

//If both the CHANNEL_ID and CHANNEL_UNIQUE_ID values exist, then it searches by prioritizing the CHANNEL_UNIQUE_ID value.

GameChat.getChannel(CHANNEL_ID, CHANNEL_UNIQUE_ID,  (Channel Channel, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error handling
        return;
    }

    //handling channelInfo instance
});
```

```csharp
GameChat.getChannel(CHANNEL_UNIQUE_ID, (Channel Channel, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error handling
        return;
    }

    //handling channelInfo instance
});
```

| ID                  | type   | desc                                          |
| ------------------- | ------ | --------------------------------------------- |
| CHANNEL\_ID         | string | Channel ID (auto-generated)                   |
| CHANNEL\_UNIQUE\_ID | string | (Unique) channel ID (customization available) |

### Create and delete channel <a href="#undefined" id="undefined"></a>

You must use an open API to create or delete a new channel within a project.\
Due to security concerns, we recommend that you use an open API to create and update channels directly from Server to Server. For more information, see the [Game Chat API Guide](https://api.ncloud-docs.com/docs/en/game-gamechat).

### Messenger <a href="#undefined" id="undefined"></a>

#### **(Received) Message Data Class (per Unit)**

```csharp
public class Message
{
    public class User
    {
        public string id;
        public string name;
        public string profile;
    }

    public string message_id;
    public string channel_id;
    public string message_type;
    public string content;

    public string[] mentions;
    public bool mentions_everyone;
    public User sender;
    public string created_at;
}
```

| ID            | type   | desc                             |
| ------------- | ------ | -------------------------------- |
| message\_id   | string | Message’s unique ID              |
| channel\_id   | string | Channel ID                       |
| message\_type | string | Message type                     |
| content       | string | Content of message (JSON string) |
| mentions      | string | Mention (tag)                    |
| created\_at   |        | string                           |

#### **Import message list**

Use the following code to import the message data of a specific channel in the form of a list.

```csharp
GameChat.getMessages(CHANNEL_ID, OFFSET, LIMIT, SEARCH, QUERY, SORT, (List<Message> Messages, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error handling
        return;
    }

    foreach(Message elem in Messages)
    {
        //handling each message instance
    }
});
```

<table><thead><tr><th width="181">ID</th><th width="119">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>Channel ID</td></tr><tr><td>OFFSET</td><td>string</td><td>Start location of the message to import from the list of all messages</td></tr><tr><td>LIMIT</td><td>string</td><td>Number of messages to import</td></tr><tr><td>SEARCH</td><td>string</td><td>Message search criterion key. E.g., content.text<br>Perform a full scan when sending empty strings</td></tr><tr><td>QUERY</td><td>string</td><td>Message search value. Only complete matches can be searched. Perform a full scan when sending empty strings</td></tr><tr><td>SORT</td><td>string</td><td>Message sorting order (default: descending order - most recent comes first) (optional: ascending order)</td></tr></tbody></table>

#### **Translate messages**

If the automatic translation feature is activated, then arbitrary text can be translated into the specified language. The automatic translation feature can be used after integrating with the [Papago Translation](https://www.ncloud.com/product/aiService/papagoTranslation) service.

**(Received) Translation Data Class (per Unit)**

```csharp
public class Translation
{
    public string detectLang = "";
    public string lang = "";
    public bool translated = false;
    public string message = "";
}
```

<table><thead><tr><th width="163">ID</th><th width="126">type</th><th>desc</th></tr></thead><tbody><tr><td>detectLang</td><td>string</td><td>Source language code</td></tr><tr><td>lang</td><td>string</td><td>Target language code</td></tr><tr><td>translated</td><td>bool</td><td>Success or failure of translation</td></tr><tr><td>message</td><td>string</td><td>Content of result message (JSON string)</td></tr></tbody></table>

> Note
>
> For more information on source language codes and target language codes, see the [Papago Text Translation API Guide](https://api.ncloud-docs.com/docs/en/ai-naver-papagonmt-translation).

```csharp
GameChat.translateMessage(CHANNEL_ID, SORCE_LANG, TARTGET_LANG, TEXT, (List<Translation> Translations, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error handling
        return;
    }

    foreach(Translation elem in Translations)
    {
        //handling each Translation instance
    }
});

GameChat.translateMessage(SORCE_LANG, TARTGET_LANG, TEXT, (List<Translation> Translations, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error handling
        return;
    }

    foreach(Translation elem in Translations)
    {
        //handling each Translation instance
    }
});
```

<table><thead><tr><th width="195">ID</th><th width="118">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>Channel ID</td></tr><tr><td>SORCE_LANG</td><td>string</td><td>Language name of the text to send ("auto": detected automatically)<br>See the <a href="https://api.ncloud-docs.com/docs/en/ai-naver-papagonmt-translation">API Guide</a></td></tr><tr><td>TARTGET_LANG</td><td>string</td><td>Language code of the text (to receive the translation)<br>(Multiple entries allowed with "," E.g., "en, fr, th")<br>See the <a href="https://api.ncloud-docs.com/docs/en/ai-naver-papagonmt-translation">Papago Text Translation API Guide</a></td></tr><tr><td>TEXT</td><td>string</td><td>Text to send</td></tr></tbody></table>

### Chat user

**(Received) Member Data Class (per Unit)**

```csharp
public class Member
{
    public string id = "";
    public string project_id = "";
    public string nickname = "";
    public string profile_url = "";
    public string country = "";
    public string remoteip = "";
    public string adid = "";
    public string device = "";
    public string network = "";
    public string version = "";
    public string model = "";
    public string logined_at = "";
    public string created_at = "";
    public string updated_at = "";
}
```

<table><thead><tr><th width="152">ID</th><th width="124">type</th><th>desc</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>Chat user's unique ID</td></tr><tr><td>project_id</td><td>string</td><td>Game Chat project ID that logged in</td></tr><tr><td>nickname</td><td>string</td><td>Chat user's nickname</td></tr><tr><td>profile_url</td><td>string</td><td>Profile image URL</td></tr><tr><td>country</td><td>string</td><td>Country connected</td></tr><tr><td>remoteip</td><td>string</td><td>Connection IP</td></tr><tr><td>adid</td><td>string</td><td>Advertisement identifier</td></tr><tr><td>device</td><td>string</td><td>Connected device's environment</td></tr><tr><td>network</td><td>string</td><td>Connected network's type (Cellular, Wi-Fi)</td></tr><tr><td>version</td><td>string</td><td>Version of the app connected</td></tr><tr><td>model</td><td>string</td><td>Connected device's model</td></tr><tr><td>logined_at</td><td>string</td><td>Login date</td></tr><tr><td>created_at</td><td>string</td><td>Chat user creation date</td></tr><tr><td>updated_at</td><td>string</td><td>Chat user information renewed date</td></tr></tbody></table>

#### **Chat user information update**

You can update the user information of a chat server.

```csharp

// Chat user nickname update
// The strings allowed for nicknames are 2 to 128 characters in length, excluding whitespaces (spaces, tabs, and line breaks).
GameChat.setName(MEMBER_ID, NAME, (Member member, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error handling
        return;
    }
    //handling updated Member instance
});

//Chat user profile image URL update
GameChat.setProfileUrl(MEMBER_ID, PROFILE_URL, (Member member, GameChatException Exception) => {

    if(Exception != null)
    {
        // Error handling
        return;
    }
    //handling updated Member instance
});

```

| ID         | type   | desc                         |
| ---------- | ------ | ---------------------------- |
| MEMBER\_ID | string | Chat user's unique ID        |
| NAME       | string | Chat user's nickname or name |
| PROFILE    | string | Profile image URL            |

## GameChatExtension (Emoji, HyperLink)

This helper class facilitates easy handling of emojis and hyperlink text included in the received message.

* Since TMP\_GameChatTextUGUI is an extension class of TextMeshPro, a built-in asset of Unity, you must use first use Package Manager to install TextMeshPro.
* The TextMeshPro asset is included as a built-in asset from Unity 2018.2 or later.
* The default output of emoji sprite sheets is available from Emoji v13.0 (Android). You can change and customize the sprite sheet.

```csharp
namespace GameChatUnity.Extension
{
    public class TMP_GameChatTextUGUI : TextMeshProUGUI
    {
        public bool isHyperLinked { get; set; }    // Whether to process link-type addresses as hyperlinks (append html tag)
        public string LinkTextColor { get; set; }  // hyperlink text color
    }
}
```

**\<Example>**

```csharp
using GameChatUnity.Extension;

TMP_GameChatTextUGUI message = msgObject.GetComponent<TMP_GameChatTextUGUI>();

//Insert text through setMessage for hyperlink recognition and processing.
message.setMessage(MESSAGE_CONTENT);
message.color = Color.green;
message.isHyperLinked = true;

...

msgObject = Instantiate(msgObject) as GameObject;

...

// Manually implement the click event listener for hyperlinks.

//Handling with TMP_LinkInfo
TMP_LinkInfo linkInfoArr = message.textInfo.linkInfo[LINK_INDEX];

...
```


# OpenAPI

Calling certain Game Chat functions via a prescribed API

> Note
>
> You must use an allowed API key issued via the dashboard to make an API call.

## Checking the API key

An API key can be generated via **Dashboard > Settings > Project settings > API key**.

> Caution
>
> Click the **\[Reissue]** button to reissue a key. Note that a new key will render the old key useless.

## Using open API

### Base URL <a href="#baseurl" id="baseurl"></a>

```curl
https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}
- Use project ID of Game Chat for {projectId}
```

<table><thead><tr><th width="162">Region</th><th>URL</th></tr></thead><tbody><tr><td>kr</td><td>https://dashboard-api.gamechat.naverncp.com/v1</td></tr><tr><td>sg</td><td>https://sg-dashboard-api.gamechat.naverncp.com/v1</td></tr><tr><td>jp</td><td>https://jp-dashboard-api.gamechat.naverncp.com/v1</td></tr></tbody></table>

### Common error codesCommon error codes

The following are common error codes that can occur when making requests to the API:

<table><thead><tr><th width="165">Code</th><th>Description</th></tr></thead><tbody><tr><td>-1</td><td>Using a key not on the dashboard</td></tr><tr><td>-2</td><td>Discrepancy between dashboard key and header key</td></tr><tr><td>-3</td><td>Using a key that was deleted on the dashboard</td></tr><tr><td>-4</td><td>Using a key that was treated as unused on the dashboard</td></tr><tr><td>-5</td><td>Expired key</td></tr><tr><td>-6</td><td>No project ID</td></tr></tbody></table>


# Channel creation API

Create a channel.

## **Request**

* Method : POST
* URI : /channel

```
POST
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel
Header : 'x-api-key: {API Key}'
Header : 'content-type: application/json'
data: '{
    "name":"#All"
}'
```

<table><thead><tr><th width="139">Header</th><th width="113">Type</th><th width="136">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>Dashboard > Settings > Project settings > API Key</td></tr></tbody></table>

<table><thead><tr><th width="141">Attribute</th><th width="112">Type</th><th width="138">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>Project ID (Dashboard > Settings > Project settings > Project ID)</td></tr><tr><td>name</td><td>String</td><td>O</td><td>Channel name</td></tr><tr><td>translation</td><td>Boolean</td><td>X</td><td>Translation availability</td></tr><tr><td>uniqueId</td><td>String</td><td>X</td><td>Unique ID that can be arbitrarily specified</td></tr></tbody></table>

## **Response**

```javascript
{
    "status": 1,
    "result": "1a51af0d-f464-4440-8ad6-ce69e0bdaba8"
}
```

<table><thead><tr><th width="168">Attribute</th><th width="129">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>Result (1: Successful. Refer to the error code for failures.)</td></tr><tr><td>result</td><td>String</td><td>Created channel ID</td></tr></tbody></table>

## **Error code**

<table><thead><tr><th width="224">Code</th><th>Description</th></tr></thead><tbody><tr><td>-100</td><td>When the required parameter doesn't exist</td></tr></tbody></table>


# Channel edit

Editing channel details

## Requests <a href="#undefined" id="undefined"></a>

* Method : PUT
* URI : /channel

```
PUT
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel
Header : 'x-api-key: {API Key}'
Header : 'content-type: application/json'
data: '{
    "name":"#All",
}'
```

Plain textCopy

<table><thead><tr><th width="154">Header</th><th width="124">Type</th><th width="120">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>Dashboard > Settings > Project settings > API key</td></tr></tbody></table>

<table><thead><tr><th width="154">Attribute</th><th width="126">Type</th><th width="117">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>Project ID (Dashboard > Settings > Project settings > Project ID)</td></tr><tr><td>name</td><td>String</td><td>O</td><td>Channel name</td></tr><tr><td>translation</td><td>Boolean</td><td>X</td><td>Translation availability</td></tr><tr><td>uniqueId</td><td>String</td><td>X</td><td>Unique ID that can be assigned arbitrarily</td></tr><tr><td>limit</td><td>Int</td><td>X</td><td>Maximum number of participants in channel (unlimited if set to 0)</td></tr></tbody></table>

## Responses <a href="#undefined" id="undefined"></a>

```javascript
{
    "status": 1,
    "result": "1a51af0d-f464-4440-8ad6-ce69e0bdaba8"
}
```

JavaScriptCopy

<table><thead><tr><th width="160">Attribute</th><th width="123">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>Result value (1: Success. See Error Code for failure)</td></tr><tr><td>result</td><td>String</td><td>Modified channel ID</td></tr></tbody></table>

## Errors <a href="#undefined" id="undefined"></a>

<table><thead><tr><th width="237">Code</th><th>Description</th></tr></thead><tbody><tr><td>-100</td><td>Missing required parameter(s)</td></tr></tbody></table>


# Channel deletion API

Delete a channel.

## **Request**

* Method : DELETE
* URI : /channel/{channelId}

```
DELETE
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel/{channelId}
Header : 'x-api-key: {API Key}'
```

Plain textCopy

<table><thead><tr><th width="139">Header</th><th width="115">Type</th><th width="120">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>Dashboard > Settings > Project settings > API Key</td></tr></tbody></table>

<table><thead><tr><th width="141">Attribute</th><th width="116">Type</th><th width="119">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>Project ID (Dashboard > Settings > Project settings > Project ID)</td></tr><tr><td>channelId</td><td>String</td><td>O</td><td>Channel ID</td></tr></tbody></table>

**Response**

Success

```javascript
{
    "status": 1,
    "message": "success"
}
```

JavaScriptCopy

<table><thead><tr><th width="195">Attribute</th><th width="139">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>Result (1: Successful. Refer to the error code for failures.)</td></tr><tr><td>message</td><td>String</td><td>Result message</td></tr></tbody></table>

<br>


# Game Chat resource management

Checking the resource information for the Game Chat service.

Check the resource information of the Game Chat (Deprecated) service. Every activity a user can perform in the Game Chat (Deprecated) service is mapped to a resource type defined in Resource Manager and history of operations (actions) by resource type. Based on the mapped values, the actual activity history performed by users is collected by Cloud Activity Tracer, which can be utilized by the admin to monitor users' activities or create audit reports. Resource types are also used as the basis for user-specific permissions in Sub Account.\
The following is a description of the resources and the task history by resource type.

* Resource
  * The main unit of information managed by each service
  * Objects that users can create, change, and delete
  * Values unique to each NAVER Cloud Platform service
* Task history (actions) by resource type
  * History of actions performed by users through the console and APIs
  * Actions of creating, changing, or deleting resources

The resource types for the Game Chat (Deprecated) service and the task history information for each resource type are as follows.

| Service name (product code)      | Resource type | Task history by resource type |
| -------------------------------- | ------------- | ----------------------------- |
| Game Chat (Deprecated)(GameChat) | Project       | Change Account                |
|                                  |               | Change License                |
|                                  |               | Change Project Name           |
|                                  |               | Create Project                |
|                                  |               | Delete Project                |
|                                  |               | Initialize Password           |
|                                  |               | Initialized                   |
|                                  |               | Request initialization        |

Note

* Resource Manager: It is a service provided by NAVER Cloud Platform for free. For more details about the usage method, see the [Resource Manager User Guide](https://guide.ncloud-docs.com/docs/en/resourcemanager-overview).
* Cloud Activity Tracer: It is a service provided by NAVER Cloud Platform for free. For more details about the usage method, see the [Cloud Activity Tracer User Guide](https://guide.ncloud-docs.com/docs/en/cat-overview).
* Sub Account: It is a service provided by NAVER Cloud Platform for free. Although you design permissions based on the resource types defined by the Resource Manager service, the resource type groups and resource type-specific actions are different from the group and action values defined by the Resource Manager service because they are configured by the Sub Account service on its own.


# Game Chat release notes

These are the release notes for the Game Chat guide. The details are as follows.

| Release date | Release item        | Release details                                                    |
| ------------ | ------------------- | ------------------------------------------------------------------ |
| 02.16.2022   | Guide amended       | <p>- Content structure is improved<br>- Style guide is applied</p> |
| 2022.07.21.  | Project name change | - Project name change feature                                      |


# Game Chat(日本語)

Game Chatは、ゲームにリアルタイムチャットやメッセージシステム、複数のユーザーが会話できるチャネルを実装できるサービスです。簡単かつ手軽にゲーム内チャットサービスを構築できるように、様々なSDKやAPIを提供します。

### Game Chatが提供する様々な機能 <a href="#gamechat" id="gamechat"></a>

* 便利なダッシュボード\
  モバイルからでもアクセス可能なGame Chatダッシュボード画面で、メッセージの統計、チャットチャネル(ギルド)の管理、悪性ユーザーの遮断、暴言や不適切な言葉のフィルタリング、チャットメッセージのダウンロードや検索が行えます。
* 1：1チャット\
  特定のユーザーに通知メッセージを伝達できます。ユーザー間の1：1チャットシステムを安定的にサポートします。
* 多言語メッセージのリアルタイム自動翻訳

  様々な国々の人々と容易に会話できるように、NAVERの強力なAI翻訳ソリューションのPapagoとの連携機能を提供します。自動翻訳機能を用いると、グローバルユーザーと手軽にコミュニティを構築できます。
* 不適切な言葉の遮断と悪性ユーザーの遮断

  健全なチャット環境の構成のため、暴言や不適切な言葉が含まれたメッセージをフィルタリングしたり、削除することができます。また、悪性ユーザー(プレイヤー)の場合、一定期間チャットを利用できないように設定できます。
* リアルタイム分析指標

  ユーザーのアクセス状況、メッセージの伝達状況などを分析できるように様々な分析指標を提供します。

### Game Chatご利用ガイドの案内 <a href="#gamechat" id="gamechat"></a>

Game Chatご利用ガイドは、効果的にGame Chatを利用できるように、以下のようなテーマで構成されています。各テーマで読者が確認できる内容は以下のとおりです。

* Game Chatの概要：Game Chatの紹介と機能の案内、関連リソースの案内
* Game Chatを使用する前に：Game Chat使用の前にあらかじめ準備しておくべき事項の案内
* Game Chatを開始する：Game Chatサービス利用申込方法の案内
* Game Chatを使用する：Game Chatユーザーが利用可能な機能についての使用方法の案内
  * Game Chatの運用と管理：ダッシュボードへのアクセス方法とダッシュボードの使用方法の案内
  * Game ChatのUnity SDK：Unity用のGame Chat SDKを使用する方法の案内

<br>


# Game Chat を使用する前に

Game Chatの円滑な利用のためにサービスのスペックや準備事項、料金情報を説明します。

## サービスのスペック

Game Chatで提供するSDKは、以下の環境で使用できます。

<table><thead><tr><th width="220">開発環境</th><th>システム要件</th></tr></thead><tbody><tr><td>Unity</td><td>Unity 2018.4.0以上</td></tr></tbody></table>

## 利用料金

プロジェクト作成時に無料プロジェクトとして作成され、有料に切り替える際に費用が発生します。

<table><thead><tr><th width="125">タイプ</th><th width="153">課金区間</th><th width="91">課金基準</th><th width="92">料金</th><th width="257">備考</th></tr></thead><tbody><tr><td>無料</td><td>200 CCU 以下</td><td>日</td><td>無料</td><td>有料に切り替え時に課金開始<br>ネットワーク使用量100GB含む</td></tr><tr><td>有料基本料</td><td>2,000 CCU 以下</td><td>日</td><td>7,333 KRW</td><td>ネットワーク転送量2TB含む</td></tr></tbody></table>

* Game Chat サービスは開発無料区間として200 CCUが提供されます。&#x20;
* CCUは、チャットチャンネルに同時に接続されたアクティブユーザーの数で集計される同時接続ユーザーを指します。

## 追加料金

<table><thead><tr><th width="205">タイプ</th><th width="241">課金区間</th><th width="90">課金基準</th><th width="103">料金</th><th width="100">備考</th></tr></thead><tbody><tr><td>追加CCU</td><td>2,000超過 ～ 10,000以下</td><td>CCU</td><td>150 KRW</td><td></td></tr><tr><td>追加CCU</td><td>10,000超過</td><td>CCU</td><td>100 KRW</td><td></td></tr><tr><td>追加ネットワーク使用量</td><td>2TB超過</td><td>GB</td><td>100 KRW</td><td></td></tr></tbody></table>

* 基本料金区間でCCUが超過した場合、追加料金が課金されます。
* 料金の例\
  \- 11月1日から11月30日までの期間に2,500 CCUを使用した顧客（500 CCU超過）\
  \- （7,333 KRW \* 30日） + （500 CCU \* 150 KRW） = 219,990 KRW + 75,000 KRW = 294,990 KRW


# Game Chat を開始する

Game Chat の利用申請およびプロジェクトの作成方法、プロジェクト管理方法について説明します。

## Game Chat サービスの申し込みおよびプロジェクトの作成

Game Chat サービスの申し込みおよびプロジェクトの作成には、<cs@nbase.io> のメールアドレスに使用したいプロジェクト名を記載して申請してください。

### プロジェクトの管理

プロジェクト名の変更、管理者アカウントのパスワードリセット、プロジェクトの削除などについては、<cs@nbase.io> のメールアドレスを通じてご依頼ください。

> 注意
>
> プロジェクトを削除すると、プロジェクトの保有データがすべて削除されますのでご注意ください。

## 有料プランへの切替

プロジェクトを作成すると、1日最大200CCUを使用できる無料開発用プロジェクトとして作成されます。200CCU以上使用するには、有料に切り替える必要があります。 プロジェクトを有料に切り替える方法は、以下のとおりです。

1. Game Chat 管理ページ（ダッシュボード）にログインしてください。
2. 管理ページ下部に表示された \[有料に切替] ボタンをクリックします。&#x20;
3. 通知画面を確認して \[確認] ボタンをクリックします。

> 注意
>
> 無料環境から有料環境に切り替えてからは、再度無料環境には戻れませんのでご注意ください。


# Game Chat の運用と管理

Game Chat の運用と管理Game Chatダッシュボードでチャットを運用・管理する方法やチャット関連の統計を確認する方法説明します。

## ダッシュボードのメニュー

ダッシュボードでは、アクセス状況、メッセージ、統計などチャットの運用状況を一目で把握できます。日付を選択してグラフを確認できます。

ダッシュボードのメニューは以下のとおりです。

<figure><img src="/files/ucBD9rf2k2yU2mJG9p8Y" alt=""><figcaption></figcaption></figure>

<table><thead><tr><th width="111">番号</th><th width="150">メニュー</th><th>説明</th></tr></thead><tbody><tr><td>1</td><td>ダッシュボード</td><td>アクセス者統計の確認</td></tr><tr><td>2</td><td>会員</td><td>会員の確認と利用停止会員の管理</td></tr><tr><td>3</td><td>チャット</td><td>チャットチャネルの追加とチャネルの管理</td></tr><tr><td>4</td><td>検索</td><td>会員の検索</td></tr><tr><td>5</td><td>設定</td><td>プロジェクトの設定とダッシュボードユーザーの設定、Unity SDKのダウンロード</td></tr><tr><td>6</td><td>作業の管理</td><td>検索メニューでデータをエクスポートした履歴の確認</td></tr><tr><td>7</td><td>DOCS</td><td>- Unity：Game Chat Unityご利用ガイドに移動</td></tr><tr><td>8</td><td>言語の設定</td><td>ダッシュボード言語を変更できる。韓国語、英語を提供</td></tr><tr><td>9</td><td>会員情報</td><td>会員情報の修正とログアウト</td></tr></tbody></table>

## 会員 <a href="#hui-yuan" id="hui-yuan"></a>

会員メニューでは、ダッシュボードに登録された会員(ゲームプレイヤー)情報を確認したり、特定の会員のチャット利用を停止したり、すべてのチャットから退会させることができます。

### 会員情報の確認

Game Chatダッシュボードに登録されている会員の情報を確認する方法は、以下のとおりです。

1. Game Chatダッシュボードで会員 > リストメニューをクリックします。&#x20;
2. 会員の詳細情報を確認するには、ユーザーIDをクリックします。&#x20;
3. 画面右側で詳細情報を確認します。&#x20;
   * ユーザーの名前、プロフィールURL、アクセスした国、ID、モデル、デバイスID、登録日、最終ログイン日などが確認できる

<figure><img src="/files/tN6oBTVMYfj9teX1FAEY" alt=""><figcaption></figcaption></figure>

4. 会員情報を修正するには、名前またはプロフィールURLを修正し、\*\*\[保存]\*\*ボタンをクリックします。
   * 名前、プロフィール画像URLのみ修正できる

### 会員の退会 <a href="#undefined" id="undefined"></a>

特定の会員を退会させる方法は以下のとおりです。

1. Game Chatダッシュボードで**会員** > **リスト**メニューをクリックします。
2. 退会させる会員IDをクリックします。
3. 画面右側に会員の詳細情報が表示されたら、**\[退会]** ボタンをクリックします。
4. ポップアップの確認画面が表示されたら、**\[はい]** ボタンをクリックします。

### 会員の検索 <a href="#undefined" id="undefined"></a>

Game Chatダッシュボードに登録されている会員を検索する方法は、以下のとおりです。

1. Game Chatダッシュボードで**会員** > **リスト**メニューをクリックします。
2. 検索の条件を設定し、**\[検索]** ボタンをクリックします。
   * ユーザーID作成日、ユーザーID、ハンドルネーム、国、IPを条件にして検索できる
3. 検索結果を確認します。

### 会員の利用停止 <a href="#undefined" id="undefined"></a>

特定の会員が一定期間チャットを使用できないように設定できます。利用停止メニューでは、利用停止中の会員を確認したり、検索することができます。\
特定の会員のチャット利用を停止する方法は、以下のとおりです。

1. Game Chatダッシュボードで**会員** > **利用停止**メニューをクリックします。
2. 画面右側にある **\[追加]** ボタンをクリックします。
3. 利用停止の登録画面が表示されたら、**\[状態]** アイコンをクリックして有効状態に変更します。
4. 利用停止したい会員をすべてのチャネルからも追放するには、**チャットから追放する** チェックボックスをクリックします。
5. ユーザーID、利用停止の理由、利用停止期間を設定して **\[保存]** ボタンをクリックします。

## チャット <a href="#undefined" id="undefined"></a>

チャットメニューでは、チャネルを確認してチャットメッセージを転送することができます。

### チャットチャネルの追加 <a href="#undefined" id="undefined"></a>

新しいチャットチャネルを追加する方法は、以下のとおりです。

1. Game Chatダッシュボードで**チャネル**メニューをクリックします。
2. **\[チャネルを追加]** ボタンをクリックします。
3. チャネルの追加画面が表示されたら、チャネルと固有IDを入力して **\[登録]** ボタンをクリックします。
   * 固有IDを入力すると、SDKでその値を用いてチャネルにアクセスできる
4. チャネルが作成されたか確認します。

### チャットチャネルの設定 <a href="#undefined" id="undefined"></a>

特定のチャットチャネルに参加中のユーザーを確認したり、チャネル情報を修正または削除する方法は、以下のとおりです。

1. Game Chatダッシュボードで **チャネル** メニューをクリックします。
2. チャネルを選択し、チャネル画面右上にある:アイコンをクリックします。
3. コンテキストメニューが表示されたら、希望する作業を選択します。

<figure><img src="/files/AjhBZltc245bvwKZbfho" alt=""><figcaption></figcaption></figure>

* チャットチャネルに参加したユーザーリストを確認するには、**\[参加リスト]** メニューをクリックします。
* チャットチャネル情報を修正するには、**\[チャネルの修正]** メニューをクリックします。
* チャットチャネルを削除するには、**\[削除]** メニューをクリックします。

## 検索

検索メニューでは、プロジェクトのすべてのチャネルでやり取りしたメッセージを確認・検索することができます。ID、ハンドルネーム、メッセージ、チャネルID、メッセージ送信日時により検索できます。また、メッセージリストをCSVファイルでダウンロードすることもできます。<br>

<figure><img src="/files/oK6wj1yy8ZOoveQdgk0z" alt=""><figcaption></figcaption></figure>

### メッセージの検索とメッセージの詳細情報の確認 <a href="#undefined" id="undefined"></a>

メッセージの詳細情報(メッセージが作成されたチャネルID、メッセージID、メッセージ、メッセージ送信時刻)を確認する方法は、以下のとおりです。

1. Game Chatダッシュボードで **検索**メニューをクリックします。
2. 検索の条件を設定し、**\[検索]** ボタンをクリックします。
   * メッセージ送信日、会員ID、チャネルID、ハンドルネーム、メッセージを条件にして検索できる
3. 詳細情報を確認するメッセージの見るアイコンをクリックします。
4. そのメッセージが登録されたチャネルID、メッセージID、メッセージ、メッセージ送信時刻を確認できます。

### メッセージの削除 <a href="#undefined" id="undefined"></a>

特定のメッセージを検索して削除することができます。検索メニューで削除したメッセージは、そのチャットチャネルからも削除されます。

1. Game Chatダッシュボードで **検索**メニューをクリックします。
2. 削除するメッセージの削除アイコンをクリックします。
3. 削除の確認画面が表示されたら、**\[はい]** ボタンをクリックします。

## 設定 <a href="#undefined" id="undefined"></a>

設定メニューでは、Game Chatプロジェクト情報を設定したり、チャット禁止語やメッセージを自動翻訳するかどうかを設定することができます。また、ユーザー情報を変更したり、特定のユーザーに管理者権限を付与することもできます。

### プロジェクトの設定 <a href="#undefined" id="undefined"></a>

プロジェクト情報の確認と修正、禁止語の設定、チャットの自動翻訳機能の使い方を説明します。

#### **プロジェクト情報の確認**

NAVERクラウドID、プロジェクトID、API Key、プロジェクト名、メッセージの長さ制限を確認したり、プロジェクト名、メッセージの長さ制限、禁止語を設定することができます。\
プロジェクト情報を確認する方法は以下のとおりです。

1. Game Chatダッシュボードで**設定** > **プロジェクトの設定**メニューをクリックします。
2. プロジェクト情報を確認します。
   * プロジェクト名、メッセージの長さ制限のみ修正できる

#### **禁止語の設定**

チャットで使用できない文字(暴言や不適切な言葉など)を禁止語に設定することで健全なチャット環境を提供できます。\
禁止語を設定する方法は以下のとおりです。

1. Game Chatダッシュボードで**設定** > **プロジェクトの設定**メニューをクリックします。
2. 禁止語の制限タイプを選択します。
   * 制限なし：禁止語に指定した単語もそのまま表示
   * *に置換：禁止語に指定された単語はチャット画面に*と表示
   * メッセージ伝達を遮断：禁止語に指定された単語は転送しない
3. 禁止語の例を自動で持ってくるには、**\[基本禁止語を使用]** ボタンをクリックします。
4. **\[保存]** ボタンをクリックします。

#### **チャットメッセージの自動翻訳**

NAVERクラウドプラットフォームで提供するサービスのPapago Translationと連携し、チャットに入力されるメッセージを自動で翻訳できます。\
チャットメッセージを自動翻訳するように設定する方法は、以下のとおりです。

1. Game Chatダッシュボードで**設定** > **プロジェクトの設定**メニューをクリックします。
2. Papago領域の有効化アイコンをクリックします。
3. Client IDとClient Secretを入力して **\[保存]** ボタンをクリックします。

> 参考
>
> Papago Translation連携のためのClient IDとClient Secretを確認する方法は、[Applicationご利用ガイド](https://guide.ncloud-docs.com/docs/ja/naveropenapiv3-application)を参照してください。

### ユーザーの設定

プロジェクトのユーザーを確認してユーザー情報を修正することができます。ただし、現在アクセス中のアカウントの詳細情報は、会員情報の修正メニューで修正できます。\
ユーザー情報を修正する方法は以下のとおりです。

1. Game Chatダッシュボードで**設定** > **ユーザーの設定**メニューをクリックします。
2. ユーザー情報を修正するユーザーの![game-gamechatmgmt\_icon\_ja.png](https://cdn.document360.io/6998976f-9d95-4df8-b847-d375892b92c2/Images/Documentation/game-gamechatmgmt_icon_ja.png?sv=2022-11-02\&spr=https\&st=2024-08-13T08%3A08%3A19Z\&se=2024-08-13T08%3A18%3A19Z\&sr=c\&sp=r\&sig=3lowgW%2FFb0YcyeCEth5w1iX1qITr1dhlH7n4bSBAuss%3D) > **詳細を見る**メニューをクリックします。
3. ユーザー名、パスワード、ユーザーの状態を設定して **\[保存]** ボタンをクリックします。
4. 特定のユーザーをダッシュボードの管理者に設定するには、管理者権限アイコンを有効化状態に変更し、**\[保存]** ボタンをクリックします。
5. ユーザー情報を削除するには、**\[削除]** ボタンをクリックします。

### SDKのダウンロード <a href="#sdk" id="sdk"></a>

Unity SDKをダウンロードできます。

## 作業の管理

作業の管理メニューでは、検索メニューからCSVでエクスポートした結果を30日間ダウンロードできます。

## 会員情報の修正 <a href="#undefined" id="undefined"></a>

会員情報メニューでは、アカウント情報を修正してログアウトすることができます。

### マイ情報の修正 <a href="#undefined" id="undefined"></a>

ログインしたアカウントの情報を確認し、名前とプロフィールURL、ダッシュボードの時間帯を変更することができます。プロフィールURLはチャットの際に用いられます。\
マイ情報を修正する方法は以下のとおりです。

1. Game Chatダッシュボード右上のユーザーアイコンをクリックし、会員情報の修正メニューをクリックします。
2. マイ情報の修正メニューで名前またはプロフィールURL、時間帯を設定して **\[保存]** ボタンをクリックします。

### パスワードの変更 <a href="#undefined" id="undefined"></a>

パスワードを変更する方法は以下のとおりです。

1. Game Chatダッシュボード右上のユーザーアイコンをクリックし、**会員情報の修正**メニューをクリックします。
2. パスワードの変更メニューをクリックし、現在のパスワードと変更後のパスワードを入力して **\[保存]** ボタンをクリックします。

## ダッシュボードからのログアウト <a href="#undefined" id="undefined"></a>

Game Chatダッシュボードからログアウトするには、Game Chatダッシュボード右上のユーザーアイコンをクリックし、**ログアウト**メニューをクリックします。\ <br>


# Unity SDK

Game Chat Unity SDKの使い方について説明します。

## システム要件 <a href="#undefined" id="undefined"></a>

Game Chat Unity SDKを使用するためのシステム要件は、以下のとおりです。

* 最小スペック: 2018.4.0以上\
  (下位バージョンの Unityへの対応が必要な場合、<cs@nbase.io> までご連絡ください。)
* 2019.4.X / 2020.3.X / 2021.1.Xバージョンの Unityエディタのユーザーは、2019.4.29f1以上 / 2020.3.15f2以上 / 2021.1.16f1以上のバージョンを使用します(AABバージョンビルド時の Unityエディタのバグが変更されたバージョン)

## SDKのインストールと環境の構成 <a href="#sdk" id="sdk"></a>

Game Chat Unity SDKをダウンロードして、Unityでプロジェクトを構成する方法は以下のとおりです。

1. **設定** > **SDKのダウンロード**メニューを順にクリックし、**Unity SDKのダウンロード**をクリックします。
2. Unityプログラムを実行し、プロジェクトを作成します。
3. Unityで、**Assets** > **Import Package** > **Custom Package**...メニューを順にクリックします。
4. ダッシュボードでダウンロードした「GameChatUnitySDK\_xxxxxxxx」ファイルを読み込みます。
5. パッケージにあるすべてのファイルを選択し、 **\[Import]** ボタンをクリックします。
6. プロジェクトを保存します。

## 認証 <a href="#undefined" id="undefined"></a>

### Game Chatインスタンスの初期化 <a href="#gamechat" id="gamechat"></a>

Game Chatプロジェクト IDを用いて Game Chatインスタンスを初期化するには、以下のコードを使用します。

```csharp
GameChat.initialize(PROJECT_ID);

// シンガポールリージョンを使用する場合
GameChat.setRegion("sg");
GameChat.initialize(PROJECT_ID);
```

<table><thead><tr><th width="167">ID</th><th width="146">type</th><th>desc</th></tr></thead><tbody><tr><td>PROJECT_ID</td><td>string</td><td>プロジェクト ID</td></tr></tbody></table>

### Game Chatソケットサーバとの接続

Game Chatソケットサーバに接続する方法は以下のとおりです。

1. チャットユーザー IDを用いてGame Chatソケットサーバにアクセスします。
   * Game Chatプロジェクトでチャットユーザー IDは固有の値です。
2. APIを使用するためのトークンの値を取得します。
   * GameChat.connect以降に更新されたトークンの値を確認できます。
3. トークンの値を取得した後、現在アクセス中のデバイスに対するチャットユーザー情報が更新されたのか確認します。
   * GameChat.connectのコールバックで渡される Memberは、更新されたデータです。

Game Chatソケットサーバに接続するには、以下のコードを使用します。

```csharp
GameChat.connect(USER_ID,  (Member User, GameChatException Exception)=>
{

    if(Exception != null)
    {
        // エラー処理
        return;
    }
});
```

<table><thead><tr><th width="190">ID</th><th width="136">type</th><th>desc</th></tr></thead><tbody><tr><td>USER_ID</td><td>string</td><td>チャットユーザーの固有 ID</td></tr></tbody></table>

### Game Chatサーバとの接続解除 <a href="#gamechat" id="gamechat"></a>

Game Chatソケットサーバとの接続を解除するには、以下のコードを使用します。

```csharp
GameChat.disconnect();
```

### チャットユーザー情報のアップデート

connect成功後にチャットユーザー情報を保存してアップデートするには、以下のコードを使用します。

#### **ハンドルネームの変更**

```csharp
GameChat.setNickname(USER_ID, NickName, (member, exception) =>
{
    if (exception != null)
    {
        // エラー処理
        return;
    }

});
```

<table><thead><tr><th width="175">ID</th><th width="123">type</th><th>desc</th></tr></thead><tbody><tr><td>USER_ID</td><td>string</td><td>チャットユーザーの固有 ID</td></tr><tr><td>NickName</td><td>string</td><td>チャットユーザーのハンドルネーム</td></tr></tbody></table>

#### **Profile URLの変更**

```csharp
GameChat.setProfileUrl(USER_ID, ProfileUrl, (member, exception) =>
{
    if (exception != null)
    {
        // エラー処理
        return;
    }

});
```

<table><thead><tr><th width="187">ID</th><th width="159">type</th><th>desc</th></tr></thead><tbody><tr><td>USER_ID</td><td>string</td><td>チャットユーザーの固有 ID</td></tr><tr><td>ProfileUrl</td><td>string</td><td>チャットユーザーの ProfileURL</td></tr></tbody></table>

## チャンネルの購読と購読解除

特定のチャンネルに対して購読または購読解除を行うには、以下のコードを使用します。

```csharp
GameChat.subscribe(CHANNEL_ID);

GameChat.unsubscribe(CHANNEL_ID);
```

<table><thead><tr><th width="217">ID</th><th width="150">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>チャンネル ID</td></tr></tbody></table>

## メッセージの送信 <a href="#undefined" id="undefined"></a>

特定のチャンネルにメッセージを送信するには、以下のコードを使用します。

```csharp
GameChat.sendMessage(CHANNEL_ID, MESSAGE);
```

<table><thead><tr><th width="197">ID</th><th width="156">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>チャンネル ID</td></tr><tr><td>MESSAGE</td><td>string</td><td>送信メッセージテキスト</td></tr></tbody></table>

MESSAGEパラメータに@\[ユーザー ID]空白\[メッセージ内容]を入力時

```csharp
@user_idメッセージ本文
```

上記のケースでユーザー IDがログインした履歴がある場合、メッセージの詳細情報のうち、mentions情報はユーザー IDです。

## イベントの登録と解除

Game Chatソケットサーバから受信するイベントに対し、カスタムハンドラを登録または解除するには、以下のコードを使用します。

```csharp
GameChat.dispatcher.(EVENT_NAME) += (CALLBACK_FUNCTION);
```

```csharp
public delegate void onConnectedCallback(string data);
public onConnectedCallback onConnected;
//「connect」Eventに対する、コールバック

public delegate void onDisconnectedCallback(string reason);
public onDisconnectedCallback onDisconnected;
//「disconnect」Eventに対する、コールバック

public delegate void onMessageReceivedCallback(Message message);
public onMessageReceivedCallback onMessageReceived;
//「message」Eventに対する、コールバック

public delegate void onUserAddedCallback(UserInfo userinfo);
public onUserAddedCallback onUserAdded;
//「userAdded」Eventに対する、コールバック

public delegate void onUserRemovedCallback(Message message);
public onUserRemovedCallback onUserRemoved;
//「userRemoved」Eventに対する、コールバック

public delegate void onErrorReceivedCallback(string result, GameChatException exception);
public onErrorReceivedCallback onErrorReceived;
//「error」Eventに対する、コールバック
```

## 例外事項

Game Chat APIの使用中に発生する Exceptionに対する共通処理 Classは、以下のとおりです。

```csharp
public class GameChatException
{
    // Detail Error Code

    // 不明なエラー
    public static readonly int CODE_UNKNOWN_ERROR           = 0;
    // 初期化に失敗
    public static readonly int CODE_NOT_INITALIZE           = 1;
    // パラメータが正しくない場合
    public static readonly int CODE_INVAILD_PARAM           = 2;
    // ソケットサーバから発生したエラー
    public static readonly int CODE_SOCKET_SERVER_ERROR     = 500;
    //ソケットから発生したエラー
    public static readonly int CODE_SOCKET_ERROR = -501;
    // ネットワークコネクションエラーおよびタイムアウトが発生した場合
    public static readonly int CODE_SERVER_NETWORK_ERROR    = 4002;
    // サーバから取得したデータをパースする際のエラー
    public static readonly int CODE_SERVER_PARSING_ERROR    = 4003;

    // HTTPエラーの場合、当該ステータスコードがレスポンスコードとして伝達されます。 (400, 403 ...)

    // Error Code
    public int code { get; set; }
    // Error Message
    public string message { get; set; }
}
```

## Client API

### チャンネルの購読 <a href="#undefined" id="undefined"></a>

#### **Subscription Data Class (per Unit)**

```csharp
public class Subscription
{
    public string id;
    public string channel_id;
    public string user_id;
    public string created_at;
}
```

<table><thead><tr><th width="213">ID</th><th width="154">type</th><th>desc</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>固有 ID</td></tr><tr><td>channel_id</td><td>string</td><td>チャンネル ID</td></tr><tr><td>user_id</td><td>string</td><td>チャットユーザーの固有 ID</td></tr><tr><td>created_at</td><td>string</td><td>作成日時</td></tr></tbody></table>

#### **チャンネル購読リストを取得する**

特定のチャンネルの購読データをリスト形式で取得するには、以下のコードを使用します。

```csharp
GameChat.getSubscriptions(CHANNEL_ID, OFFSET, LIMIT, (List<Subscription> Subscriptions, GameChatException Exception) => {

    if(Exception != null)
    {
        // エラー処理
        return;
    }

    foreach(Subscription elem in Subscriptions)
    {
        //handling each subscription instance
    }
}));
```

### チャンネル

**Channel Data Class (per Unit)**

```csharp
public class Channel
{
    public string id;
    public string project_id;
    public string unique_id;
    public string name;
    public string user_id;
    public string created_at;
    public string updated_at;
}
```

<table><thead><tr><th width="202">ID</th><th width="128">type</th><th>desc</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>チャンネル ID(固有)</td></tr><tr><td>project_id</td><td>string</td><td>プロジェクト ID</td></tr><tr><td>unique_id</td><td>string</td><td>開発会社で設定できるチャンネル ID(固有)</td></tr><tr><td>name</td><td>string</td><td>チャンネル名</td></tr><tr><td>user_id</td><td>string</td><td>(チャンネルを作成した)チャットユーザー ID</td></tr><tr><td>created_at</td><td>string</td><td>作成日時</td></tr><tr><td>updated_at</td><td>string</td><td>更新日</td></tr></tbody></table>

#### **チャンネルリストを取得する**

プロジェクトのチャンネルデータをリスト形式で取得するには、以下のコードを使用します。

```csharp
GameChat.getChannels(OFFSET, LIMIT, (List<Channel> Channels, GameChatException Exception) => {

    if(Exception != null)
    {
        // エラー処理
        return;
    }

    foreach(Channel elem in Channels)
    {
        //handling each channelInfo instance
    }
});
```

<table><thead><tr><th width="195">ID</th><th width="133">type</th><th>desc</th></tr></thead><tbody><tr><td>OFFSET</td><td>int</td><td>全体チャンネルリストから取得するチャンネルの開始位置(index)</td></tr><tr><td>LIMIT</td><td>int</td><td>取得するチャンネル数</td></tr></tbody></table>

#### **チャンネルデータを取得する**

チャンネル IDや固有 IDを用いてチャンネルデータを取得するには、以下のコードを使用します。

```csharp
//CHANNEL_IDでのみ検索する場合、CHANNEL_UNIQUE_IDパラメータに nullを入れます。

//CHANNEL_IDと CHANNEL_UNIQUE_IDの値が同時に存在する場合、CHANNEL_UNIQUE_IDの値を優先的に検索します。

GameChat.getChannel(CHANNEL_ID, CHANNEL_UNIQUE_ID,  (Channel Channel, GameChatException Exception) => {

    if(Exception != null)
    {
        // エラー処理
        return;
    }

    //handling channelInfo instance
});
```

```csharp
GameChat.getChannel(CHANNEL_UNIQUE_ID, (Channel Channel, GameChatException Exception) => {

    if(Exception != null)
    {
        // エラー処理
        return;
    }

    //handling channelInfo instance
});
```

| ID                  | type   | desc                  |
| ------------------- | ------ | --------------------- |
| CHANNEL\_ID         | string | チャンネル ID(自動作成)        |
| CHANNEL\_UNIQUE\_ID | string | チャンネル(固有)ID(カスタマイズ可能) |

### チャンネルの作成と削除

プロジェクト内で新しいチャンネルを作成または削除するには、Open APIを活用します。\
セキュリティ問題のため、チャンネル作成やアップデートなどは、Open APIを活用して Server to Serverで直接行うことをお勧めします。 詳細は、[Game Chat APIガイド](https://api.ncloud-docs.com/docs/ja/game-gamechat)をご参照ください。

### メッセージ

**(Received) Message Data Class (per Unit)**

```csharp
public class Message
{
    public class User
    {
        public string id;
        public string name;
        public string profile;
    }

    public string message_id;
    public string channel_id;
    public string message_type;
    public string content;

    public string[] mentions;
    public bool mentions_everyone;
    public User sender;
    public string created_at;
}
```

<table><thead><tr><th width="200">ID</th><th width="160">type</th><th>desc</th></tr></thead><tbody><tr><td>message_id</td><td>string</td><td>メッセージの固有 ID</td></tr><tr><td>channel_id</td><td>string</td><td>チャンネル ID</td></tr><tr><td>message_type</td><td>string</td><td>メッセージタイプ</td></tr><tr><td>content</td><td>string</td><td>メッセージの内容(JSON文字列)</td></tr><tr><td>mentions</td><td>string</td><td>メンション(タグ)</td></tr><tr><td>created_at</td><td></td><td>string</td></tr></tbody></table>

#### **メッセージリストを取得する**

特定のチャンネルに対するメッセージデータをリスト形式で取得するには、以下のコードを使用します。

```csharp
GameChat.getMessages(CHANNEL_ID, OFFSET, LIMIT, SEARCH, QUERY, SORT, (List<Message> Messages, GameChatException Exception) => {

    if(Exception != null)
    {
        // エラー処理
        return;
    }

    foreach(Message elem in Messages)
    {
        //handling each message instance
    }
});
```

<table><thead><tr><th width="184">ID</th><th width="121">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>チャンネル ID</td></tr><tr><td>OFFSET</td><td>string</td><td>全体メッセージリストから取得するメッセージの開始位置</td></tr><tr><td>LIMIT</td><td>string</td><td>取得するメッセージ数</td></tr><tr><td>SEARCH</td><td>string</td><td>メッセージ検索基準キー。 &#x3C;例> content.text<br>空の文字列を伝達する場合、全体検索</td></tr><tr><td>QUERY</td><td>string</td><td>メッセージ検索の値。 完全一致のみ検索可能。 空の文字列を伝達する場合、全体検索</td></tr><tr><td>SORT</td><td>string</td><td>メッセージのソート順序(デフォルト: 降順 - 最新順) (オプション: 昇順)</td></tr></tbody></table>

#### **メッセージの翻訳**

自動翻訳機能が有効化されている場合、任意のテキストを指定した言語に翻訳できます。 自動翻訳機能は、[Papago Translation](https://www.ncloud.com/product/aiService/papagoTranslation)サービスと連携すると使用できます。

**(Received) Translation Data Class (per Unit)**

```csharp
public class Translation
{
    public string detectLang = "";
    public string lang = "";
    public bool translated = false;
    public string message = "";
}
```

<table><thead><tr><th width="167">ID</th><th width="138">type</th><th>desc</th></tr></thead><tbody><tr><td>detectLang</td><td>string</td><td>ソース言語コード</td></tr><tr><td>lang</td><td>string</td><td>ターゲット言語コード</td></tr><tr><td>translated</td><td>bool</td><td>翻訳の成否</td></tr><tr><td>message</td><td>string</td><td>結果メッセージの内容(JSON文字列)</td></tr></tbody></table>

#### 参考

ソース言語コードとターゲット言語コードについての説明は、[Papago Text Translation APIガイド](https://api.ncloud-docs.com/docs/ja/ai-naver-papagonmt-translation)をご参照ください。

```csharp
GameChat.translateMessage(CHANNEL_ID, SORCE_LANG, TARTGET_LANG, TEXT, (List<Translation> Translations, GameChatException Exception) => {

    if(Exception != null)
    {
        // エラー処理
        return;
    }

    foreach(Translation elem in Translations)
    {
        //handling each Translation instance
    }
});

GameChat.translateMessage(SORCE_LANG, TARTGET_LANG, TEXT, (List<Translation> Translations, GameChatException Exception) => {

    if(Exception != null)
    {
        // エラー処理
        return;
    }

    foreach(Translation elem in Translations)
    {
        //handling each Translation instance
    }
});
```

<table><thead><tr><th width="181">ID</th><th width="113">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>チャンネル ID</td></tr><tr><td>SORCE_LANG</td><td>string</td><td>(送信する)テキストの言語名(auto: 自動検出)<br><a href="https://api.ncloud-docs.com/docs/ja/ai-naver-papagonmt-translation">API Guide</a>を参考</td></tr><tr><td>TARTGET_LANG</td><td>string</td><td>(翻訳受信する)テキストの言語コード<br>(","で区切って、複数入力可能。 &#x3C;例> "en, fr, th")<br><a href="https://api.ncloud-docs.com/docs/ja/ai-naver-papagonmt-translation">Papago Text Translation APIガイド</a>を参考</td></tr><tr><td>TEXT</td><td>string</td><td>送信するテキスト</td></tr></tbody></table>

### チャットユーザー

**(Received) Member Data Class (per Unit)**

```csharp
public class Member
{
    public string id = "";
    public string project_id = "";
    public string nickname = "";
    public string profile_url = "";
    public string country = "";
    public string remoteip = "";
    public string adid = "";
    public string device = "";
    public string network = "";
    public string version = "";
    public string model = "";
    public string logined_at = "";
    public string created_at = "";
    public string updated_at = "";
}
```

<table><thead><tr><th width="162">ID</th><th width="111">type</th><th>desc</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>チャットユーザーの固有 ID</td></tr><tr><td>project_id</td><td>string</td><td>ログインした Game Chatプロジェクト ID</td></tr><tr><td>nickname</td><td>string</td><td>チャットユーザーのハンドルネーム</td></tr><tr><td>profile_url</td><td>string</td><td>プロフィール画像 URL</td></tr><tr><td>country</td><td>string</td><td>アクセスした国</td></tr><tr><td>remoteip</td><td>string</td><td>アクセス IPアドレス</td></tr><tr><td>adid</td><td>string</td><td>広告識別子</td></tr><tr><td>device</td><td>string</td><td>アクセスデバイスの環境</td></tr><tr><td>network</td><td>string</td><td>アクセスネットワークのタイプ (セルラー、Wi-Fi)</td></tr><tr><td>version</td><td>string</td><td>アクセスアプリのバージョン</td></tr><tr><td>model</td><td>string</td><td>アクセスデバイスのモデル</td></tr><tr><td>logined_at</td><td>string</td><td>ログインした日</td></tr><tr><td>created_at</td><td>string</td><td>チャットユーザーの作成日時</td></tr><tr><td>updated_at</td><td>string</td><td>チャットユーザー情報の更新日</td></tr></tbody></table>

#### **チャットユーザー情報のアップデート**

チャットサーバのユーザー情報をアップデートできます。

```csharp
// チャットユーザーのハンドルネームをアップデート
// ハンドルネームには、whitespace(spaces、tabs、line breaks)を除く2~128文字で入力できます。
GameChat.setName(MEMBER_ID, NAME, (Member member, GameChatException Exception) => {

    if(Exception != null)
    {
        // エラー処理
        return;
    }
    //handling updated Member instance
});

//チャットユーザーのプロフィール画像 URLをアップデート
GameChat.setProfileUrl(MEMBER_ID, PROFILE_URL, (Member member, GameChatException Exception) => {

    if(Exception != null)
    {
        // エラー処理
        return;
    }
    //handling updated Member instance
});
```

<table><thead><tr><th width="170">ID</th><th width="128">type</th><th>desc</th></tr></thead><tbody><tr><td>MEMBER_ID</td><td>string</td><td>チャットユーザーの固有 ID</td></tr><tr><td>NAME</td><td>string</td><td>チャットユーザーのハンドルネームまたは名前</td></tr><tr><td>PROFILE</td><td>string</td><td>プロフィール画像 URL</td></tr></tbody></table>

## GameChatExtension (Emoji, HyperLink) <a href="#gamechatextensionemojihyperlink" id="gamechatextensionemojihyperlink"></a>

受信メッセージに含まれた絵文字とハイパーリンクテキストを扱いやすいようにサポートするヘルパークラスです。

* TMP\_GameChatTextUGUIは、Unityビルトインアセットの TextMeshProを拡張したクラスであるため、先に Package Managerを用いて TextMeshProをインストールする必要があります。
* TextMeshProアセットの場合、Unity 2018.2以上のバージョンからビルトインアセットとして含まれます。
* 絵文字スプライトシートの場合、絵文字バージョン13(Android)を基準に基本的に表示され、スプライトシートを変更してカスタマイズできます。

```csharp
namespace GameChatUnity.Extension
{
    public class TMP_GameChatTextUGUI : TextMeshProUGUI
    {
        public bool isHyperLinked { get; set; }    // リンク形式アドレスをハイパーリンク処理するかどうか(HTMLタグを追加する)
        public string LinkTextColor { get; set; }  // hyperlink text color
    }
}
```

**<例>**

```csharp
using GameChatUnity.Extension;

TMP_GameChatTextUGUI message = msgObject.GetComponent<TMP_GameChatTextUGUI>();

//ハイパーリンクの認識と処理のために、テキストは setMessageを通じて入れます。
message.setMessage(MESSAGE_CONTENT);
message.color = Color.green;
message.isHyperLinked = true;

...

msgObject = Instantiate(msgObject) as GameObject;

...

// ハイパーリンクに対するクリックイベントリスナーは、直接実装してください。

//Handling with TMP_LinkInfo
TMP_LinkInfo linkInfoArr = message.textInfo.linkInfo[LINK_INDEX];

...
```


# OpenAPI

Game Chat のいくつかの機能を規定の APIで呼び出す機能です。

> 参考
>
> ダッシュボードで発行した、許可された API Keyを使用すると呼び出せます。

## API Keyの確認

API Keyは、**ダッシュボード** > **設定** > **プロジェクトの設定** > **API Key** で作成できます。

> 注意
>
> **\[再発行]** ボタンをクリックするとキーが再発行され、以前のキーは使用できなくなるのでご注意ください。

## Open APIを使用する

### Base URL <a href="#baseurl" id="baseurl"></a>

```curl
https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}
- {projectId}には Game Chatの project IDを適用
```

<table><thead><tr><th width="185">Region</th><th>URL</th></tr></thead><tbody><tr><td>kr</td><td>https://dashboard-api.gamechat.naverncp.com/v1</td></tr><tr><td>sg</td><td>https://sg-dashboard-api.gamechat.naverncp.com/v1</td></tr><tr><td>jp</td><td>https://jp-dashboard-api.gamechat.naverncp.com/v1</td></tr></tbody></table>

## 共通エラーコード

Open APIのリクエスト時に発生する共通エラーコードは次の通りです。

<table><thead><tr><th width="165">Code</th><th>Description</th></tr></thead><tbody><tr><td>-1</td><td>ダッシュボードにないキーを使用した場合</td></tr><tr><td>-2</td><td>ダッシュボードのキーとヘッダのキーが別の場合</td></tr><tr><td>-3</td><td>ダッシュボードで削除したキーを使用した場合</td></tr><tr><td>-4</td><td>ダッシュボードで未使用として処理されたキーを使用した場合</td></tr><tr><td>-5</td><td>キーの期限が切れた場合</td></tr><tr><td>-6</td><td>プロジェクト IDがない場合</td></tr></tbody></table>


# チャンネル作成API

チャンネルを作成します。

## **Request**

* Method : POST
* URI : /channel

```
POST
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel
Header : 'x-api-key: {API Key}'
Header : 'content-type: application/json'
data: '{
    "name":"#All"
}'
```

<table><thead><tr><th width="157">Header</th><th width="107">Type</th><th width="122">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>ダッシュボード > 設定 > プロジェクトの設定 > API Key</td></tr></tbody></table>

<table><thead><tr><th width="160">Attribute</th><th width="107">Type</th><th width="119">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>プロジェクトID(ダッシュボード > 設定 > プロジェクトの設定 > プロジェクトID)</td></tr><tr><td>name</td><td>String</td><td>O</td><td>チャンネル名</td></tr><tr><td>translation</td><td>Boolean</td><td>X</td><td>翻訳の可不可</td></tr><tr><td>uniqueId</td><td>String</td><td>X</td><td>任意に指定できる固有ID</td></tr></tbody></table>

## **Response**

```javascript
{
    "status": 1,
    "result": "1a51af0d-f464-4440-8ad6-ce69e0bdaba8"
}
```

<table><thead><tr><th width="159">Attribute</th><th width="138">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>結果値(1：成功、失敗はエラーコードを参考)</td></tr><tr><td>result</td><td>String</td><td>作成されたチャンネルID</td></tr></tbody></table>

## **Error code**

<table><thead><tr><th width="244">Code</th><th>Description</th></tr></thead><tbody><tr><td>-100</td><td>必須パラメータがない場合</td></tr></tbody></table>


# チャネルの修正

チャネルの詳細情報を修正します。

## リクエスト <a href="#undefined" id="undefined"></a>

* Method : PUT
* URI : /channel

```
PUT
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel
Header : 'x-api-key: {API Key}'
Header : 'content-type: application/json'
data: '{
    "name":"#All",
}'
```

<table><thead><tr><th width="133">Header</th><th width="115">Type</th><th width="120">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>ダッシュボード > 設定 > プロジェクトの設定 > API Key</td></tr></tbody></table>

<table><thead><tr><th width="133">Attribute</th><th width="114">Type</th><th width="126">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>プロジェクト ID(ダッシュボード > 設定 > プロジェクトの設定 > プロジェクト ID)</td></tr><tr><td>name</td><td>String</td><td>O</td><td>チャネル名</td></tr><tr><td>translation</td><td>Boolean</td><td>X</td><td>翻訳の可不可</td></tr><tr><td>uniqueId</td><td>String</td><td>X</td><td>任意に指定できる固有 ID</td></tr><tr><td>limit</td><td>Int</td><td>X</td><td>チャネル内の最大参加者数(0の場合、制限なし)</td></tr></tbody></table>

## レスポンス <a href="#undefined" id="undefined"></a>

```javascript
{
    "status": 1,
    "result": "1a51af0d-f464-4440-8ad6-ce69e0bdaba8"
}
```

<table><thead><tr><th width="162">Attribute</th><th width="109">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>結果値(1: 成功、失敗は Error codeを参考)</td></tr><tr><td>result</td><td>String</td><td>修正するチャネル ID</td></tr></tbody></table>

## エラーコード <a href="#undefined" id="undefined"></a>

<table><thead><tr><th width="175">Code</th><th>Description</th></tr></thead><tbody><tr><td>-100</td><td>必須パラメータがない場合</td></tr></tbody></table>


# チャンネル削除API

チャンネルを削除します。

## **Request**

* Method : DELETE
* URI : /channel/{channelId}

```
DELETE
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel/{channelId}
Header : 'x-api-key: {API Key}'
```

<table><thead><tr><th width="135">Header</th><th width="113">Type</th><th width="124">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>ダッシュボード > 設定 > プロジェクトの設定 > API Key</td></tr></tbody></table>

<table><thead><tr><th width="138">Attribute</th><th width="114">Type</th><th width="124">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>プロジェクトID(ダッシュボード > 設定 > プロジェクトの設定 > プロジェクトID)</td></tr><tr><td>channelId</td><td>String</td><td>O</td><td>チャンネルID</td></tr></tbody></table>

## **Response**

成功

```javascript
{
    "status": 1,
    "message": "success"
}
```

<table><thead><tr><th width="147">Attribute</th><th width="117">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>結果値(1：成功、失敗はエラーコードを参考)</td></tr><tr><td>message</td><td>String</td><td>結果メッセージ</td></tr></tbody></table>


# Game Chatのリソース管理

Game Chatサービスのリソース情報を確認します。

&#x20;Game Chatサービスでユーザーが実行できるすべての活動は、Resource Managerで定義したリソースタイプおよびリソースタイプ別作業履歴(アクション)とマッピングされます。 マッピングされた値を基準にユーザーが実際に行った活動履歴は Cloud Activity Tracerで収集し、管理者がユーザーの活動をモニタリングしたり、監査レポートを作成する際に活用できます。 さらに、リソースタイプは Sub Accountでユーザー別使用権限の基準としても使用されます。\
リソースとリソースタイプ別作業履歴に関する説明は以下のとおりです。

* リソース
  * 各サービスで管理する主な情報単位
  * ユーザーが作成、変更、削除できるオブジェクト
  * NAVERクラウドプラットフォームサービス別の固有の値
* リソースタイプ別作業履歴(アクション)
  * ユーザーがコンソールや APIを通じて行った作業履歴
  * リソースを作成、変更、削除する行為

Game Chatサービスのリソースタイプとリソースタイプ別作業履歴情報は以下のとおりです。

<table><thead><tr><th>サービス名(商品コード)</th><th width="163">リソースタイプ</th><th>リソースタイプ別作業履歴</th></tr></thead><tbody><tr><td>Game Chat (GameChat)</td><td>Project</td><td>Change Account</td></tr><tr><td></td><td></td><td>Change License</td></tr><tr><td></td><td></td><td>Change Project Name</td></tr><tr><td></td><td></td><td>Create Project</td></tr><tr><td></td><td></td><td>Delete Project</td></tr><tr><td></td><td></td><td>Initialize Password</td></tr><tr><td></td><td></td><td>Initialized</td></tr><tr><td></td><td></td><td>Request initialization</td></tr></tbody></table>

参考

* Resource Manager: NAVERクラウドプラットフォームで無料提供するサービスです。 使用方法の詳細は、[Resource Managerご利用ガイド](https://guide.ncloud-docs.com/docs/ja/resourcemanager-overview)をご参照ください。
* Cloud Activity Tracer: NAVERクラウドプラットフォームで無料提供するサービスです。 使用方法の詳細は、[Cloud Activity Tracerご利用ガイド](https://guide.ncloud-docs.com/docs/ja/cat-overview)をご参照ください。


# Game Chat のリリースノート

Game Chatご利用ガイドに関するリリースノートです。詳細内容は以下のとおりです。

<table><thead><tr><th width="176">リリース日</th><th width="202">リリース項目</th><th>リリース内容</th></tr></thead><tbody><tr><td>2022.02.16.</td><td>ご利用ガイドの改定</td><td>- コンテンツの構造を改善<br>- スタイルガイドを適用</td></tr><tr><td>2022.07.21.</td><td>プロジェクト名の変更</td><td>- プロジェクト名変更機能</td></tr></tbody></table>

<br>


# Game Chat(中文)

Game Chat服务可以构建游戏内的实时聊天与消息系统、供多名用户交谈的频道。

提供多种SDK和API，以便开发人员可以简单轻松地在游戏内构建聊天服务。

可在直观方便的Game Chat仪表盘内进行统计分析、服务运营和管理，并通过关联NAVER Cloud Platform的各种服务构建强大的聊天环境。

## Game Chat的丰富功能 <a href="#gamechat" id="gamechat"></a>

* 方便的仪表盘

  在手机上也能访问的Game Chat仪表盘界面中提供消息统计、聊天频道（公会）管理、屏蔽恶意用户、过滤脏话和辱骂、下载和搜索聊天消息功能。
* 一对一聊天

  可向特定用户发送通知消息，稳定地支持用户之间的一对一聊天系统。
* 多国语言消息实时自动翻译\
  为方便不同国家/地区的人交谈，提供与NAVER的强大AI翻译解决方案Papago关联的功能。可利用自动翻译功能与全球用户轻松构建社区。
* 屏蔽辱骂及屏蔽恶意用户

  为构建健康的聊天环境，可过滤并删除包含脏话和辱骂的消息，还可以设置为恶意用户（玩家）在一定时间内禁用聊天。
* 实时分析指标

  提供各种分析指标，以便分析用户访问现况、消息发送现况等。

## Game Chat使用指南说明 <a href="#gamechat" id="gamechat"></a>

为方便用户有效使用Game Chat，Game Chat使用指南由以下主题构成。读者可通过各主题了解以下内容：

* Game Chat概述：Game Chat介绍和功能介绍、相关资源介绍
* Game Chat使用前准备：介绍使用Game Chat之前需要提前准备的事项
* 启动Game Chat：Game Chat服务的方法
* 使用Game Chat：介绍可供Game Chat用户使用的功能的使用方法
  * Game Chat运营和管理：介绍仪表盘的访问方法和使用方法
  * Game Chat Unity SDK：介绍Unity专用Game Chat SDK的使用方法


# Game Chat使用前准备

介绍顺利使用Game Chat所需的服务配置、准备事项和费用信息。

## 服务配置 <a href="#undefined" id="undefined"></a>

Game Chat提供的SDK支持在以下环境中使用。

<table><thead><tr><th width="198">开发环境</th><th>配置要求</th></tr></thead><tbody><tr><td>Unity</td><td>Unity 2018.4.0以上</td></tr></tbody></table>

## 使用费

项目创建时默认为免费项目，转为付费时会产生费用。

<table><thead><tr><th width="125">类型</th><th width="153">收费区间</th><th width="98">收费标准</th><th width="93">费用</th><th width="257">备注</th></tr></thead><tbody><tr><td>免费료</td><td>200 CCU 以下</td><td>日</td><td>免费</td><td>付费转换时，计费开始 包含100GB的网络使用量</td></tr><tr><td>付费基础费</td><td>2,000 CCU 以下</td><td>日</td><td>7,333 KRW</td><td>2TB的网络使用量</td></tr></tbody></table>

* Game Chat 服务在开发免费区间内提供200 CCU。&#x20;
* CCU指的是同时连接到聊天频道的活跃用户数。

## 额外费用

<table><thead><tr><th width="185">类型</th><th width="229">收费区间</th><th width="96">收费标准</th><th width="149">费用</th><th width="70">备注</th></tr></thead><tbody><tr><td>附加 CCU</td><td>2,000 초超出 ~ 10,000 以下</td><td>CCU</td><td>150 KRW</td><td></td></tr><tr><td>附加 CCU</td><td>10,000 超出</td><td>CCU</td><td>100 KRW</td><td></td></tr><tr><td>额外网络使用量</td><td>2TB 超出</td><td>GB</td><td>100 KRW</td><td></td></tr></tbody></table>

* 在基本费用区间内，如果CCU超出，则会产生额外费用。
* 费用示例：\
  \- 从11月1日到11月30日，使用2,500 CCU的客户（超出500 CCU）\
  \- （7,333 KRW \* 30天）+ （500 CCU \* 150 KRW）= 219,990 KRW + 75,000 KRW = 294,990 KRW


# 启动Game Chat

介绍申请使用Game Chat及创建项目、管理项目的方法。

## 申请 Game Chat 服务及创建项目

要申请 Game Chat 服务并创建项目，请将您希望使用的项目名称发送至 <cs@nbase.io> 进行申请。

## 项目管理&#x20;

如需更改项目名称、重置管理员账户密码、删除项目等，请通过 <cs@nbase.io> 邮件进行请求。

> 注意
>
> 删除项目时项目中包含的所有数据也将被一并删除，请谨慎操作。

## 转换为付费

创建项目时会创建每天最多可使用200CCU的免费开发用项目。

如想使用200CCU以上，须转换为付费服务。 转换为付费项目的方法如下：

1. 请登录到 Game Chat 管理页面（仪表盘）。
2. 点击管理页面下方显示的 \[转换为付费] 按钮。&#x20;
3. 确认通知窗口后点击 \[确定] 按钮。

> 注意&#x20;
>
> 从免费环境转换为付费环境后将无法重新转换为免费环境，请谨慎操作


# Game Chat运营和管理

介绍如何在Game Chat仪表盘中运营和管理聊天，如何确认与聊天有关的统计

## 仪表盘菜单

仪表盘一目了然地提供访问现况、消息、统计等聊天的运营情况。选择日期可查看相应图表。

仪表盘菜单如下：

<figure><img src="/files/rQ1spBfp3ik5FWW4vEmS" alt=""><figcaption></figcaption></figure>

<table><thead><tr><th width="107">编号</th><th width="143">菜单</th><th>描述</th></tr></thead><tbody><tr><td>1</td><td>仪表盘</td><td>查看访问者统计</td></tr><tr><td>2</td><td>会员</td><td>查看会员及管理停用会员</td></tr><tr><td>3</td><td>聊天</td><td>添加聊天频道及管理频道</td></tr><tr><td>4</td><td>搜索</td><td>搜索会员</td></tr><tr><td>5</td><td>设置</td><td>进行项目设置、仪表盘用户设置及Unity SDK下载</td></tr><tr><td>6</td><td>操作管理</td><td>查看从搜索菜单中导出数据的记录</td></tr><tr><td>7</td><td>DOCS</td><td>- Unity：跳转至Game Chat Unity使用指南</td></tr><tr><td>8</td><td>语言设置</td><td>可变更仪表盘语言。提供韩语、英语</td></tr><tr><td>9</td><td>会员信息</td><td>修改会员信息及退出登录</td></tr></tbody></table>

## 会员 <a href="#undefined" id="undefined"></a>

可在会员菜单中查看已添加至仪表盘的会员（游戏玩家）信息，停止特定会员使用聊天或在所有聊天中将其注销。

查看会员信息 查看已添加至Game Chat仪表盘的会员信息的方法如下：

1. 在Game Chat仪表盘中点击**会员** > **列表**菜单。
2. 如需查看会员的详细信息，请点击用户ID。
3. 在界面右侧查看详细信息。
   * 可查看用户的姓名、头像URL、访问国家、ID、型号、设备ID、注册日期、最后一次登录日期等

<figure><img src="/files/UWJ9QIaUKYxVjbnNYskK" alt=""><figcaption></figcaption></figure>

4. 如需修改会员信息，请修改姓名或头像URL后点击 **\[保存]** 按钮。
   * 只能修改姓名、头像图片URL

### 注销会员 <a href="#undefined" id="undefined"></a>

注销特定会员的方法如下：

1. 在Game Chat仪表盘中点击**会员** > **列表**菜单。
2. 点击要注销的会员ID。
3. 在界面右侧显示会员详细信息后，点击 **\[注销]** 按钮。
4. 显示确认弹窗后，点击 **\[是]** 按钮。

### 搜索会员 <a href="#undefined" id="undefined"></a>

搜索已添加至Game Chat仪表盘的会员的方法如下：

1. 在Game Chat仪表盘中点击**会员** > **列表**菜单。
2. 设置搜索条件后点击 **\[搜索]** 按钮。
   * 可按用户ID创建日期、用户ID、昵称、国家、IP条件搜索
3. 查看搜索结果。

### 停用会员 <a href="#undefined" id="undefined"></a>

可设置特定会员在一定时间内禁用聊天。可在停用菜单中查看和搜索处于停用状态的会员。\
停止特定会员使用聊天的方法如下：

1. 在Game Chat仪表盘中点击**会员** > **停用**菜单。
2. 点击界面右侧的 **\[添加]** 按钮。
3. 显示停用添加窗口后，点击 **\[状态]** 按钮变更为激活状态。
4. 如需将拟停用会员从所有频道中踢出，请勾选 **踢出聊天**复选框。
5. 设置用户ID和停用原因、停用期限后点击 **\[保存]** 按钮。

## 聊天 <a href="#undefined" id="undefined"></a>

可在聊天菜单中查看频道、发送聊天消息。

### 添加聊天频道 <a href="#undefined" id="undefined"></a>

添加新聊天频道的方法如下：

1. 在Game Chat仪表盘中点击**频道**菜单。
2. 点击 **\[添加频道]** 按钮。
3. 显示频道添加窗口后，输入频道和唯一ID并点击 **\[添加]** 按钮。
   * 输入唯一ID时，SDK可利用该值访问频道
4. 确认是否已创建频道。

### 设置聊天频道 <a href="#undefined" id="undefined"></a>

查看正在参与特定聊天频道的用户或修改、删除频道信息的方法如下：

1. 在Game Chat仪表盘中点击**频道**菜单。
2. 选择频道后点击频道界面右上方的“:”图标。
3. 显示上下文菜单后选择所需操作。<br>

<figure><img src="/files/jhkCGnFqfPtUIovL8Gzj" alt=""><figcaption></figcaption></figure>

* 如需查看参与聊天频道的用户列表，请点击 **\[参与列表]** 菜单。
* 如需修改聊天频道信息，请点击 **\[修改频道]** 菜单。
* 如需删除聊天频道，请点击 **\[删除]** 菜单。

## 搜索 <a href="#undefined" id="undefined"></a>

可在搜索菜单中查看和搜索项目的所有频道中收发的消息。可按ID、昵称、消息、频道ID、消息发送时间标准搜索，并以CSV文件格式下载消息列表。

<figure><img src="/files/oGO7fMuwq5ga0zJSQi2h" alt=""><figcaption></figcaption></figure>

### 搜索消息及查看消息详细信息 <a href="#undefined" id="undefined"></a>

查看消息详细信息（填写消息的频道ID、消息ID、消息、消息发送时间）的方法如下：

1. 在Game Chat仪表盘中点击 **搜索** 菜单。
2. 设置搜索条件后点击 **\[搜索]** 按钮。
   * 可按消息发送日期、会员ID、频道ID、昵称、消息条件搜索
3. 点击要查看详细信息的消息的查看图标。
4. 可查看添加相应消息的频道ID、消息ID、消息、消息发送时间。

### 删除消息 <a href="#undefined" id="undefined"></a>

可搜索特定消息后删除。在搜索菜单中删除的消息在相应聊天频道中也将被删除。

1. 在Game Chat仪表盘中点击 **搜索** 菜单。
2. 点击拟删除消息的删除图标。
3. 显示删除确认弹窗后点击 **\[是]** 按钮。

## 设置 <a href="#undefined" id="undefined"></a>

可在设置菜单中设置Game Chat项目信息、设置聊天禁用词和是否自动翻译消息、变更用户信息或赋予特定用户管理员权限。

### 项目设置 <a href="#undefined" id="undefined"></a>

介绍如何查看和修改项目信息，如何设置禁用词，以及如何使用聊天内容自动翻译功能。

#### **查看项目信息**

可查看NAVER Cloud ID、项目ID、API密钥、项目名、消息长度限制，还可以设置项目名、消息长度限制、禁用词。\
查看项目信息的方法如下：

1. 在Game Chat仪表盘中点击**设置** > **项目设置**菜单。
2. 查看项目信息。
   * 只能修改项目名、消息长度限制

#### **禁用词设置**

可将禁止在聊天中使用的文字（脏话和辱骂等）设置为禁用词，提供健康的聊天环境。\
设置禁用词的方法如下：

1. 在Game Chat仪表盘中点击**设置** > **项目设置**菜单。
2. 选择禁用词限制类型。
   * 无限制：被指定为禁用词的单词也直接显示
   * 替换为\*：被指定为禁用词的单词在聊天窗口中显示为\*
   * 阻止消息发送：不发送被指定为禁用词的单词
3. 如需自动导入禁用词示例，请点击 **\[使用基本禁用词]** 按钮。
4. 点击 **\[保存]** 按钮。

#### **自动翻译聊天消息**

可关联NAVER Cloud Platform提供的Papago Translation服务，自动翻译聊天中输入的消息。\
设置为自动翻译聊天消息的方法如下：

1. 在Game Chat仪表盘中点击**设置** > **项目设置**菜单。
2. 点击Papago区域的激活图标。
3. 输入客户端ID和客户端密钥后点击 **\[保存]** 按钮。

> 参考
>
> 关于查看用于关联Papago Translation的客户端ID和客户端密钥的方法，请参考[Application使用指南](https://guide.ncloud-docs.com/docs/en/naveropenapiv3-application)。

### 用户设置 <a href="#undefined" id="undefined"></a>

可查看项目的用户并修改用户信息。但当前正在访问账户的详细信息可在修改会员信息菜单中修改。\
修改用户信息的方法如下：

1. 在Game Chat仪表盘中点击**设置** > **用户设置**菜单。
2. 点击要修改用户信息的用户的![game-gamechatmgmt\_icon\_zh.png](https://files.document360.io/6998976f-9d95-4df8-b847-d375892b92c2/Images/Documentation/game-gamechatmgmt_icon_zh.png) > **详情**菜单。
3. 设置用户名、密码、用户状态后点击 **\[保存]** 按钮。
4. 如需将特定用户设置为仪表盘的管理员，请将管理员权限图标变更为激活状态后点击 **\[保存]** 按钮。
5. 如需删除用户信息，请点击 **\[删除]** 按钮。

#### 下载SDK <a href="#sdk" id="sdk"></a>

可下载Unity SDK。

## 操作管理 <a href="#undefined" id="undefined"></a>

在30天期限内，可在下载操作管理菜单中以CSV格式从搜索菜单导出的结果。

## 修改会员信息 <a href="#undefined" id="undefined"></a>

可在会员信息菜单中修改账户信息并退出登录。

### 修改我的信息 <a href="#undefined" id="undefined"></a>

可查看登录账户的信息，并修改姓名、头像URL和仪表盘显示时区。头像URL会在聊天时使用。\
修改我的信息的方法如下：

1. 点击Game Chat仪表盘右上方的用户图标后点击修改会员信息菜单。
2. 在修改我的信息菜单中设置姓名或头像URL、时区后点击 **\[保存]** 按钮。

### 变更密码

变更密码的方法如下：

1. 点击Game Chat仪表盘右上方的用户图标后点击**修改会员信息**菜单。
2. 点击修改密码菜单后，输入当前密码和要变更的密码并点击 **\[保存]** 按钮。

## 退出仪表盘 <a href="#undefined" id="undefined"></a>

如需退出Game Chat仪表盘，请点击Game Chat仪表盘右上方的用户图标后点击**退出登录**菜单。<br>


# Unity SDK

以下介绍Game Chat Unity SDK的使用方法。

## 配置要求 <a href="#undefined" id="undefined"></a>

使用Game Chat Unity SDK时的配置要求如下。

* 最低配置：2018.4.0以上\
  （如需获得低版本Unity的支持，请在 '<cs@nbase.io>' 进行咨询。 )
* 2019.4.X/2020.3.X/2021.1.X版本的Unity编辑器用户请使用2019.4.29f1以上/2020.3.15f2以上/2021.1.16f1以上版本（构建AAB版本时存在的Unity编辑器漏洞被修复的版本）。

## 验证

#### 重置Game Chat实例 <a href="#gamechat" id="gamechat"></a>

如需使用Game Chat项目ID重置Game Chat实例，请使用下列代码：

```csharp
GameChat.initialize(PROJECT_ID);

// 使用新加坡区域时
GameChat.setRegion("sg");
GameChat.initialize(PROJECT_ID);
```

| ID          | type   | desc |
| ----------- | ------ | ---- |
| PROJECT\_ID | string | 项目ID |

### 连接Game Chat Socket服务器

#### 连接Game Chat Socket服务器的方法如下：

1. 使用聊天用户ID访问Game Chat Socket服务器。
   * Game Chat项目中，聊天用户ID是唯一值。
2. 获取使用API所需的Token值。
   * 可查看GameChat.connect之后更新的Token值。
3. 获取Token值后确认当前访问设备的聊天用户信息是否已更新。
   * 通过回调GameChat.connect获取的会员信息为更新后的数据。

### 如需连接Game Chat Socket服务器，请使用下列代码：

```csharp
GameChat.connect(USER_ID,  (Member User, GameChatException Exception)=> 
{

    if(Exception != null)
    {
        // 错误处理
        return;
    }
});
```

| ID       | type   | desc     |
| -------- | ------ | -------- |
| USER\_ID | string | 聊天用户唯一ID |

### 断开Game Chat服务器连接 <a href="#gamechat" id="gamechat"></a>

如需断开与Game Chat Socket服务器的连接，请使用下列代码：

```csharp
GameChat.disconnect();
```

### 更新聊天用户信息 <a href="#undefined" id="undefined"></a>

连接成功后，如需保存并更新聊天用户信息，请使用下列代码。

#### **修改昵称**

```csharp
GameChat.setNickname(USER_ID, NickName, (member, exception) =>
{
    if (exception != null)
    {
        // 错误处理
        return;
    }
    
});
```

<table><thead><tr><th width="206">ID</th><th width="169">type</th><th>desc</th></tr></thead><tbody><tr><td>USER_ID</td><td>string</td><td>聊天用户唯一ID</td></tr><tr><td>NickName</td><td>string</td><td>聊天用户昵称</td></tr></tbody></table>

#### **修改简介URL**

```csharp
GameChat.setProfileUrl(USER_ID, ProfileUrl, (member, exception) =>
{
    if (exception != null)
    {
        // 错误处理
        return;
    }
    
});
```

<table><thead><tr><th width="210">ID</th><th width="169">type</th><th>desc</th></tr></thead><tbody><tr><td>USER_ID</td><td>string</td><td>聊天用户唯一ID</td></tr><tr><td>ProfileUrl</td><td>string</td><td>聊天用户ProfileURL</td></tr></tbody></table>

## 订阅和取消订阅频道

如需订阅或取消订阅特定频道，请使用下列代码：

```csharp
GameChat.subscribe(CHANNEL_ID);

GameChat.unsubscribe(CHANNEL_ID);
```

| ID          | type   | desc |
| ----------- | ------ | ---- |
| CHANNEL\_ID | string | 频道ID |

## 发送消息 <a href="#undefined" id="undefined"></a>

如需向特定频道发送消息，请使用下列代码：

```csharp
GameChat.sendMessage(CHANNEL_ID, MESSAGE);
```

<table><thead><tr><th width="220">ID</th><th width="160">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>频道ID</td></tr><tr><td>MESSAGE</td><td>string</td><td>发送的消息文本</td></tr></tbody></table>

在消息参数中输入@\[玩家ID]空格\[消息内容]时

```csharp
@user_id消息正文
```

在上述用例中，如果玩家ID已有登录历史，消息详细信息中提及的信息即为玩家ID。

## 添加和解除事件

如需对从Game Chat Socket服务器接收的事件添加或解除自定义处理，请使用下列代码：

```csharp
GameChat.dispatcher.(EVENT_NAME) += (CALLBACK_FUNCTION);
```

```csharp
public delegate void onConnectedCallback(string data);
public onConnectedCallback onConnected;
对//“connect”事件的回调

public delegate void onDisconnectedCallback(string reason);
public onDisconnectedCallback onDisconnected;
对//“disconnect”事件的回调

public delegate void onMessageReceivedCallback(Message message);
public onMessageReceivedCallback onMessageReceived;
对//“message”事件的回调

public delegate void onUserAddedCallback(UserInfo userinfo);
public onUserAddedCallback onUserAdded;
对//“userAdded”事件的回调

public delegate void onUserRemovedCallback(Message message);
public onUserRemovedCallback onUserRemoved;
对//“userRemoved”事件的回调

public delegate void onErrorReceivedCallback(string result, GameChatException exception);
public onErrorReceivedCallback onErrorReceived;
对//“error”事件的回调
```

## 例外情形

下面是对使用Game Chat API过程中发生的例外情况采取的通用处理Class。

<pre class="language-csharp"><code class="lang-csharp"><strong>public class GameChatException
</strong>{
    // Detail Error Code
   
    // 未知错误
    public static readonly int CODE_UNKNOWN_ERROR           = 0;
    // 初始化失败
    public static readonly int CODE_NOT_INITALIZE           = 1;
    // 参数不正确时
    public static readonly int CODE_INVAILD_PARAM           = 2;  
    // Socket服务器发生错误
    public static readonly int CODE_SOCKET_SERVER_ERROR     = 500;
    // Socket发生错误
    public static readonly int CODE_SOCKET_ERROR = -501;
    // 发生网络连接错误及超时时
    public static readonly int CODE_SERVER_NETWORK_ERROR    = 4002;
    // 解析从服务器接收的数据时发生错误
    public static readonly int CODE_SERVER_PARSING_ERROR    = 4003;

    // 发生HTTP错误时，传递相应状态码作为响应代码。 (400, 403 ...)

    // Error Code
    public int code { get; set; }
    // Error Message
    public string message { get; set; }
}
</code></pre>

## Client API

### 订阅频道

#### **Subscription Data Class (per Unit)**

```csharp
public class Subscription
{
    public string id;
    public string channel_id;
    public string user_id;
    public string created_at;
}
```

<table><thead><tr><th width="173">ID</th><th width="186">type</th><th>desc</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>唯一ID</td></tr><tr><td>channel_id</td><td>string</td><td>频道ID</td></tr><tr><td>user_id</td><td>string</td><td>聊天用户唯一ID</td></tr><tr><td>created_at</td><td>string</td><td>创建日期</td></tr></tbody></table>

#### **导入频道订阅列表**

如需以列表形式导入特定频道的订阅数据，请使用下列代码：

```csharp
GameChat.getSubscriptions(CHANNEL_ID, OFFSET, LIMIT, (List<Subscription> Subscriptions, GameChatException Exception) => {

    if(Exception != null)
    {
        // 错误处理
        return;
    }

    foreach(Subscription elem in Subscriptions)
    {
        //handling each subscription instance
    }
}));
```

### 频道

#### **Channel Data Class (per Unit)**

```csharp
public class Channel
{
    public string id;
    public string project_id;
    public string unique_id;
    public string name;
    public string user_id;
    public string created_at;
    public string updated_at;
}
```

<table><thead><tr><th width="193">ID</th><th width="172">type</th><th>desc</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>频道ID（唯一值）</td></tr><tr><td>project_id</td><td>string</td><td>项目ID</td></tr><tr><td>unique_id</td><td>string</td><td>开发公司可设置的频道ID（唯一值）</td></tr><tr><td>name</td><td>string</td><td>频道名称</td></tr><tr><td>user_id</td><td>string</td><td>（创建频道的）聊天用户ID</td></tr><tr><td>created_at</td><td>string</td><td>创建日期</td></tr><tr><td>updated_at</td><td>string</td><td>更新日期</td></tr></tbody></table>

#### **导入频道列表**

如需以列表形式导入项目的频道数据，请使用下列代码：

```csharp
GameChat.getChannels(OFFSET, LIMIT, (List<Channel> Channels, GameChatException Exception) => {

    if(Exception != null)
    {
        // 错误处理
        return;
    }

    foreach(Channel elem in Channels)
    {
        //handling each channelInfo instance
    }
});
```

<table><thead><tr><th width="185">ID</th><th width="134">type</th><th>desc</th></tr></thead><tbody><tr><td>OFFSET</td><td>int</td><td>拟从全部频道列表导入的频道的开始位置（索引）</td></tr><tr><td>LIMIT</td><td>int</td><td>拟导入的频道数量</td></tr></tbody></table>

#### **导入频道数据**

如需使用频道ID和唯一ID导入频道数据，请使用下列代码：

```csharp
仅使用//CHANNEL_ID搜索时，在CHANNEL_UNIQUE_ID参数中输入null。

//CHANNEL_ID和CHANNEL_UNIQUE_ID值同时存在时，优先搜索CHANNEL_UNIQUE_ID值。

GameChat.getChannel(CHANNEL_ID, CHANNEL_UNIQUE_ID,  (Channel Channel, GameChatException Exception) => {

    if(Exception != null)
    {
        // 错误处理
        return;
    }

    //handling channelInfo instance
});
```

```csharp
GameChat.getChannel(CHANNEL_UNIQUE_ID, (Channel Channel, GameChatException Exception) => {

    if(Exception != null)
    {
        // 错误处理
        return;
    }

    //handling channelInfo instance
});
```

| ID                  | type   | desc           |
| ------------------- | ------ | -------------- |
| CHANNEL\_ID         | string | 频道ID（自动生成）     |
| CHANNEL\_UNIQUE\_ID | string | 频道（唯一）ID（可自定义） |

### 创建和删除频道 <a href="#undefined" id="undefined"></a>

如需在项目内创建和删除新的频道，应使用Open API。\
考虑到安全问题，建议使用Open API通过Server to Server手动进行频道创建和更新等操作。 详细内容请参考Game Chat API指南。

### 消息 <a href="#undefined" id="undefined"></a>

**(Received) Message Data Class (per Unit)**

```csharp
public class Message
{
    public class User
    {
        public string id;
        public string name;
        public string profile;
    }

    public string message_id;
    public string channel_id;
    public string message_type;
    public string content;

    public string[] mentions;
    public bool mentions_everyone;
    public User sender;
    public string created_at;
}
```

<table><thead><tr><th width="195">ID</th><th width="140">type</th><th>desc</th></tr></thead><tbody><tr><td>message_id</td><td>string</td><td>消息的唯一ID</td></tr><tr><td>channel_id</td><td>string</td><td>频道ID</td></tr><tr><td>message_type</td><td>string</td><td>消息类型</td></tr><tr><td>content</td><td>string</td><td>消息内容（JSON字符串）</td></tr><tr><td>mentions</td><td>string</td><td>提及（标签）</td></tr><tr><td>created_at</td><td></td><td>string</td></tr></tbody></table>

#### **导入消息列表**

如需以列表形式导入特定频道的消息数据，请使用下列代码：

```csharp
GameChat.getMessages(CHANNEL_ID, OFFSET, LIMIT, SEARCH, QUERY, SORT, (List<Message> Messages, GameChatException Exception) => {

    if(Exception != null)
    {
        // 错误处理
        return;
    }

    foreach(Message elem in Messages)
    {
        //handling each message instance
    }
});
```

<table><thead><tr><th width="190">ID</th><th width="125">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>频道ID</td></tr><tr><td>OFFSET</td><td>string</td><td>拟从全部消息列表导入的消息的开始位置</td></tr><tr><td>LIMIT</td><td>string</td><td>拟导入的消息数量</td></tr><tr><td>SEARCH</td><td>string</td><td>消息搜索基准参数； &#x3C;示例> content.text<br>传递空字符串时，全数扫描</td></tr><tr><td>QUERY</td><td>string</td><td>消息搜索值； 只能搜索完全一致的内容。 传递空字符串时，全数扫描</td></tr><tr><td>SORT</td><td>string</td><td>消息排列顺序（默认：降序 - 按最新排列）（可选项：升序）</td></tr></tbody></table>

#### **翻译消息**

自动翻译功能被激活的状态下，可将任意文本翻译成指定语言。 关联[Papago Translation](https://www.ncloud.com/product/aiService/papagoTranslation){target="\_blank"}服务后即可使用自动翻译功能。

**(Received) Translation Data Class (per Unit)**

```csharp
public class Translation
{
    public string detectLang = "";
    public string lang = "";
    public bool translated = false;
    public string message = "";
}
```

<table><thead><tr><th width="177">ID</th><th width="141">type</th><th>desc</th></tr></thead><tbody><tr><td>detectLang</td><td>string</td><td>源语言代码</td></tr><tr><td>lang</td><td>string</td><td>目标语言代码</td></tr><tr><td>translated</td><td>bool</td><td>是否翻译成功</td></tr><tr><td>message</td><td>string</td><td>结果消息内容（JSON字符串）</td></tr></tbody></table>

> &#x20;参考
>
> 关于源语言代码和目标语言代码的介绍，请参考[Papago Text Translation API指南](https://api.ncloud-docs.com/docs/zh/ai-naver-papagonmt-translation)

```csharp
GameChat.translateMessage(CHANNEL_ID, SORCE_LANG, TARTGET_LANG, TEXT, (List<Translation> Translations, GameChatException Exception) => {

    if(Exception != null)
    {
        // 错误处理
        return;
    }

    foreach(Translation elem in Translations)
    {
        //handling each Translation instance
    }
});

GameChat.translateMessage(SORCE_LANG, TARTGET_LANG, TEXT, (List<Translation> Translations, GameChatException Exception) => {

    if(Exception != null)
    {
        // 错误处理
        return;
    }

    foreach(Translation elem in Translations)
    {
        //handling each Translation instance
    }
});
```

<table><thead><tr><th width="187">ID</th><th width="108">type</th><th>desc</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>频道ID</td></tr><tr><td>SORCE_LANG</td><td>string</td><td>拟发送的文本语言名称（auto：自动检测）<br>参考<a href="https://api.ncloud-docs.com/docs/zh/ai-naver-papagonmt-translation">API指南</a>{target="_blank"}</td></tr><tr><td>TARTGET_LANG</td><td>string</td><td>（待接收翻译的）文本语言代码<br>（可使用“,”符号隔开输入多个。 &#x3C;示例> “en, fr, th”）<br>参考<a href="https://api.ncloud-docs.com/docs/zh/ai-naver-papagonmt-translation">Papago Text Translation API指南</a>{target="blank"}</td></tr><tr><td>TEXT</td><td>string</td><td>拟发送的文本</td></tr></tbody></table>

### 聊天用户 <a href="#undefined" id="undefined"></a>

**(Received) Member Data Class (per Unit)**

```csharp
public class Member
{
    public string id = "";
    public string project_id = "";
    public string nickname = "";
    public string profile_url = "";
    public string country = "";
    public string remoteip = "";
    public string adid = "";
    public string device = "";
    public string network = "";
    public string version = "";
    public string model = "";
    public string logined_at = "";
    public string created_at = "";
    public string updated_at = "";
}
```

<table><thead><tr><th width="187">ID</th><th width="127">type</th><th>desc</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>聊天用户唯一ID</td></tr><tr><td>project_id</td><td>string</td><td>已登录的Game Chat项目ID</td></tr><tr><td>nickname</td><td>string</td><td>聊天用户昵称</td></tr><tr><td>profile_url</td><td>string</td><td>头像图片URL</td></tr><tr><td>country</td><td>string</td><td>访问国家</td></tr><tr><td>remoteip</td><td>string</td><td>访问IP</td></tr><tr><td>adid</td><td>string</td><td>广告标识符</td></tr><tr><td>device</td><td>string</td><td>访问设备环境</td></tr><tr><td>network</td><td>string</td><td>访问网络类型（移动数据、Wi-Fi）</td></tr><tr><td>version</td><td>string</td><td>访问的应用版本</td></tr><tr><td>model</td><td>string</td><td>访问设备型号</td></tr><tr><td>logined_at</td><td>string</td><td>登录日期</td></tr><tr><td>created_at</td><td>string</td><td>聊天用户创建日期</td></tr><tr><td>updated_at</td><td>string</td><td>聊天用户信息更新日期</td></tr></tbody></table>

#### **更新聊天用户信息**

可更新聊天服务器的用户信息。

```csharp

// 更新聊天用户昵称
// 昵称可用的字符串长度为2~128个字符，不得包含空白字符（空格、制表符、换行符）。
GameChat.setName(MEMBER_ID, NAME, (Member member, GameChatException Exception) => {

    if(Exception != null)
    {
        // 错误处理
        return;
    }
    //handling updated Member instance
});

//更新聊天用户简介图片URL
GameChat.setProfileUrl(MEMBER_ID, PROFILE_URL, (Member member, GameChatException Exception) => {

    if(Exception != null)
    {
        // 错误处理
        return;
    }
    //handling updated Member instance
});

```

<table><thead><tr><th width="190">ID</th><th width="153">type</th><th>desc</th></tr></thead><tbody><tr><td>MEMBER_ID</td><td>string</td><td>聊天用户唯一ID</td></tr><tr><td>NAME</td><td>string</td><td>聊天用户昵称或姓名</td></tr><tr><td>PROFILE</td><td>string</td><td>头像图片URL</td></tr></tbody></table>

## GameChatExtension (Emoji, HyperLink) <a href="#gamechatextensionemojihyperlink" id="gamechatextensionemojihyperlink"></a>

帮助开发人员轻松处理所接收消息中包含的表情符号和超链接文本的辅助类。

* TMP\_GameChatTextUGUI是对Unity内置资源TextMeshPro进行扩展的类，因此须先使用Package Manager安装TextMeshPro。
* TextMeshPro资源在Unity 2018.2以上版本中以内置资源形式提供。
* 表情符号的精灵表单默认以Emoji 13版本（Android）为基准进行输出，可通过更改精灵表单进行自定义设置。

```csharp
namespace GameChatUnity.Extension
{
    public class TMP_GameChatTextUGUI : TextMeshProUGUI
    {
        public bool isHyperLinked { get; set; }   // 是否对链接形式的地址进行超链接处理（添加HTML标签）
        public string LinkTextColor { get; set; }  // hyperlink text color
    }
}
```

**<示例>**

```csharp
using GameChatUnity.Extension;

TMP_GameChatTextUGUI message = msgObject.GetComponent<TMP_GameChatTextUGUI>();

//为了识别并处理超链接，需使用setMessage输入文本。
message.setMessage(MESSAGE_CONTENT);
message.color = Color.green;
message.isHyperLinked = true;

...

msgObject = Instantiate(msgObject) as GameObject;

...

// 对于超链接的click event listener需直接构建。

//Handling with TMP_LinkInfo
TMP_LinkInfo linkInfoArr = message.textInfo.linkInfo[LINK_INDEX];

...
```


# Open API

该功能可以利用规定的API调用Game Chat的几种功能。

> 参考
>
> 调用时，须使用仪表盘发放的已授权的API Key。

## API Key确认 <a href="#apikey" id="apikey"></a>

可以在 **仪表盘** > **设置** > **项目设置** > **API Key** 中创建API Key。

> 注意
>
> 请注意，点击 **\[重发]** 按键可重发密钥，且之前的密钥将无法使用。

## 使用Open API <a href="#openapi" id="openapi"></a>

### Base URL <a href="#baseurl" id="baseurl"></a>

```curl
https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}
- 将Game Chat的project id应用于{projectId}部分
```

<table><thead><tr><th width="158">Region</th><th>URL</th></tr></thead><tbody><tr><td>kr</td><td>https://dashboard-api.gamechat.naverncp.com/v1</td></tr><tr><td>sg</td><td>https://sg-dashboard-api.gamechat.naverncp.com/v1</td></tr><tr><td>jp</td><td>https://jp-dashboard-api.gamechat.naverncp.com/v1</td></tr></tbody></table>

### 通用错误代码 <a href="#undefined" id="undefined"></a>

Open API请求时发生的通用错误代码如下：

<table><thead><tr><th width="195">Code</th><th>Description</th></tr></thead><tbody><tr><td>-1</td><td>使用了仪表盘中不存在的密钥时</td></tr><tr><td>-2</td><td>仪表盘密钥和头部信息的密钥不同时</td></tr><tr><td>-3</td><td>使用了已从仪表盘删除的密钥时</td></tr><tr><td>-4</td><td>使用了仪表盘中作未使用处理的密钥时</td></tr><tr><td>-5</td><td>密钥到期时</td></tr><tr><td>-6</td><td>没有项目ID时</td></tr></tbody></table>


# 频道创建API

此API用于创建频道。

## **Request**

* Method : POST
* URI : /channel

```
POST
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel
Header : 'x-api-key: {API Key}'
Header : 'content-type: application/json'
data: '{
    "name":"#All"
}'
```

<table><thead><tr><th width="141">Header</th><th width="115">Type</th><th width="122">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>仪表盘 > 设置 > 项目设置 > API Key</td></tr></tbody></table>

<table><thead><tr><th width="143">Attribute</th><th width="113">Type</th><th width="125">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>项目ID（仪表盘 > 设置 > 项目设置 > 项目ID）</td></tr><tr><td>name</td><td>String</td><td>O</td><td>频道名称</td></tr><tr><td>translation</td><td>Boolean</td><td>X</td><td>可否翻译</td></tr><tr><td>uniqueId</td><td>String</td><td>X</td><td>可随机指定的唯一ID</td></tr></tbody></table>

## **Response**

```javascript
{
    "status": 1,
    "result": "1a51af0d-f464-4440-8ad6-ce69e0bdaba8"
}
```

<table><thead><tr><th width="153">Attribute</th><th width="134">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>结果值(1：成功，失败请参考错误代码)</td></tr><tr><td>result</td><td>String</td><td>创建的频道ID</td></tr></tbody></table>

## **Error code**

<table><thead><tr><th width="191">Code</th><th>Description</th></tr></thead><tbody><tr><td>-100</td><td>必须参数不存在的情况</td></tr></tbody></table>


# 修改频道

修改频道上的详细信息。

## 请求 <a href="#undefined" id="undefined"></a>

* Method : PUT
* URI : /channel

```
PUT
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel
Header : 'x-api-key: {API Key}'
Header : 'content-type: application/json'
data: '{
    "name":"#All",
}'
```

<table><thead><tr><th width="143">Header</th><th width="104">Type</th><th width="109">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>仪表盘 > 设置 > 项目设置 > API Key</td></tr></tbody></table>

<table><thead><tr><th width="144">Attribute</th><th width="105">Type</th><th width="111">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>项目ID（仪表盘 > 设置 > 项目设置 > 项目ID）</td></tr><tr><td>name</td><td>String</td><td>O</td><td>频道名称</td></tr><tr><td>translation</td><td>Boolean</td><td>X</td><td>是否可翻译</td></tr><tr><td>uniqueId</td><td>String</td><td>X</td><td>可任意指定的固有ID</td></tr><tr><td>limit</td><td>Int</td><td>X</td><td>频道内最大参与人数（为0时没有限制）</td></tr></tbody></table>

## 响应 <a href="#undefined" id="undefined"></a>

```javascript
{
    "status": 1,
    "result": "1a51af0d-f464-4440-8ad6-ce69e0bdaba8"
}
```

<table><thead><tr><th width="158">Attribute</th><th width="136">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>结果值（1：成功，失败参考Error code）</td></tr><tr><td>result</td><td>String</td><td>修改的频道ID</td></tr></tbody></table>

## 错误代码 <a href="#undefined" id="undefined"></a>

<table><thead><tr><th width="192">Code</th><th>Description</th></tr></thead><tbody><tr><td>-100</td><td>无必要参数时</td></tr></tbody></table>


# 频道删除API

此API用于删除频道。

## **Request**

* Method : DELETE
* URI : /channel/{channelId}

```
DELETE
url : https://dashboard-api.gamechat.naverncp.com/v1/api/project/{projectId}/channel/{channelId}
Header : 'x-api-key: {API Key}'
```

<table><thead><tr><th width="144">Header</th><th width="98">Type</th><th width="122">Required</th><th>Description</th></tr></thead><tbody><tr><td>x-api-key</td><td>String</td><td>O</td><td>仪表盘 > 设置 > 项目设置 > API Key</td></tr></tbody></table>

<table><thead><tr><th width="145">Attribute</th><th width="97">Type</th><th width="123">Required</th><th>Description</th></tr></thead><tbody><tr><td>projectId</td><td>String</td><td>O</td><td>项目ID（仪表盘 > 设置 > 项目设置 > 项目ID）</td></tr><tr><td>channelId</td><td>String</td><td>O</td><td>频道ID</td></tr></tbody></table>

## **Response**

成功

```javascript
{
    "status": 1,
    "message": "success"
}
```

<table><thead><tr><th width="164">Attribute</th><th width="157">Type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>Int</td><td>结果值(1：成功，失败请参考错误代码)</td></tr><tr><td>message</td><td>String</td><td>结果消息</td></tr></tbody></table>


# Game Chat资源管理

查看Game Chat（已失效）服务的资源信息。 用户可在Game Chat（已失效）服务中执行的所有活动都将与Resource Manager定义的资源类型和各资源类型的作业记录（操作）进行映射。 Cloud Activity Tracer会根据映射值收集用户实际执行的活动记录，管理员可在监控用户活动或创建审核报告时使用这些记录。 此外，资源类型还用作Sub Account中各用户的使用权限标准。 关于资源和各资源类型的作业记录的描述如下。

* 资源
  * 各项服务管理的主要信息单位
  * 用户创建、变更和删除的对象
  * NAVER Cloud Platform服务的唯一值
* 各资源类型的作业记录（操作）
  * 用户通过控制台和API执行的作业记录
  * 创建、变更或删除资源的行为

Game Chat（已失效）服务的资源类型和各资源类型的作业记录信息如下。

| 服务名称（产品代码）                       | 资源类型    | 各资源类型的作业记录             |
| -------------------------------- | ------- | ---------------------- |
| Game Chat (Deprecated)(GameChat) | Project | Change Account         |
|                                  |         | Change License         |
|                                  |         | Change Project Name    |
|                                  |         | Create Project         |
|                                  |         | Delete Project         |
|                                  |         | Initialize Password    |
|                                  |         | Initialized            |
|                                  |         | Request initialization |

> &#x20;参考
>
> * Resource Manager：由NAVER Cloud Platform提供的免费服务。 具体使用方法请参考 Resource Manager 使用指南。
> * Cloud Activity Tracer：由NAVER Cloud Platform提供的免费服务。 具体使用方法请参考 Cloud Activity Tracer 使用指南。
> * Sub Account：由NAVER Cloud Platform提供的免费服务。 虽然权限是根据Resource Manager服务定义的资源类型设计的，但资源类型组和各资源类型的操作由Sub Account服务自行配置，因此与Resource Manager服务定义的组和操作值不同。


# Game Chat版本注释

Game Chat使用指南的版本注释。具体内容如下。

<table><thead><tr><th width="191">版本日期</th><th width="175">版本项目</th><th>版本内容</th></tr></thead><tbody><tr><td>2022.02.16.</td><td>修订使用指南</td><td>- 改善内容结构<br>- 适用风格指南</td></tr><tr><td>2022.07.21.</td><td>项目名称变更</td><td>- 项目名称更改特征</td></tr></tbody></table>


# Game Chat (V3)


# Game Chat(한국어)


# V3 사용 시작

Game Chat 대시보드에서 채팅을 운영하고 관리하는 방법, 채팅과 관련된 통계를 확인하는 방법과 네이버 클라우드 플랫폼의 다양한 서비스와 연동하는 방법을 설명합니다.

## 대시보드 메뉴 <a href="#undefined" id="undefined"></a>

대시보드에서는 접속 현황, 메시지, 통계 등 채팅의 운영 상황을 한 눈에 파악할 수 있습니다. 날짜를 선택하여 그래프를 확인할 수 있습니다.

대시보드 메뉴는 다음과 같습니다.

| 항목            | 설명                              |
| ------------- | ------------------------------- |
| ① **홈**       | 서비스 사용량 및 사용현황 확인               |
| ② **분석**      | 사용자 및 동시접속자 분석                  |
| ③ **유저**      | 사용자 확인 및 이용 정지 사용자 관리           |
| ④ **채팅**      | 채팅 채널 추가 및 채널 관리                |
| ⑤ **메시지**     | 기간단위 채팅 메시지 검색 및 엑셀 추출          |
| ⑥ **아카이브**    | 채팅간 주고 받은 모든 파일(이미지/영상)등 확인     |
| ⑦ **푸시알림**    | 푸시 전송 및 내역 확인                   |
| ⑧ **설정**      | 프로젝트의 일반, 보안, 연동상품, 대시보드 관리자 설정 |
| ⑨ **활동 및 파일** | 검색 메뉴에서 데이터 내보내기 한 내역 확인        |
| ⑩ **가이드**     | Game Chat 사용 가이드로 이동            |

## 유저 <a href="#undefined" id="undefined"></a>

유저 메뉴에서는 대시보드에 등록된 사용자의 정보를 확인하고, 특정 사용자의 채팅 이용을 정지하거나 모든 채팅에서 탈퇴시킬 수 있습니다.

### 유저 정보 확인 <a href="#undefined" id="undefined"></a>

Game Chat 대시보드에 등록된 사용자의 정보를 확인하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **유저** > **유저들** 메뉴를 클릭해 주십시오.
2. 사용자의 상세 정보를 확인하려면 사용자 ID를 클릭해 주십시오.
3. 화면 팝업창에서 상세 정보를 확인해 주십시오.
   * 유저의 이름, 프로필 URL, 접속 국가, IP, 모델, 디바이스 ID, 가입일, 마지막 로그인 날짜 등 기능 확인과 커스텀 필드 및 노트 기능 제공
4. 사용자 정보를 수정 하려면 항목을 수정한 후 **\[저장]** 버튼을 클릭해 주십시오.

### 사용자 탈퇴 <a href="#undefined" id="undefined"></a>

특정 사용자을 탈퇴시키는 방법은 다음과 같습니다.

1. &#x20;Game Chat 대시보드에서 **유저** > **유저들** 메뉴를 클릭해 주십시오.
2. 탈퇴시킬 사용자 ID를 클릭해 주십시오.
3. 화면에 사용자 상세 정보가 나타나면 **\[삭제]** 버튼을 클릭해 주십시오.
4. 팝업 확인 창이 나타나면 **\[삭제]** 버튼을 클릭해 주십시오.

### 사용자 검색 <a href="#undefined" id="undefined"></a>

Game Chat 대시보드에 등록된 사용자을 검색하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **유저** > **유저들** 메뉴를 클릭해 주십시오.
2. 검색 조건을 설정하고 **\[검색]** 버튼을 클릭해 주십시오.
   * 사용자 ID, 이름, IP를 조건으로 검색 가능
3. 검색 결과를 확인해 주십시오.

### 사용자 이용 정지 <a href="#undefined" id="undefined"></a>

특정 사용자가 일정 기간 동안 채팅을 사용할 수 없도록 설정할 수 있습니다. 정지된 유저들 메뉴에서는 이용 정지 중인 사용자를 확인하고 검색할 수 있습니다.\
특정 사용자의 채팅 이용을 정지하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **유저** > **정지된 유저들** 메뉴를 클릭해 주십시오.
2. 우측에 있는 **\[추가]** 버튼을 클릭해 주십시오.
3. 추가 창이 나타나면 유저 아이디를 검색해서 일시정지나 영구정지, 기본언어를 설정할 수 있습니다.
4. 이용 정지하려는 사용자를 모든 채널에서도 내보내려면 **모든 채팅에서 나가기** 체크 박스를 클릭해 주십시오.
5. 유저 ID와 이용 정지 사유, 이용 정지 기간을 설정하고 **\[추가]** 버튼을 클릭해 주십시오.

## 채팅 <a href="#undefined" id="undefined"></a>

채팅 메뉴에서는 채널을 확인하고 채팅 메시지를 전송할 수 있습니다.

### 채팅 채널 추가 <a href="#undefined" id="undefined"></a>

새로운 채팅 채널을 추가하는 방법은 다음과 같습니다

1. Game Chat 대시보드에서 **채널** 메뉴를 클릭해 주십시오.
2. **\[추가]** 버튼을 클릭해 주십시오.
3. 채널은 **공개채팅**과 **비공개채팅**을 구분해서 생성할 수 있습니다.\
   (**공개**는 최대 200,000명이 참여 가능한 채팅 채널이며 **비공개**는 1:N으로 프라이빗한 채널을 생성할 수 있습니다.)
4. 채널 이름과 고유 아이디를 입력하고 **\[추가]** 버튼을 클릭해 주십시오.
   * 고유 아이디 입력 시 SDK에서 해당 값을 이용하여 채널에 접속 가능
   * 푸시, 자동번역을 선택할 수 있으며 연동에서 추가 상품을 연동하여 사용할 수 있습니다.
5. 채널이 생성 되었는지 확인해 주십시오.

### 채팅 채널 설정 <a href="#undefined" id="undefined"></a>

특정 채팅 채널에 참여 중인 사용자를 확인하거나 채널 정보를 수정하거나 삭제하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **채널** 메뉴를 클릭해 주십시오.
2. 채널을 선택한 후, 채널 화면 우측 상단에 있는 **...** 아이콘를 클릭해 주십시오.
3. 컨텍스트 메뉴가 나타나면 원하는 작업을 선택해 주십시오.
   * **구독자들**: 채팅 채널에 참여한 사용자 목록을 확인하려면 클릭
   * **수정**: 채팅 채널 정보를 수정하려면 클릭
   * **삭제**: 채팅 채널을 삭제하려면 클릭

### 이미지 메시지 전송 <a href="#undefined" id="undefined"></a>

특정 채팅 채널에 참여 중인 사용자를 확인하거나 채널 정보를 수정하거나 삭제하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **채널** 메뉴를 클릭해 주십시오.
2. 채널을 선택한 후, 채팅메시지 작성 필드 우측에 있는 파일첨부 아이콘을 클릭해 주십시오.

> 참고
>
> 지원 이미지 타입: image/bmp, image/gif, image/jpeg, image/png, image/webp, image/heic, image/heic-sequence, image/heif, image/heif-sequence, image/svg+xml

## 메세지 <a href="#undefined" id="undefined"></a>

메세지 메뉴에서는 프로젝트의 모든 채널에서 주고 받은 메세지를 확인하고 검색할 수 있습니다. 아이디, 닉네임, 메시지, 채널 ID, 메시지 발송 일시를 기준으로 검색할 수 있고 메시지 목록을 CSV 파일로 다운로드할 수 있습니다.

### 메세지 검색 및 메세지 상세 정보 확인 <a href="#undefined" id="undefined"></a>

메세지의 상세 정보를 확인하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **메세지** 메뉴를 클릭해 주십시오.
2. 검색 조건을 설정하고 **\[검색]** 버튼을 클릭해 주십시오.
   * 발신자 ID, 발신자 이름, 채팅 ID, 닉네임, 메시지 내용을 조건으로 검색 가능
3. 상세 정보를 확인할 메시지를 클릭해 주십시오.
4. 해당 메시지가 등록된 유저 아이디, 이름, 채팅 아이디, 메시지 아이디, 메세지 내용, 생성일을 확인할 수 있습니다.

### 메세지 삭제 <a href="#undefined" id="undefined"></a>

특정 메세지를 검색하여 삭제할 수 있습니다. 검색 메뉴에서 삭제한 메시지는 해당 채팅 채널에서도 삭제됩니다.

1. Game Chat 대시보드에서 **메세지**을 클릭해 주십시오.
2. 삭제할 메시지를 클릭해 주십시오.
3. 메세지 보기 화면에서 삭제를 선택하여 **\[삭제]** 버튼을 클릭해 주십시오.

## 아카이브 <a href="#undefined" id="undefined"></a>

아카이브 메뉴에서는 프로젝트의 모든 채널에서 주고 받은 이미지 및 파일을 확인하고 검색할 수 있습니다. 사용여부와 발신자, 채팅아이디, 미리보기, 파일이름, 포맷, 크기, 전송횟수, 생성일, 만기일을 확인할 수 있습니다. 특정 파일을 선택하여 사용자를 사용정지하거나, 삭제할 수 있습니다.

## 푸시 알림 <a href="#undefined" id="undefined"></a>

푸시 알림은 앱 퍼블리셔가 보내는 모바일 기기에 표시되는 메시지입니다. 이러한 알림은 사용자가 앱이나 기기를 활성적으로 사용하든 상관없이 언제든지 전달될 수 있습니다. 몇 가지 주요 사항을 확인해 주십시오.

* JSON의 크기인 메시지 페이로드는 4KB로 제한됩니다.
* 국외에 알림을 보낼 때 예약된 시간을 기준으로 각 국가의 현지 시간에 따라 전달됩니다.\
  푸시 알림을 설정하고 발송된 푸시알림 목록을 확인 할 수 있습니다.

## 설정 <a href="#undefined" id="undefined"></a>

설정 메뉴에서는 Game Chat 프로젝트 정보를 설정하거나 채팅 금칙어 및 메시지 자동 번역 여부를 설정하는 방법, 회원 정보를 변경하거나 특정 회원에게 관리자 권한을 부여할 수 있습니다.

### 일반 <a href="#undefined" id="undefined"></a>

프로젝트 이름, ID, API 키 확인 및 메세지 최대길이, 피속어 필터 제한유형 설정을 할 수 있습니다.

1. 프로젝트 ID를 확인하고 복사할 수 있습니다.
2. API 키를 복사하거나 재생성 할 수 있습니다.
3. 메시지 최대길이를 설정합니다.
4. 비속어 필터 제한 유형을 선택해 주십시오.
   * 사용안함: 금칙어로 지정된 단어도 그대로 노출
   * \*로 대체: 금칙어로 지정된 단어는 채팅창에 \*로 노출
   * 메시지 전송 차단: 금칙어로 지정된 단어는 전송하지 않음
5. 비속어 예시를 자동으로 가져오려면 **\[기본 필터 사용]** 버튼을 클릭해 주십시오.

### 보안 <a href="#undefined" id="undefined"></a>

생성한 프로젝트의 보안과 허용 IP, 이미지 타입을 지정할 수 있습니다.

1. Game Chat 대시보드에서 **설정 > 보안**을 클릭해 주십시오.
2. 보안의 필요한 설정을 지정해 주십시오.
   * 토큰 인증: 특정 토큰으로 액세스 권한 부여
   * 허용된 IP를 추가하거나 삭제
   * 허용된 이미지 타입을 추가하거나 삭제
   * 업로드 사이즈 제한
   * 다운로드 만료 시간 지정
   * 허용된 액세스 타입 설정
   * 화이트 리스트 지정 및 삭제
3. **\[저장]** 버튼을 클릭해 주십시오.

### 연동

생성한 프로젝트에 Papago,Object Storage 등 다양한 상품의 연동상태 또는 연동을 설정할 수 있습니다.

1. Game Chat 대시보드엣보드에서 **설정 > 연동**을 클릭해 주십시오.
2. 연동의 필요한 상품명을 선택해 주십시오.
3. 연동 상품별로 연동여부와 입력필드를 입력하고 **저장** 버튼을 클릭해 주십시오.

> 참고
>
> Papago Translation 연동을 위한 Client ID와 Client Secret을 확인하는 방법은 [Papago Translation 사용 가이드](https://guide.ncloud-docs.com/docs/papagotranslation-overview)를 참조해 주십시오.

### 관리자 <a href="#undefined" id="undefined"></a>

Game Chat 프로젝트의 관리자 정보를 확인하고 수정할 수 있습니다. 단, 현재 접속 중인 계정의 상세 정보는 계정 정보의 프로필 수정 메뉴에서 수정할 수 있습니다.\
관리자 정보를 수정하는 방법은 다음과 같습니다.

1. Game Chat 대시보드에서 **설정** > **관리자** 메뉴를 클릭해 주십시오.
2. 정보를 수정할 회원을 클릭해 주십시오.,
3. 회원 이름, 새로운 비밀번호, 사용여부 상태를 설정하고 **\[저장]** 버튼을 클릭해 주십시오.
4. 특정 회원을 대시보드의 관리자로 설정하려면 관리자 권한 아이콘을 활성화 상태로 변경하고 **\[저장]** 버튼을 클릭해 주십시오.
5. 회원 정보를 삭제하려면 **\[삭제]** 버튼을 클릭해 주십시오.

## 활동 및 파일 <a href="#undefined" id="undefined"></a>

활동 및 파일 메뉴에서는 검색 메뉴에서 csv로 내보내기한 결과를 30일 간 다운로드할 수 있습니다.

## 계정 정보 <a href="#undefined" id="undefined"></a>

우측상단의 사용자 아이콘에서는 계정 정보를 수정하고 로그아웃할 수 있습니다.

### 프로필 수정 <a href="#undefined" id="undefined"></a>

로그인한 계정의 정보를 확인하고 이름과 프로필 URL, 대시보드 시간대를 변경할 수 있습니다. 프로필 URL은 채팅 시 사용됩니다.\
프로필 정보를 수정하는 방법은 다음과 같습니다.

1. Game Chat 대시보드 우측 상단의 사용자 아이콘을 클릭한 후 프로필 수정 메뉴를 클릭해 주십시오.
2. 프로필 수정 메뉴에서 이름 또는 프로필 URL, 시간대를 설정하고 **\[저장]** 버튼을 클릭해 주십시오.

### 비밀번호 변경 <a href="#undefined" id="undefined"></a>

비밀번호를 변경하는 방법은 다음과 같습니다.

1. Game Chat 대시보드 우측 상단의 사용자 아이콘을 클릭한 후 **프로필 수정** 메뉴를 클릭해 주십시오.
2. 비밀번호 변경 메뉴를 클릭한 후, 현재 비밀 번호와 변경할 비밀번호를 입력하고 **\[저장]** 버튼을 클릭해 주십시오.

## 대시보드 로그아웃 <a href="#undefined" id="undefined"></a>

Game Chat 대시보드에서 로그아웃하려면 Game Chat 대시보드 우측 상단의 사용자 아이콘을 클릭한 후 **로그아웃**을 클릭해 주십시오.


# Unity SDK 설치

Unity SDK 사용에 대해 안내합니다. SDK를 설치하고 환경을 구성함으로써 채팅과 대시보드를 연동할 수 있습니다.

## 요구 사양

* 최소 사양: 2020 이상 (하위 버전의 Unity 지원이 필요할 경우 '<cs@nbase.io>' 메일로 문의해 주십시오.)
* 2020.3.X / 2021.1.X 버전의 Unity 에디터 사용자는 2020.3.15f2 이상 / 2021.1.16f1 이상 버전을 사용해 주십시오(AAB 버전 빌드 시 Unity 에디터 버그 수정 버전).

## SDK 설치 및 환경 구성

Game Chat Unity SDK를 다운로드하고 Unity에서 프로젝트를 구성하는 방법은 다음과 같습니다.

1. GitHub 리포지스토리의 페이지에서 **다운로드**해 주십시오.
2. 샘플 또한 GitHub 리포지스토리의 페이지에서 **다운로드**해 주십시오.
3. Unity 프로그램을 실행한 후 프로젝트를 생성해 주십시오.
4. Unity에서 **Assets** > **Import Package** > **Custom Package...** 메뉴를 차례대로 클릭해 주십시오.
5. 대시보드에서 다운로드한 'GameChat.Unity.SDK.\[version].unitypackage' 파일을 불러와 주십시오.
6. 패키지에 있는 모든 파일을 선택한 후 **\[Import]** 버튼을 클릭해 주십시오.
7. 프로젝트를 저장해 주십시오.

<br>


# 초기화

## 초기화

Game Chat을 사용하기 전에 초기화해야 합니다. \
대시보드에서 확인한 프로젝트 ID를 추가해 주십시오. Game Chat을 초기화하는 방법은 다음과 같습니다.

1. 대시보드에 접속하여 설정 메뉴에서 프로젝트 아이디를 확인해 주십시오.
2. 인스턴스를 초기화하려면 아래 코드를 사용해 주십시오.

* NBaseSDK 모듈을 임포트합니다.

```csharp
using NBaseSDK;
```

* NBaseSDK Chat 인스턴스를 생성합니다.

```csharp
BaseSDK.Chat nc = NBaseSDK.Chat.GetInstance();
```

* 프로젝트 ID와 리전, 언어 코드로 Ncloud Chat을 초기화합니다.

```csharp
nc.initialize([PROJECT_ID], [REGION], [LANGUAGE]);
```

<table><thead><tr><th width="151">ID</th><th width="86">Type</th><th width="381">Description</th><th>Required</th></tr></thead><tbody><tr><td>PROJECT_ID</td><td>string</td><td>ID (Game Chat 대시보드 Project ID)</td><td>O</td></tr><tr><td>REGION</td><td>string</td><td>리전 (별도로 사용하는 경우가 아니라면 "kr"으로 사용)</td><td>O</td></tr><tr><td>LANGUAGE</td><td>string</td><td>언어 코드 ("en", "ko" 등)</td><td>O</td></tr></tbody></table>

## 오류 처리

* 기본적인 오류 처리는 아래와 같이 try ... catch 안에 코드를 추가합니다.

```csharp
try
{
    // 오류가 발생할 수 있는 코드를 이곳에 작성합니다.
    ...
}
catch (InvalidOperationException e)
{
    // 특정 오류 타입에 대한 처리를 이곳에 작성합니다.
    Console.WriteLine("InvalidOperationException: {0}", e.Message);
}
catch(Exception e)
{
    // 일반적인 오류 처리를 이곳에 작성합니다.
    Console.WriteLine("Error: {0}", e.Message);
}
```


# 로그인

## 로그인

초기화 완료 후 사용자명, 이름, 프로필 이미지 주소(옵션)를 입력하여 접속 할 수 있습니다.

### 접속

```csharp
await nc.Connect(
    id: [USERNAME],
    name: [NAME],
    profile: [PROFILE_URL],
    customField: [CUSTOM_FIELD],
    token: [TOKEN]
);
```

<table><thead><tr><th width="233">ID</th><th width="126">Type</th><th width="249">Description</th><th>Required</th></tr></thead><tbody><tr><td>USERNAME</td><td>string</td><td>아이디</td><td>O</td></tr><tr><td>NAME</td><td>string</td><td>닉네임</td><td>X</td></tr><tr><td>PROFILE_URL</td><td>string</td><td>프로필 주소 URL</td><td>X</td></tr><tr><td>LANGUAGE</td><td>string</td><td>언어코드</td><td>X</td></tr><tr><td>CUSTOM_FIELD</td><td>string</td><td>사용자 정의 필드</td><td>X</td></tr><tr><td>TOKEN</td><td>string</td><td>토큰 값</td><td>X</td></tr></tbody></table>

> 참고
>
> * 로그인 시 보안을 위해 API로 토큰을 발급받는 것을 권장합니다.
> * [API DOCS TOKEN](https://api.ncloud-docs.com/docs/bizapp-token-issuance) API를 통해 발급된 토큰을 사용할 수 있습니다.
> * 토큰 방식을 사용하지 않으실 경우 **대시보드 > 보안설정 > Token 인증**을 **사용 안함**으로 설정해 주십시오.

### 접속 종료

연결된 Game Chat 서버와의 연결을 해제하려면 아래 코드를 사용해 주십시오.

```csharp
await nc.Disconnect();
```

### 사용자 정보 <a href="#undefined" id="undefined"></a>

* Member Data Class

<table><thead><tr><th width="181">ID</th><th width="216">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>사용자 ID</td></tr><tr><td>name</td><td>string</td><td>사용자 이름</td></tr><tr><td>profile</td><td>string</td><td>이미지 주소</td></tr></tbody></table>

#### **사용자 정보 가져오기**

특정 아이디에 대한 정보를 가져옵니다(보안상 닉네임만 전달됩니다).

```csharp
Hashtable filter = new Hashtable
{
    { "id", [USER_ID] }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var users = await nc.getUsers(filter, sort, option);
```

* Parameters

<table><thead><tr><th width="111">ID</th><th width="93">Type</th><th width="440">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>쿼리를 필터 모든 필드에 대해서 검색 가능</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>소트 하고자 하는 필드의 필터 정의 (오름차순 "1", 내림차순 "-1")</td><td>X</td></tr><tr><td>option</td><td>object</td><td>옵션이 존재할 경우 아래 참고</td><td>X</td></tr></tbody></table>

* Options

<table><thead><tr><th width="207">ID</th><th width="208">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>시작 offset</td></tr><tr><td>per_page</td><td>number</td><td>리턴하는 개수(최대 100개)</td></tr></tbody></table>


# 채널

## 채널

Game Chat에서 채널은 사용자들이 그룹으로 소통할 수 있는 가상의 공간입니다. \
채널을 통해 사용자는 특정 주제나 목적에 맞게 정보를 공유하고, 팀워크를 강화하며, 커뮤니케이션을 조직화할 수 있습니다. \
채널은 업무 효율을 높이고, 특정 그룹 내 커뮤니케이션을 중앙집중화하여 관리할 수 있는 유용한 도구입니다. \
아래는 Game Chat의 채널 기능에 대한 자세한 설명입니다.

### 채널의 주요 기능 <a href="#undefined" id="undefined"></a>

1. **그룹 커뮤니케이션**: 채널을 생성하여 특정 그룹의 멤버들과 소통할 수 있습니다. 이는 프로젝트 팀, 부서, 클럽 등 다양한 형태의 그룹에 적합합니다.
2. **메시지 및 파일 공유**: 채널 내에서는 텍스트 메시지, 이미지, 동영상, 문서 등 다양한 형태의 파일을 쉽게 공유할 수 있습니다.
3. **실시간 업데이트**: 채널 내의 모든 활동은 실시간으로 업데이트되어, 모든 참여자가 최신의 정보를 접할 수 있습니다.
4. **관리자 제어**: 채널의 생성자 또는 관리자는 채널 설정을 변경하거나 사용자를 추가/제거할 권한을 가집니다.
5. **통화 및 화상회의 기능**: 일부 채널에서는 음성 통화나 화상 회의를 지원하여, 멤버 간의 대화를 더욱 효과적으로 할 수 있습니다.
6. **알림 설정**: 사용자는 채널별로 알림을 설정하여 중요한 메시지를 놓치지 않도록 할 수 있습니다.
7. **검색 기능**: 채널 내의 대화나 파일을 쉽게 검색할 수 있어, 필요한 정보를 빠르게 찾을 수 있습니다.

### 채널 관리 <a href="#undefined" id="undefined"></a>

* **채널 생성**: 사용자는 목적에 맞는 채널을 새로 생성할 수 있으며, 채널명, 설명, 멤버 등의 정보를 설정할 수 있습니다.
* **채널 초대**: 채널의 관리자는 다른 사용자를 채널에 초대할 수 있습니다. 초대받은 사용자는 초대를 수락하거나 거절할 수 있습니다.
* **멤버 관리**: 관리자는 채널 멤버의 권한을 설정하거나 멤버를 채널에서 제거할 수 있습니다.

### 보안 <a href="#undefined" id="undefined"></a>

* **데이터 보안**: 채널 내의 모든 데이터는 암호화되어 전송되며, 서버에 안전하게 저장됩니다.
* **개인 정보 보호**: 채널 내에서 공유되는 정보는 채널 멤버들 사이에서만 접근 가능하며, 외부에 유출되지 않도록 보호됩니다.

Game Chat의 채널 기능을 활용하면 조직 내 또는 개인적인 소통을 원활하게 하고, 정보를 효과적으로 관리할 수 있습니다. 이러한 특성은 특히 대규모 조직이나 다양한 프로젝트를 관리할 때 매우 유용합니다.

### 채널 생성 <a href="#undefined" id="undefined"></a>

모든 대화는 채널을 생성해야 하며 채널에 참여해야 정상적으로 채팅을 할 수 있습니다. \
아래는 채널을 생성하고 구독하는 방법을 안내합니다.

```csharp
await nc.createChannel(new NBaseSDK.Channel
{
    name = "New Channel",
    type =[TYPE],    // PUBLIC or PRIVATE
    customField = [CustomField]
});
```

<table><thead><tr><th width="175">ID</th><th width="128">Type</th><th width="350">Description</th><th>Required</th></tr></thead><tbody><tr><td>NAME</td><td>string</td><td>채널 이름</td><td>O</td></tr><tr><td>TYPE</td><td>string</td><td>채널 종류 ( PUBLIC or PRIVATE )</td><td>O</td></tr><tr><td>UniqueID</td><td>string</td><td>고유한 ID</td><td>X</td></tr><tr><td>push</td><td>boolean</td><td>푸시 알림 여부</td><td>X</td></tr><tr><td>linkUrl</td><td>string</td><td>링크 여부</td><td>X</td></tr><tr><td>imageUrl</td><td>string</td><td>링크 여부</td><td>X</td></tr><tr><td>integrationId</td><td>string</td><td>연동 기능 (번역, 보이스 등)</td><td>X</td></tr><tr><td>disabled</td><td>string</td><td>채널 사용여부</td><td>X</td></tr><tr><td>members</td><td>array</td><td>PRIVATE 일 경우 참여 가능한 아이디</td><td>X</td></tr><tr><td>CustomField</td><td>string</td><td>사용자 정의 필드, JSON String으로 넣으면 다양하게 활용 가능</td><td>X</td></tr></tbody></table>

> 참고
>
> 보안을 위해서 클라이언트에서 채널을 생성하는 것보다는 서버를 통한 채널을 생성을 추천해 드립니다.

### 채널 구독 <a href="#undefined" id="undefined"></a>

원하는 채널에 가입(방 참여)합니다. 참여된 채널에는 구독 해제할 때까지 재접속 시에도 자동으로 참여하게 됩니다.

```csharp
Hashtable option = new Hashtable
{
    { "language", "en" }    // 자동 번역시 필요한 옵션 이외에도 다양한 옵션 추가 가능합니다.
};
await nc.subscribe([CHANNEL_ID], option);
```

### 채널 구독 해제 <a href="#undefined" id="undefined"></a>

해당 채널에 대한 가입을 해지합니다. 해당 채널에서 더 이상 메시지를 받을 수 없습니다.

```csharp
await nc.unsubscribe([CHANNEL_ID]);
```

### 참여자 리스트 <a href="#undefined" id="undefined"></a>

(특정 채널에 대해) 참여자 리스트를 가져올 수 있습니다.

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", channelId }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var subscriptions = await nc.getSubscriptions(filter, sort, option);
foreach (var subscription in subscriptions.edges)
{
    string id = subscription.node.id.ToString();
    Console.WriteLine("[CloudChatSample] id={0}", id);
}
```

* Parameters

<table><thead><tr><th width="147">ID</th><th width="125">Type</th><th>Description</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>쿼리를 필터 모든 필드에 대해서 검색 가능</td></tr><tr><td>sort</td><td>object</td><td>소트하고자 하는 필드의 필터 정의 (오름차순 "1", 내림차순 "-1")</td></tr><tr><td>option</td><td>object</td><td>옵션이 존재할 경우 아래 참고</td></tr></tbody></table>

* Options

<table><thead><tr><th width="152">ID</th><th width="124">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>시작 offset</td></tr><tr><td>per_page</td><td>number</td><td>리턴하는 개수(최대 100개)</td></tr></tbody></table>

#### **응용편**

특정 채널에 온라인 접속 상태인 접속자 목록만 가져오려면 filter에 online을 true로 추가해 주십시오.

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", [CHANNEL_ID] },
    { "online" , true}
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};

var subscriptions = await nc.getSubscriptions(filter, sort, option);

```

#### **채널 구독**

* Subscription Data Class

  <table><thead><tr><th width="215">ID</th><th width="153">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>유니크 아이디</td></tr><tr><td>channel_id</td><td>string</td><td>채널 아이디</td></tr><tr><td>user_id</td><td>string</td><td>유저 고유 아이디</td></tr><tr><td>created_at</td><td>string</td><td>생성 일자</td></tr><tr><td>online</td><td>boolean</td><td>온라인 여부</td></tr><tr><td>push</td><td>boolean</td><td>푸시 참여 여부</td></tr><tr><td>language</td><td>string</td><td>접속 언어</td></tr><tr><td>channel</td><td>string</td><td>채널 정보</td></tr><tr><td>mark.user_id</td><td>string</td><td>마지막 메시지 보낸 사용자</td></tr><tr><td>mark.message_id</td><td>string</td><td>마지막 메시지 아이디</td></tr><tr><td>mark.sort_id</td><td>string</td><td>마지막 메시지 정렬 ID</td></tr><tr><td>mark.unread</td><td>string</td><td>마지막 메시지 이후 안읽은 메시지 갯수</td></tr></tbody></table>

### 채널 정보 <a href="#undefined" id="undefined"></a>

* Channel Data Class

<table><thead><tr><th width="243">ID</th><th width="148">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>채널 아이디 (unique)</td></tr><tr><td>project_id</td><td>string</td><td>프로젝트 아이디</td></tr><tr><td>unique_id</td><td>string</td><td>개발사에서 설정 가능한 채널 아이디 (unique)</td></tr><tr><td>name</td><td>string</td><td>채널 이름</td></tr><tr><td>user_id</td><td>string</td><td>(채널을 생성한) 유저 아이디</td></tr><tr><td>unique_id</td><td>string</td><td>채널 고유 ID</td></tr><tr><td>default_lang</td><td>string</td><td>기본 언어</td></tr><tr><td>lang</td><td>string</td><td>현재 접속 중인 이용자의 언어</td></tr><tr><td>members</td><td>string</td><td>Private일 경우 참여된 사용자 목록</td></tr><tr><td>last_message</td><td>array</td><td>마지막 메시지 정보 [MessageType] 참고</td></tr><tr><td>push</td><td>boolean</td><td>푸시 메시지 지원 여부 (Private 채널일 경우)</td></tr><tr><td>state</td><td>boolean</td><td>채널 상태</td></tr><tr><td>customField</td><td>string</td><td>사용자 정의 데이터</td></tr><tr><td>created_at</td><td>string</td><td>생성 일자</td></tr><tr><td>updated_at</td><td>string</td><td>갱신 일자</td></tr></tbody></table>

#### **채널 데이터 가져오기**

프로젝트의 채널 데이터를 목록 형태로 가져오려면 아래 코드를 사용해 주십시오.

```csharp
Hashtable filter = new Hashtable
{
    { "state", true }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var channels = await nc.getChannels(filter,sort,option);
foreach (var channel in channels.edges)
{
    string id = channel.node.id.ToString();
    Console.WriteLine("[CloudChatSample] id={0}", id);
}
```

* Parameters

<table><thead><tr><th width="123">ID</th><th width="90">Type</th><th width="393">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>쿼리를 필터 모든 필드에 대해서 검색 가능</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>소트하고자 하는 필드의 필터 정의</td><td>X</td></tr><tr><td>option</td><td>object</td><td>옵션이 존재할 경우 아래를 참고</td><td>X</td></tr></tbody></table>

* Options

<table><thead><tr><th width="170">ID</th><th width="167">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>시작 offset</td></tr><tr><td>per_page</td><td>number</td><td>리턴하는 개수(최대 100개)</td></tr></tbody></table>

### 개별 채널

개별 채널에 대한 정보를 가져올 수 있습니다.

```csharp
Channel channel = await nc.getChannel(id);
```

### 채널 내 사용자 초대 <a href="#undefined" id="undefined"></a>

PRIVATE 채널의 경우 참여하고자 하는 사용자를 초대합니다.

```csharp
await nc.addUsers(newChannelId, new string[] { "ID", "ID" });
```

### 채널 내 사용자 삭제 <a href="#undefined" id="undefined"></a>

PRIVATE 채널의 경우 참여된 사용자를 삭제합니다.

```csharp
await nc.removeUsers(channelId, new string[] { "ID", "ID" });
```

### 채널 내 사용자 차단 <a href="#undefined" id="undefined"></a>

채널 내에 사용자를 차단합니다. 채널을 생성한 권한을 가지고 있는 유저나 전체 관리자만 사용이 가능합니다.

```csharp
Hashtable option = new Hashtable
{
    { "timeout", [종료시간(초)] },
    { "reason", [차단사유] }
};
await nc.banUser(channelId, userId, options);
```

* Options Data Class

<table><thead><tr><th width="195">ID</th><th width="186">Type</th><th>Description</th></tr></thead><tbody><tr><td>timeout</td><td>string</td><td>차단 시간 (seconds)</td></tr><tr><td>reason</td><td>string</td><td>차단 사유</td></tr></tbody></table>

### 채널 내 사용자 차단 해제 <a href="#undefined" id="undefined"></a>

채널 내에 차단한 사용자의 차단을 해제합니다. 채널을 생성한 권한을 가지고 있는 유저나 전체 관리자만 사용이 가능합니다.

```csharp
await nc.unbanUser(channelId, userId);
```

### 채널 삭제 <a href="#undefined" id="undefined"></a>

해당 채널을 삭제합니다 (한 개 또는 여러 개를 삭제할 수 있습니다).

```csharp
Channel channel = await nc.deleteChannel([CHANNEL_ID]);
```

### 채널 수정 <a href="#undefined" id="undefined"></a>

채널 정보를 업데이트합니다.

```csharp
Channel channel = await nc.updateChannel([CHANNEL_ID],new NBaseSDK.Channel
{
    name = "Update Channel",
    type =[TYPE],    // PUBLIC or PRIVATE
    customField = [CustomField]
});
```


# 메시지

## 메시지 <a href="#undefined" id="undefined"></a>

Game Chat에서 제공하는 메시지 기능은 사용자 간의 효과적인 커뮤니케이션을 지원하는 다양한 서비스를 포함합니다. 이 플랫폼은 개인 대화뿐만 아니라 그룹 대화에도 적합하며, 메시지를 보내고 받는 과정을 간편하고 신속하게 만들어 줍니다. \
다음은 Game Chat의 주요 메시지 기능과 그 특징입니다.

### 1. 즉시 메시징 <a href="#id-1" id="id-1"></a>

* **실시간 소통**: 사용자들은 실시간으로 메시지를 보내고 받을 수 있으며, 이는 커뮤니케이션의 지연을 최소화합니다.
* **다중 장치 지원**: 사용자는 스마트폰, 태블릿, PC 등 다양한 장치에서 메시지를 주고받을 수 있습니다.

### 2. 그룹 채팅 <a href="#id-2" id="id-2"></a>

* **다수의 참여자**: 사용자는 여러 명이 참여하는 그룹 채팅을 생성하여 정보를 공유하고 팀 내 소통을 용이하게 할 수 있습니다.
* **채널 관리**: 관리자는 그룹 채팅을 통해 멤버를 추가하거나 제거하고, 그룹의 설정을 조정할 수 있습니다.

### 3. 파일 공유 <a href="#id-3" id="id-3"></a>

* **다양한 파일 형식 지원**: 텍스트, 이미지, 비디오, 문서 등 다양한 형식의 파일을 채팅을 통해 손쉽게 공유할 수 있습니다.
* **안전한 파일 보관**: Ncloud Chat은 고객님 소유의 Object Storage 내에 파일을 저장관리하기 때문에 정보의 외부 유출을 방지합니다.

### 4. 메시지 검색 <a href="#id-4" id="id-4"></a>

* **키워드 검색**: 채팅 내에서 특정 키워드를 사용하여 과거의 대화 내용을 검색할 수 있습니다.
* **고급 필터 옵션**: 날짜, 참여자, 파일 유형 등 다양한 필터를 적용하여 원하는 메시지를 빠르게 찾을 수 있습니다.

### 5. 알림 및 알림 조정 <a href="#id-5" id="id-5"></a>

* **푸시 알림**: 새 메시지나 중요한 업데이트가 있을 때 사용자에게 알림을 보내어 정보의 누락을 방지합니다.
* **알림 설정**: 사용자는 알림의 종류와 빈도를 조정할 수 있어, 원하는 방식으로 정보를 받아볼 수 있습니다.

### 6. 보안과 개인 정보 보호 <a href="#id-6" id="id-6"></a>

* **데이터 암호화**: 모든 메시지는 전송과 저장 과정에서 암호화되어 외부로부터의 데이터 유출을 방지합니다.
* **개인 정보 보호**: 사용자의 개인 정보와 대화 내용은 엄격하게 보호되며, 사용자의 동의 없이 제3자에게 공개되지 않습니다.

Game Chat의 메시지 기능은 사용자의 커뮤니케이션을 원활하고 효율적으로 만들어 주며, 업무와 일상 생활에서 중요한 역할을 합니다. 이러한 기능들은 사용자가 더욱 쉽게 소통할 수 있도록 돕고, 팀워크를 강화하는 데 크게 기여합니다.

## 메시지 전달 <a href="#undefined" id="undefined"></a>

채널을 생성하고 가입했다면 아래와 같이 호출하여 새로운 메시지를 전달합니다.

```csharp
const message = 'Hello !!!';
await nc.sendMessage(
        channelId: CHANNEL_ID, 
        type:"text", 
        content: message
);


// 메시지에 답글을 보내는 경우
await nc.sendMessage(
        channelId: CHANNEL_ID, 
        type:"text", 
        content: message, 
        parentMessageId: [MESSAGE_ID]
        );

// 메시지에 자동 번역을 해야하는 경우
await nc.sendMessage(
        channelId: CHANNEL_ID, 
        type:"text", 
        content: message, 
        translate: true
        );

// 신규 메시지에서 아래과 같이 parent_message 로 부모 메시지의 내용을 보강하여 전달합니다.
{
    "id": "message_id",
    "text": "Message",
    "parent_message_id": "first_message_id",
    "parent_message": { 
        "id": "message_id", 
        "text": "message_name",
        "sender" : {
            "id" : "Sender",
             "name" : "Sender Nickname",
             "profile" : "profile url"
        }
    }
}
```

> 참고
>
> message는 JSON 형태로 발송/수신하시면 다양한 사용자 정의 값을 사용할 수 있습니다.

```csharp
Hashtable messageArray = new Hashtable
{
    { "channel_id", "channelId" },
    { "state", 1 },
    { "desc" , "Desc" }
};
// 메시지를 일반 텍스트로 변환 합니다.
const jsonString = JsonConvert.SerializeObject(messageArray);
// 받은 메시지를 Array 로 변환합니다.
Hashtable hashtable = JsonConvert.DeserializeObject<Hashtable>(jsonString);
```

<table><thead><tr><th width="195">ID</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>채널 아이디</td></tr><tr><td>type</td><td>string</td><td>보내는 메시지 종류(text, image)</td></tr><tr><td>MESSAGE</td><td>string</td><td>전송 메시지 텍스트, JSON String을 활용하면 다양하게 사용 가능</td></tr><tr><td>MENTIONS</td><td>array</td><td>멘션할 사용자 ID</td></tr></tbody></table>

* Express Message 사용하기: 오직 고속으로 메시지를 발송하기 위한 함수입니다. \
  시간 지연이 걸릴 수 있는 부분을 모두 스킵하여 기존 대비 10배 빠르게 메시지 전송이 가능합니다. 일반 sendMessage와 차이점은 아래와 같습니다.

<table><thead><tr><th width="209">Function</th><th width="165">Description</th><th>필터링</th><th>차단</th><th>번역</th></tr></thead><tbody><tr><td>sendMessage</td><td>일반 메시지 발송</td><td>O</td><td>O</td><td>O</td></tr><tr><td>sendExpressMessage</td><td>빠른 메시지 발송</td><td>X</td><td>X</td><td>X</td></tr></tbody></table>

게임 내에서 실시간 PvP를 제작하거나 고속의 Broadcasting이 필요한 모든 서비스에 이용이 가능합니다.

## 파일 업로드 <a href="#undefined" id="undefined"></a>

* 특정 채널로 파일을 전송할 수 있습니다.
* 대시보드 > 설정 > 보안 > 허용된 파일 타입만 업로드할 수 있습니다.

```csharp
await nc.sendFile([CHANNEL_ID],file);
```

| ID          | Type   | Description |
| ----------- | ------ | ----------- |
| CHANNEL\_ID | string | 채널 아이디      |
| file        | string | 파일 정보       |

> 참고
>
> * 오브젝트 스토리지가 활성화되어 있어야 합니다.
> * [Object Storage](https://www.ncloud.com/product/storage/objectStorage) 상품과 연동한 후에 사용할 수 있습니다.
> * 업로드 시 대시보드 **프로젝트 설정 > 보안설정**에 업로드 타입과 업로드 크기 등을 설정해 주십시오.
> * 지원 파일 타입: 이미지, 비디오, 문서, 압축 등의 일반적인 타입을 모두 지원하며, 추가로 지원이 필요한 확장자는 문의하기를 통해 문의 주시면 보안 검토 후 추가해 드리고 있습니다.
> * 파일 링크 활용시 Endpoint 주소는 <https://apps.ncloudchat.naverncp.com> 입니다.\
>   예) <https://apps.ncloudchat.naverncp.com/archive/\\[archiveId>]

## 메시지 정보 <a href="#undefined" id="undefined"></a>

* Message Data Class

<table><thead><tr><th width="269">ID</th><th width="170">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>아이디 (unique)</td></tr><tr><td>message_id</td><td>string</td><td>메시지 아이디</td></tr><tr><td>sort_id</td><td>string</td><td>메시지 정렬을 위한 ID</td></tr><tr><td>message_type</td><td>string</td><td>메시지 종류</td></tr><tr><td>sender.id</td><td>string</td><td>보낸 사람 ID</td></tr><tr><td>sender.name</td><td>string</td><td>보낸 사람 이름</td></tr><tr><td>sender.profile</td><td>string</td><td>보낸 사람 프로필 이미지</td></tr><tr><td>metions</td><td>string</td><td>맨션된 리스트</td></tr><tr><td>metions_everyone</td><td>string</td><td>전체 맨션 여부</td></tr><tr><td>content</td><td>string</td><td>메시지</td></tr><tr><td>created_at</td><td>string</td><td>생성 일자</td></tr><tr><td>sended_at</td><td>string</td><td>보낸 일자</td></tr></tbody></table>

### 개별 메시지 정보 <a href="#undefined" id="undefined"></a>

개별 메시지에 대한 정보를 가져올 수 있습니다.

```csharp
NBaseSDK.Message message = await nc.getMessage([CHANNEL_ID], [MESSAGE_ID]);
```

### 전체 메시지 정보 <a href="#undefined" id="undefined"></a>

전체 메시지 정보를 가져올 수 있습니다.

* MessageData data class

  | ID         | Type    | Description |
  | ---------- | ------- | ----------- |
  | totalCount | Int     | 전체 메시지 수    |
  | messages   | Message | 메시지 데이터 리스트 |

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", [CHANNEL_ID] }
};
Hashtable sort = new Hashtable
{
    { "sort_id", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var messages = await nc.getMessages(filter, sort, option);
if (messages != null)
    {
            foreach (var message in messages.edges)
        {
            string id = message.Node.message_id.ToString();
            Console.WriteLine("[CloudChatSample] id={0}", id);
        }
    }
```

* Parameters

<table><thead><tr><th width="161">ID</th><th width="113">Type</th><th width="346">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>쿼리를 필터 모든 필드에 대해서 검색 가능</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>소트하고자 하는 필드의 필터 정의</td><td>X</td></tr><tr><td>option</td><td>object</td><td>옵션이 존재할 경우 아래를 참고</td><td>X</td></tr></tbody></table>

* Filter

  <table><thead><tr><th width="220">ID</th><th width="159">Type</th><th>Description</th></tr></thead><tbody><tr><td>message_id</td><td>String</td><td>메시지 ID</td></tr><tr><td>channel_id</td><td>String</td><td>채널 ID</td></tr><tr><td>sort_id</td><td>String</td><td>정렬 ID</td></tr><tr><td>message_type</td><td>String</td><td>메시지 타입</td></tr><tr><td>embedProviders</td><td>String</td><td>임베드 제공자</td></tr><tr><td>isExpress</td><td>Boolean</td><td>즉시 메시지 여부</td></tr><tr><td>bytes</td><td>Int</td><td>메시지 바이트 크기</td></tr><tr><td>content</td><td>String</td><td>메시지 내용</td></tr><tr><td>sended_at</td><td>String</td><td>메시지 전송 시간</td></tr><tr><td>created_at</td><td>String</td><td>메시지 생성 시간</td></tr></tbody></table>

* Sort

  <table><thead><tr><th width="221">ID</th><th width="159">Type</th><th>Description</th></tr></thead><tbody><tr><td>created_at</td><td>number</td><td>생성 날짜 (오름차순 "1", 내림차순 "-1")</td></tr></tbody></table>

* Options

<table><thead><tr><th width="252">ID</th><th width="160">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>시작 offset</td></tr><tr><td>per_page</td><td>number</td><td>리턴하는 개수(최대 100개)</td></tr></tbody></table>

## 안 읽은 메시지 <a href="#undefined" id="undefined"></a>

읽지 않는 메시지 수를 리턴합니다. \
첫 번째로 markRead를 통해서 마지막 읽은 메시지의 정보를 전달합니다.

```csharp
nc.markRead([CHANNEL_ID], new NBaseSDK.MarkInput 
{
    user_id = USER_ID, 
    message_id = MESSAGE_ID,
    sort_id = SORT_ID
});
// 마크된 이후의 읽지 않은 메시지 전체 개수를 리턴합니다.
var unread = nc.unreadCount([CHANNEL_ID]);
```

<table><thead><tr><th width="219">ID</th><th width="188">Type</th><th>Description</th></tr></thead><tbody><tr><td>USER_ID</td><td>string</td><td>메시지에 포함된 user_id 입력</td></tr><tr><td>MESSAGE_ID</td><td>string</td><td>메시지에 포함된 message_id 입력</td></tr><tr><td>SORT_ID</td><td>string</td><td>메시지에 포함된 sort_id 입력</td></tr></tbody></table>

## 메시지 삭제 <a href="#undefined" id="undefined"></a>

해당 채널내에 내가 보낸 메시지를 삭제할 수 있습니다.

```csharp
await nc.deleteMessage([CHANNEL_ID], [MESSAGE_ID]);
```

* Parameters

| ID          | Type   | Description |
| ----------- | ------ | ----------- |
| CHANNEL\_ID | string | 채널 ID       |
| MESSAGE\_ID | string | 메시지 ID      |


# 이벤트

## 이벤트

Game Chat에서는 클라이언트 측에서 발생하는 다양한 이벤트를 처리할 수 있는 이벤트 리스너(Event Listener) 기능을 제공합니다. \
이 기능을 통해 사용자는 채팅 어플리케이션 내에서 일어나는 여러 상황을 실시간으로 모니터링하고 적절하게 반응할 수 있습니다. 아래는 주요 이벤트들과 이벤트 핸들링 방법에 대한 설명입니다.

## 주요 이벤트 타입 <a href="#undefined" id="undefined"></a>

1. **메시지 수신**: 새로운 메시지가 수신되었을 때 트리거됩니다.
2. **메시지 삭제**: 메시지가 삭제되었을 때 트리거됩니다.
3. **오류 메시지**: 오류가 발생했을 때 트리거됩니다.
4. **접속 성공**: 서버에 성공적으로 연결되었을 때 트리거됩니다.
5. **접속 종료**: 서버 연결이 종료되었을 때 트리거됩니다.
6. **타이핑 시작/종료**: 사용자가 타이핑을 시작하거나 종료할 때 각각 트리거됩니다.
7. **멤버 추가/제거**: 채널에 사용자가 추가되거나 제거될 때 트리거됩니다.
8. **멤버 정지/탈퇴**: 사용자가 채널에서 정지 당하거나 탈퇴할 때 트리거됩니다.

다음은 클라이언트 측에서 이벤트를 수신하는 방법입니다.

```csharp
nc.dispatcher.onMessageReceived += message =>
{
    Console.WriteLine("received a new message: ", message);
}
```

## 이벤트 핸들러 연결 및 해제 <a href="#undefined" id="undefined"></a>

이벤트 핸들러를 사용하여 다양한 이벤트를 수신하고, 필요한 로직을 구현할 수 있습니다. \
아래 코드는 각 이벤트에 대한 이벤트 핸들러 연결 및 해제 방법을 보여줍니다.

```csharp
// 메시지 수신
nc.dispatcher.onMessageReceived += e =>
{
    Console.WriteLine("onMessageReceived: ", e);
};

// 메시지 삭제
nc.dispatcher.onMessageDeleted += e =>
{
    Console.WriteLine("onMessageDeleted: ", e);
};

// 오류 메시지
nc.dispatcher.onErrorReceived += e =>
{
    Console.WriteLine("[CloudChatSample] onErrorReceived: ", e);
};

// 접속 성공
nc.dispatcher.onConnected += e =>
{
    Console.WriteLine("[CloudChatSample] Connected to server with id: {0} ", e);
};

// 접속 종료
nc.dispatcher.onDisconnected += e =>
{
    Console.WriteLine("Disconnected");
};

// 타이핑을 시작할 경우
nc.dispatcher.onStartTyping += e =>
{
    Console.WriteLine("onStartTyping: ", e);
};

// 타이핑을 종료할 경우
nc.dispatcher.onStopTyping += e =>
{
    Console.WriteLine("onStopTyping: ", e);
};

// 채널에 사용자가 구독 한 경우
nc.dispatcher.onMemberAdded += e =>
{
    Console.WriteLine("onMemberAdded: ", e);
};

// 채널에 사용자가 구독 해지 경우
nc.dispatcher.onMemberLeft += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberLeft: ", e);
};

// 채널에 사용자가 정지를 당한 경우
nc.dispatcher.onMemberBanned += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberBanned: ", e);
};

// 채널에 사용자가 탈퇴를 한 경우
nc.dispatcher.onMemberDeleted += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberDeleted: ", e);
};

nc.dispatcher.onSubscriptionUpdated += e =>
{
    Console.WriteLine("[CloudChatSample] onSubscriptionUpdated: ", e);
};
```

이벤트 리스너를 활용함으로써, Game Chat 사용자는 채팅 환경의 변화를 실시간으로 파악하고 적절히 대응할 수 있습니다.


# 친구

## 친구 관리

Game Chat은 친구를 초대하고 관리하는 기능을 제공하여 사용자 간의 소셜 네트워킹을 용이하게 합니다. \
이 시스템을 통해 사용자는 친구를 초대, 수락, 거절, 삭제하는 등의 다양한 친구 관리 작업을 수행할 수 있습니다. 아래는 친구 관리 기능의 주요 세부 사항과 각 기능의 사용 방법입니다.

## 친구 목록 <a href="#undefined" id="undefined"></a>

사용자의 친구 목록을 조회할 수 있으며, 특정 상태의 친구만 필터링하여 조회할 수도 있습니다. 목록은 페이징 옵션을 통해 관리되므로 많은 수의 사용자를 효과적으로 관리할 수 있습니다.

```csharp
Hashtable filter = new Hashtable
{
    { "status", "accepted" },
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 },
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 },
};
var friends = await nc.getFriendships(filter, sort, option);
```

* **filter**: 조회할 친구의 상태(예: "accepted")를 기준으로 필터링합니다.
* **sort**: 결과를 정렬하는 기준을 설정합니다. 여기서는 생성 시간 기준 내림차순으로 정렬합니다.
* **option**: 조회할 데이터의 범위를 설정합니다. `offset`은 데이터 시작 위치, `per_page`는 페이지당 반환할 항목 수입니다.

## 초대 <a href="#undefined" id="undefined"></a>

특정 사용자를 친구로 초대합니다. 초대받은 사용자는 이 요청을 수락하거나 거절할 수 있습니다.

```csharp
var response = await nc.requestFriend(friendId);
```

* **friendId**: 초대하고자 하는 사용자의 식별자입니다.

## 수락 <a href="#undefined" id="undefined"></a>

받은 친구 초대를 수락합니다. 이를 통해 두 사용자는 상호 친구 관계가 됩니다.

```csharp
var response = await nc.acceptFriend(friendId);
```

* **friendId**: 수락할 친구 초대의 사용자 식별자입니다.

## 리젝 <a href="#undefined" id="undefined"></a>

받은 친구 초대를 거절합니다. 이 요청을 거절하면 상대방과 친구 관계가 이루어지지 않습니다.

```csharp
var response = await nc.rejectFriend(friendId);
```

* **friendId**: 거절할 친구 초대의 사용자 식별자입니다.

## 삭제 <a href="#undefined" id="undefined"></a>

친구 목록에서 특정 사용자를 삭제합니다. 이 작업은 친구 상태나 초대 상태와 관계없이 수행될 수 있습니다.

```csharp
var response = await nc.removeFriend(friendId);
```

* **friendId**: 삭제할 친구의 사용자 식별자입니다.

친구 관리 기능은 사용자 간의 상호작용을 촉진하고, 네트워킹을 강화하는 데 중요한 역할을 합니다. 이 기능을 통해 사용자는 자신의 소셜 네트워크를 보다 쉽게 확장하고 관리할 수 있습니다.


# 푸시

## 푸시

Game Chat에서 푸시 알림은 사용자들에게 중요한 정보나 업데이트를 실시간으로 알려주는 핵심 기능입니다. \
이 푸시 알림 서비스를 통해 사용자는 앱이 백그라운드에 있거나 장치가 활성 상태가 아닐 때도 중요한 메시지를 놓치지 않게 됩니다. 아래는 Game Chat의 푸시 알림 기능에 대한 세부 설명입니다.

## 푸시 알림의 주요 기능 <a href="#undefined" id="undefined"></a>

1. **실시간 알림**: 새 메시지, 멤버 변경, 이벤트 초대 등과 같은 채팅 관련 알림을 사용자에게 즉시 전송합니다.
2. **커스터마이징 가능**: 알림의 형태와 내용을 애플리케이션의 요구 사항에 맞게 사용자 정의할 수 있습니다.
3. **다중 플랫폼 지원**: iOS, Android 등 다양한 모바일 운영체제에 대해 푸시 알림을 지원하여, 사용자 기반을 넓힐 수 있습니다.
4. **배터리 및 데이터 효율성**: 최신 푸시 기술을 사용하여 배터리 소모와 데이터 사용을 최소화하면서도 효율적으로 알림을 전달합니다.
5. **대화형 알림**: 사용자가 알림 자체에서 직접 대응할 수 있도록 대화형 요소를 포함시킬 수 있습니다. 예를 들어, 메시지에 바로 답장하거나, 초대에 응답할 수 있습니다.

## 푸시 알림의 구현 방법 <a href="#undefined" id="undefined"></a>

푸시 알림 서비스를 구현하기 위해 Game Chat API는 몇 가지 핵심 요소를 제공합니다:

* **푸시 토큰 등록**: 사용자 장치의 푸시 토큰을 Game Chat 서버에 등록하여, 해당 장치에 알림을 보낼 수 있게 합니다.
* **알림 설정 관리**: 사용자는 자신의 알림 선호도에 따라 알림을 받을지 여부를 설정할 수 있습니다.
* **백엔드 통합**: 서버 측에서는 Game Chat의 백엔드와 통합하여 실시간으로 푸시 알림을 생성하고 전송할 수 있습니다.

## 보안 및 개인 정보 보호 <a href="#undefined" id="undefined"></a>

* **데이터 암호화**: 모든 푸시 알림은 전송 중 암호화되어, 외부의 접근으로부터 보호됩니다.
* **개인 정보 보호 정책 준수**: Game Chat은 사용자의 개인 정보 보호를 매우 중요하게 여기며, 관련 법률 및 규정을 준수하여 알림 서비스를 제공합니다.

푸시 알림 기능을 통해 Game Chat은 사용자의 참여를 유도하고, 앱 사용률을 높이며, 사용자 경험을 향상시키는 데 크게 기여합니다. 사용자는 중요한 커뮤니케이션을 놓치지 않고, 언제 어디서나 연결되어 있을 수 있습니다.

## Android(Kotlin)

[Firebase Console](https://console.firebase.google.com/) 에서 Andoird 앱을 추가 후, 다운로드한 "google-services.json' 파일을 프로젝트 앱 모듈의 루트 폴더에 추가합니다.

파일 추가 후 bundle.gradle.kts 내 아래 내용을 추가합니다.

```kotlin
plugins {
...
    id("com.google.gms.google-services")
...
}
dependencies {
...
    implementation("com.google.firebase:firebase-messaging-ktx:23.2.1")
...
}
```

푸시 허용 권한 팝업을 요청 합니다.

```kotlin
import com.nbase.sdk.Permission

NChat.setEnablePush(true)
NChat.requestPermission(this, Permission.NOTIFICATION)
// initialize 전에 호출이 되어야 합니다.
```

Connect 이후 푸시 수신 여부 설정을 위해 setPushState 를 호출합니다.

```kotlin
NChat.setPushState(PushState([PUSH], [AD], [NIGHT])) { state, e ->
    if (e != null) {
        // 오류
    } else {
        // 성공
    }
}
```

<table><thead><tr><th width="213">ID</th><th width="202">Type</th><th>Description</th></tr></thead><tbody><tr><td>push</td><td>boolean</td><td>푸시 수신 On/ Off (true = On)</td></tr><tr><td>ad</td><td>boolean</td><td>푸시 수신을 위해 반드시 true 로 호출</td></tr><tr><td>night</td><td>boolean</td><td>야간 푸시 수신 On/ Off</td></tr></tbody></table>

### **Android(Kotlin) 푸시 클릭 이벤트**

안드로이드 푸시 클릭 핸들러를 설정 할 수 있습니다.

```kotlin
NChat.setNotificationClickedHandler { notification ->
    val title = notification.title
    val content = notification.body
    val channel = notification.data?.get("channel") ?: ""
    val imageUrl = notification.data?.get("imageUrl") ?: ""
    val url = notification.data?.get("url") ?: ""
    val metadata = notification.data?.get("metadata") ?: ""
    
    // 푸시 클릭 시 원하는 동작을 정의합니다.
}
```

## Android (Java) <a href="#androidjava" id="androidjava"></a>

1. 프로젝트의 build.gradle 내 아래 repo를 추가합니다.

```Groovy
allprojects {
    repositories {
    	...
        google()
    	// nbase repo
        maven { url "https://repo.nbase.io/repository/nbase-releases" }
	...
    }
}
```

2. app 모듈의 build.gradle 내 아래 내용을 추가합니다.

```Groovy
dependencies {
    ...
    implementation ("io.nbase:nbasesdk:3.0.78")
    implementation ("io.nbase:nbase-adapter-cloudchat:1.0.17")
    implementation ("com.google.firebase:firebase-messaging-ktx:23.2.1")
    ...
}
```

### **Android (Java) 푸시 클릭 이벤트**

안드로이드 푸시 클릭 핸들러를 설정 할 수 있습니다.

```Java
NChat.INSTANCE.setNotificationClickedHandler(notification -> {
    // 푸시 클릭 시 원하는 동작을 정의합니다.
    String title = notification.getTitle();
    String content = notification.getBody();
    String channel = notification.getData() != null ? notification.getData().get("channel") : "";
});
```

#### **Android 푸시 데이터**

안드로이드 푸시 클릭 핸들러를 통해 전달되는 값에 대한 리스트입니다.

| Key          | Description                    |
| ------------ | ------------------------------ |
| Title        | 푸시 메시지에 설정된 제목                 |
| Body         | 푸시 메시지에 설정된 메시지                |
| Data.channel | 채팅방 푸시의 경우 푸시가 발생한 CHANNEL\_ID |

## iOS(Swift)

앱푸시 발송 권한을 추가합니다. Target 의 Signing & Capabilites으로 들어와 좌상단의 + Capability > Push Notifications 를 선택하여 추가합니다.<br>

<figure><img src="/files/pxOzkssP7zSAorIWmDdq" alt=""><figcaption></figcaption></figure>

AppDelegate.swift 생성 혹은 이미 생성된 AppDelegate.swift 내 아래 내용을 정의합니다.

```swift
import UIKit
import NChat

class AppDelegate: NSObject, UIApplicationDelegate {
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 푸시 알림 권한 요청
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            print("Permission granted: \(granted)")
        }
        
        UNUserNotificationCenter.current().delegate = self
        application.registerForRemoteNotifications()
        
        // 메인 윈도우 설정
        window = UIWindow(frame: UIScreen.main.bounds)
        let initialViewController = UIViewController()
        initialViewController.view.backgroundColor = .white
        window?.rootViewController = initialViewController
        window?.makeKeyAndVisible()
        
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // 디바이스 토큰을 문자열로 변환
        let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
        let token = tokenParts.joined()
        
        // sandbox 환경에서 푸시를 수신하려면 sandbox: true
        NChat.setPushToken(token: token, sandbox: false)
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("RegisterForRemoteNotifications Failed: \(error.localizedDescription)")
    }
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        if #available(iOS 14.0, *) {
            completionHandler([.banner, .list, .sound, .badge])
        } else {
            completionHandler([.alert, .sound, .badge])
        }
    }
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        do {
            try handleNotificationClick(userInfo: userInfo, actionIdentifier: response.actionIdentifier)
        } catch let error as NotificationError {
            print("NotificationError: \(error.localizedDescription)")
        } catch {
            print("UnexpectedError: \(error.localizedDescription)")
        }

        // NChat 라이브러리의 푸시 알림 처리 함수 호출
        NChat.handlePushNotification(userInfo: userInfo)
        completionHandler()
    }
}

// 알림 관련 오류 정의
enum NotificationError: LocalizedError {
    case invalidUserInfo(String)
    case navigationError(String)

    var errorDescription: String? {
        switch self {
        case .invalidUserInfo(let message):
            return "잘못된 사용자 정보: \(message)"
        case .navigationError(let message):
            return "네비게이션 오류: \(message)"
        }
    }
}

extension UIViewController {
    func topMostViewController() -> UIViewController {
        if let presented = self.presentedViewController {
            return presented.topMostViewController()
        }
        if let navigation = self as? UINavigationController {
            return navigation.visibleViewController?.topMostViewController() ?? navigation
        }
        if let tab = self as? UITabBarController {
            return tab.selectedViewController?.topMostViewController() ?? tab
        }
        return self
    }
}
```

> 참고\
> sandbox 환경에서의 푸시는\
> NChat.setPushToken(token: token, sandbox: true)\
> sandbox 값이 true 설정이 되어야 정상적으로 수신이 가능합니다.

Connect 이후 푸시 수신 여부 설정을 위해 setPushState 를 호출합니다.

```swift
NChat.setPushState(push: true, ad: true, night: true) { result in
    switch(result)
    {
    case .success(let status) :
        // 성공
        break;
    case .failure(let error) :
        // 실패
        break;
    }
}
```

<table><thead><tr><th width="203">ID</th><th width="175">Type</th><th>Description</th></tr></thead><tbody><tr><td>push</td><td>boolean</td><td>푸시 수신 On/ Off (true = On)</td></tr><tr><td>ad</td><td>boolean</td><td>푸시 수신을 위해 반드시 true 로 호출</td></tr><tr><td>night</td><td>boolean</td><td>야간 푸시 수신 On/ Off</td></tr></tbody></table>

### **iOS (Swift) 푸시 클릭 이벤트**

iOS 푸시 클릭 핸들러를 설정 할 수 있습니다.

AppDelegate.swift 내 아래 예시와 같이 추가 정의합니다.

```swift
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?
    // 알림 클릭 처리 함수
    private func handleNotificationClick(userInfo: [AnyHashable: Any], actionIdentifier: String) throws {
        if actionIdentifier == UNNotificationDefaultActionIdentifier {
            showNotificationPopup(with: userInfo)
        } else {
            handleCustomAction(actionIdentifier, userInfo: userInfo)
        }
    }

    // 사용자 정의 액션 처리 함수
    private func handleCustomAction(_ actionIdentifier: String, userInfo: [AnyHashable: Any]) {
        switch actionIdentifier {
        case "ACTION_1":
            showNotificationPopup(with: userInfo, title: "ACTION_1")
        case "ACTION_2":
            showNotificationPopup(with: userInfo, title: "ACTION_2")
        default:
            print("actionIdentifier: \(actionIdentifier)")
        }
    }

    // 알림 팝업을 표시하는 함수
    private func showNotificationPopup(with userInfo: [AnyHashable: Any], title: String = "알림") {
        DispatchQueue.main.async {
            let alertController = UIAlertController(title: title, message: "알림 수신됨", preferredStyle: .alert)

            // userInfo의 내용을 메시지에 추가
            for (key, value) in userInfo {
                alertController.message?.append("\n\(key): \(value)")
            }

            let okAction = UIAlertAction(title: "확인", style: .default, handler: nil)
            alertController.addAction(okAction)

            // 키 윈도우를 찾아 팝업을 표시
            if let keyWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
                if let topViewController = keyWindow.rootViewController?.topMostViewController() {
                    topViewController.present(alertController, animated: true, completion: nil)
                }
            } else {
                print("키 윈도우를 찾을 수 없음")
            }
        }
    }
}
```

#### **iOS 푸시 데이터**

iOS 푸시 클릭 핸들러를 통해 전달되는 값에 대한 리스트입니다.

| Key     | Description                    |
| ------- | ------------------------------ |
| Title   | 푸시 메시지에 설정된 제목                 |
| Body    | 푸시 메시지에 설정된 메시지                |
| channel | 채팅방 푸시의 경우 푸시가 발생한 CHANNEL\_ID |


# 가져오기&내보내기

## 가져오기&내보내기 <a href="#undefined" id="undefined"></a>

대용량 마이그레이션 서비스로는 크게 두 가지 방법으로 진행할 수 있으며, 대규모 마이그레이션을 위해서는 프리미엄 지원을 받으시기 바랍니다.(무료)

1. **하드 전환을 통한 마이그레이션**:
   * 서비스 중단이 필요하며, 고객은 애플리케이션을 업그레이드해야 합니다.
   * 서비스를 일시 중지할 최적의 시간을 예약합니다.
   * 관련 데이터를 Game Chat 플랫폼의 올바른 가져오기 형식으로 내보냅니다.
   * Game Chat 대시보드를 통해 Game Chat 데이터를 가져옵니다.
   * 데이터의 온전성을 검증하고 확인합니다.

이러한 절차를 통해 마이그레이션 과정을 효과적으로 관리하고, Game Chat 플랫폼에서 새로운 채팅 서비스를 원활하게 시작할 수 있습니다. 프리미엄 지원을 통해 실시간으로 엔지니어링 팀과 소통하면서 이러한 과정을 보다 쉽게 진행할 수 있습니다.

### 가져오기 <a href="#undefined" id="undefined"></a>

1. API 를 통해 데이터를 대량의 데이터를 입력하실 수 있습니다.
2. Game Chat 에 맞는 데이터 포멧(JSON) 으로 변환하여 전달해 주시면 지정된 시간에 데이터를 대량으로 추가가 가능합니다. 프리미엄 지원 서비스를 받으시길 추천드립니다.

### 내보내기 <a href="#undefined" id="undefined"></a>

각 메뉴마다 내보내기가 존재하며, 내보낸 데이터는 도움 => 활동 및 파일 에서 다운로드 받으실 수 있습니다.


# 고정 메시지

## 고정 메시지 <a href="#undefined" id="undefined"></a>

채팅에서 고정메시지(Pinned Message)는 채팅방이나 그룹 대화에서 중요한 메시지를 채널이나 대화창의 상단에 고정하는 기능을 말합니다. 이 기능은 참가자들이 해당 채팅을 열 때마다 쉽게 볼 수 있도록 하여 중요한 정보나 알림을 놓치지 않도록 도와줍니다. 다음은 고정메시지의 주요 특징과 활용 방법에 대한 설명입니다.

### 고정 메시지의 활용 방법 <a href="#undefined" id="undefined"></a>

* **회의 일정 공지**: 정기 회의나 중요 이벤트의 일정을 고정메시지로 설정하여 참여자들이 일정을 잊지 않도록 합니다.
* **중요 문서 링크**: 중요한 문서나 자료의 링크를 고정하여 모든 참가자가 쉽게 접근할 수 있도록 합니다.
* **규칙 및 지침 공유**: 채팅방의 규칙이나 프로젝트 지침을 고정메시지로 설정하여 새로운 참가자도 쉽게 지침을 확인할 수 있게 합니다.
* **긴급 공지**: 긴급하게 전달해야 할 내용이나 변경 사항을 고정메시지로 빠르게 공유할 수 있습니다.

고정메시지 기능은 다양한 커뮤니케이션 플랫폼에서 제공되며, 이를 효과적으로 활용하면 팀 커뮤니케이션의 효율성을 크게 높일 수 있습니다.

### 고정 메시지 생성 <a href="#undefined" id="undefined"></a>

채팅 애플리케이션에서 중요한 메시지를 사용자들이 쉽게 볼 수 있도록 상단에 고정하는 기능입니다. 아래의 C# 코드는 채팅 채널에서 메시지를 고정하는 방법을 보여줍니다.

```csharp
var newPin = await nc.createPin(channelId, messageId, pinned, pinnedAt, expiredAt);
```

* `channelId`: 메시지가 고정될 채팅 채널의 고유 식별자입니다.
* `pinned`: 고정할 메시지의 내용입니다.
* `pinnedAt`: 메시지가 고정된 시각을 나타냅니다.
* `expiredAt`: 메시지 고정이 해제될 시각입니다.

이 함수를 사용하면 특정 채팅 채널 내에서 중요한 메시지를 쉽게 강조하여 표시할 수 있습니다.

### 고정 메시지 수정 <a href="#undefined" id="undefined"></a>

기존에 고정된 메시지의 정보를 업데이트하기 위한 기능입니다. 메시지의 내용, 고정 시각 또는 만료 시각을 변경할 수 있습니다.

```csharp
var updatedPin = await nc.updatePin(id, channelId, pinned, pinnedAt, expiredAt);
```

* `channelId`: 수정할 메시지가 있는 채널의 ID입니다.
* `pinned`: 수정된 메시지 내용입니다.
* `pinnedAt`: 메시지가 새롭게 고정된 시각입니다.
* `expiredAt`: 메시지 고정의 새로운 만료 시각입니다.

이 코드는 이미 고정된 메시지의 세부사항을 변경할 때 사용되며, 메시지의 중요성이 변경되었거나 고정 시간을 조정해야 할 때 유용합니다.

### 고정 메시지 정보 <a href="#undefined" id="undefined"></a>

특정 메시지의 고정 관련 정보를 조회하는 기능입니다. 이는 메시지의 고정 상태, 고정 시각, 만료 시각 등을 확인할 수 있습니다.

```csharp
var pin = await nc.getPin(channelId, messageId);
```

* `channelId`: 정보를 조회할 채널의 ID입니다.
* `messageId`: 고정된 메시지의 고유 식별자입니다.

이 함수를 통해 특정 메시지가 현재 어떤 상태인지 확인할 수 있으며, 이는 관리자나 사용자가 채널 내 메시지 관리를 보다 효과적으로 할 수 있게 도와줍니다.

### 고정 메시지 목록 <a href="#undefined" id="undefined"></a>

채팅 채널에서 현재 고정된 모든 메시지의 목록을 조회하는 기능입니다. 이 함수는 페이징을 지원하여 대규모 채널에서도 효율적으로 데이터를 처리할 수 있습니다. 사용자는 `offset`과 `per_page`을 설정하여 원하는 범위의 데이터를 가져올 수 있습니다.

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", channelId },
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 },
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 },
};
var pins = await nc.getPins(channelId, filter, sort, option);
```

**파라미터 설명**

* **filter**: 조회할 데이터를 필터링하기 위한 조건들을 정의합니다. 예를 들어, 특정 채널에서 고정 메시지를 조회할 수 있습니다.
* **sort**: 결과 목록의 정렬 방식을 정의합니다. 여기서는 생성 시간(`created_at`)을 기준으로 내림차순(-1) 정렬을 사용합니다.
* **option**: 조회 시 사용할 옵션을 정의합니다. `offset`은 조회 시작 위치, `per_page`는 페이지 당 보여질 메시지 수를 지정합니다.

**옵션 세부 사항**

<table><thead><tr><th width="149">ID</th><th width="140">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>데이터를 가져올 시작 위치입니다.</td></tr><tr><td>per_page</td><td>number</td><td>한 페이지당 반환할 메시지의 수, 최대 100개까지 설정 가능합니다.</td></tr></tbody></table>

이 기능을 사용하면 채널 관리자는 채널 내에서 중요한 메시지를 쉽게 모니터링하고 관리할 수 있습니다. 또한, 특정 사용자 또는 시간 기준으로 고정 메시지를 빠르게 검색하고 정렬할 수 있어, 채널의 효율적인 운영을 돕습니다.


# 외부연동

## 외부연동 <a href="#undefined" id="undefined"></a>

채팅 애플리케이션에서 외부 서비스나 다양한 상품군과 연동하는 것은 사용자 경험을 향상시키고, 더 많은 기능을 제공할 수 있게 합니다. 예를 들어, 번역 서비스, AI 기반의 콘텐츠 추천, 상품 추천 등을 통합할 수 있습니다. 다음은 이러한 기능들을 채팅 애플리케이션에 통합하는 방법에 대한 설명입니다:

### 외부 연동 예시 <a href="#undefined" id="undefined"></a>

* 번역 서비스 연동: 채팅 애플리케이션에서 다국어 지원이 필요한 경우, Papago 번역 API와 같은 번역 서비스를 연동할 수 있습니다. 사용자가 메시지를 입력하면, API를 통해 해당 메시지를 번역하고 결과를 채팅창에 표시할 수 있습니다.
* AI 기반 콘텐츠 추천: 사용자의 채팅 내용과 행동 패턴을 분석하여 AI가 개인화된 콘텐츠를 추천할 수 있습니다. 예를 들어, Netflix의 추천 시스템처럼, 사용자의 관심사에 맞는 영화나 TV 프로그램을 추천할 수 있습니다.
* 고객 지원 자동화: 채팅봇을 도입하여 기본적인 고객 문의 사항을 자동으로 처리할 수 있습니다. AI 채팅봇은 사용자의 질문을 이해하고 적절한 답변을 제공하거나, 필요한 경우 인간 상담원에게 연결할 수 있습니다.

이러한 연동을 통해 채팅 애플리케이션은 단순한 메시지 교환 도구를 넘어, 다양한 서비스를 통합하여 풍부한 사용자 경험을 제공하는 플랫폼으로 확장될 수 있습니다.

### 외부 연동 서비스 목록 <a href="#undefined" id="undefined"></a>

* 푸시 (NPush)
* 번역 (파파고)
* 이미지 분석
* 감정 분석
* HyperClova X
* Object Storage


# 사용예제

## 예제 <a href="#undefined" id="undefined"></a>

### Ncloudchat React 예제

깃헙에 전체 소스가 공개되어 있으며, [깃헙소스](https://github.com/nbase-io/CloudChat-JS-Demo) 는 다운로드 하실 수 있으며, [https://www.ncloudchat.com](https://www.ncloudchat.com/) 을 통해 이용해 보실 수 있습니다.

### 전체 샘플 코드 예제 <a href="#undefined" id="undefined"></a>

접속하고 채널을 생성하고 생성된 채널에 가입 메시지를 발송하는 예제입니다.

```csharp

// 초기화 
CloudChat nc = CloudChat.GetInstance();
await nc.initialize([PROJECT_ID]);
nc.dispatcher.onMessageReceived += e =>
{
    Console.WriteLine("received a new message: ", e);
};
await nc.Connect(
    userId: 'guest@company',
    name: 'Guest',
    profile: 'https://image_url',
    customField: 'json',
);
// 채널 생성
var channel = await nc.createChannel(new CloudChatSDK.Channel
{
    name = "New Channel",
    type = "PUBLIC",    // PUBLIC or PRIVATE
    customField = "customField"
});
var channel = await nc.createChannel({type:'PUBLIC', name:'First Channel', customField:'customField'});
var channel_id = channel.createChannel.channel.id.ToString();
// 채널 구독
await nc.subscribe(channel_id);
// 메시지 발송
var response = await nc.sendMessage(
        channelId: channel_id, 
        type:"text", 
        content: message
    );
```


# Troubleshooting

서비스 이용 중 발생할 수 있는 오류와 해결 방법을 안내합니다.

## 1. 채널 생성 시 '주소를 확인할 수 없습니다.' <a href="#id-1" id="id-1"></a>

해당 오류는 link\_url 입력 시 해당 주소가 기본 주소 체계(URL)가 아닐 때 발생하는 오류입니다. 주소를 입력하지 않거나 입력하려는 주소를 올바르게 입력해 주십시오.

## 2. 업로드가 되지 않습니다. <a href="#id-2" id="id-2"></a>

보안 강화를 위해서 허용된 타입이 아니면 업로드할 수 없습니다.\
**대시보드 > 설정 > 파일 업로드 허용 타입**에서 image, video, document, compress 와 같이 허용하려는 MIME TYPE을 선택해 주십시오.\
오브젝트 스토리지가 활성화되어 있어야 합니다. [Object Storage](https://www.ncloud.com/product/storage/objectStorage) 상품과 연동한 후 사용해 주십시오.

## 3. 모든 메시지가 수신 됩니다. <a href="#id-3" id="id-3"></a>

여러가지 채널에 가입된 경우 가입된 모든 채널의 메시지가 수신 됩니다.\
channelId를 통해 구분하실 수 있습니다.

```javascript
nc.bind('onMessageReceived',function(channel, message) {       
    // 여러 채널에 가입된 경우 여러 채널의 메시지가 이곳으로 모두 수신됩니다.
    // channel 을 통해서 고객에서 보여줄 채널을 구분해야만 합니다.   
    if(channel == current_channel) {
        console.log(message);
    }
});
```


# Game Chat(English)

## &#x20;<a href="#undefined" id="undefined"></a>


# Start using V3

This page describes how to operate and manage chats from the Game Chat dashboard, how to view chat-related statistics, and how to set up integration with various NAVER Cloud Platform services.

## Dashboard menu <a href="#undefined" id="undefined"></a>

The dashboard helps you view the operation status of your chats, including access status, message, and statistics at a glance. Check a graph by selecting a date.

The dashboard menus are listed below.

<table><thead><tr><th width="266">Item</th><th>Description</th></tr></thead><tbody><tr><td>① <strong>Home</strong></td><td>View service usage and status</td></tr><tr><td>② <strong>Analysis</strong></td><td>Analyze users and concurrent users</td></tr><tr><td>③ <strong>User</strong></td><td>View members and manage blocked users</td></tr><tr><td>④ <strong>Chat</strong></td><td>Add and manage chat channels</td></tr><tr><td>⑤ <strong>Message</strong></td><td>Search and extract chat messages to Excel by time period</td></tr><tr><td>⑥ <strong>Archive</strong></td><td>Check all files (images/videos) transferred during a chat</td></tr><tr><td>⑦ <strong>Push notification</strong></td><td>Send and view push notifications</td></tr><tr><td>⑧ <strong>Settings</strong></td><td>Manage General, Security, Integrations, and Dashboard settings for a project</td></tr><tr><td>⑨ <strong>Activities &#x26; Files</strong></td><td>View the history of data exports from the Search menu</td></tr><tr><td>⑩ <strong>Guide</strong></td><td>Go to Game Chat user guide</td></tr></tbody></table>

## User <a href="#undefined" id="undefined"></a>

In the User menu, you can view the information of members registered on the dashboard, block specific users from using chats, or withdraw them from all chats.

### Check user information <a href="#undefined" id="undefined"></a>

To view the information of users registered on Game Chat dashboard, follow these steps:

1. From the Game Chat dashboard, click **User** > **Users**.
2. Click the user ID to view the user's details.
3. View the details in the pop-up window.
   * View features such as user name, profile URL, country of access, IP, model, device ID, sign-up date, and last login date and use custom fields and notes
4. Edit the item to user information, and then click the **\[Save]** button.

### Remove user <a href="#undefined" id="undefined"></a>

To withdraw a specific user, follow these steps:

1. From the Game Chat dashboard, click **User** > **Users**.
2. Click the ID of the user to withdraw.
3. When the user's details appear on the screen, click the **\[Delete]** button.
4. When a pop-up confirmation window appears, click the **\[Delete]** button.

### Search users <a href="#undefined" id="undefined"></a>

To search users registered on Game Chat dashboard, follow these steps:

1. From the Game Chat dashboard, click **User** > **Users**.
2. Set search conditions, and then click the **\[Search]** button.
   * Search by user ID, name or IP
3. Check the search results.

### Block users <a href="#undefined" id="undefined"></a>

You can adjust settings so that a specific user is blocked from using chats for a certain period. In the Blocked users menu, you can view and search users who have been blocked.\
To block a specific user from using chats, follow these steps:

1. Click **User** > **Blocked users** from the Game Chat dashboard.
2. Click the **\[Add]** button located on the right.
3. In the Add window that appears, you can search for a user ID, set a suspension or permanent suspension, and set the default language.
4. If you also want to remove the user you're about to block from all channels, then mark the **Remove from all chats** checkbox.
5. Set the user ID, reasons for the blocking, and block period, and then click the **\[Add]** button.

## Chat <a href="#undefined" id="undefined"></a>

In the Chat menu, you can view channels and send chat messages.

### Add chat channel <a href="#undefined" id="undefined"></a>

To add a new chat channel, follow these steps:

1. From the Game Chat dashboard, click the **Channel** menu.
2. Click the **\[Add]** button.
3. You can separately create **Open chats** and **Private chats**. (**Open chats** can accommodate up to 200,000 users, and **Private chats** creates a private channel with a limited number of members.)
4. Enter the channel name and unique ID and click the **\[Add]** button.
   * Enter a unique ID to access a channel with the value in the SDK
   * You can select push, automatic translation, and integrate additional products from Integrations.
5. Check if the channel has been created.

### Chat channel settings <a href="#undefined" id="undefined"></a>

To check users participating in a specific chat channel, or edit or delete the channel information, follow these steps:

1. From the Game Chat dashboard, click the **Channel** menu.
2. Select a channel and click the **...** icon at the upper right of the channel page.
3. When the context menu appears, select the task you want.
   * **Subscribers**: click to view the list of users participating in the chat channel
   * **Edit**: click to edit the chat channel information
   * **Delete**: click to delete the chat channel

### Send image message

To check users participating in a specific chat channel, or edit or delete the channel information, follow these steps:

1. From the Game Chat dashboard, click the **Channel** menu.
2. After selecting a channel, click the Attach File icon to the right of the chat message compose field.

> Note
>
> Supported image types: image/bmp, image/gif, image/jpeg, image/png, image/webp, image/heic, image/heic-sequence, image/heif, image/heif-sequence, image/svg+xml

## Message <a href="#undefined" id="undefined"></a>

In the Message menu, you can view and search messages exchanged in all channels of a project. You can search with ID, nickname, message, channel ID, or date and time the message is sent. You can also download the message list in a CSV file.

### Search message and view message details <a href="#undefined" id="undefined"></a>

To view a message's details, follow these steps:

1. From the Game Chat dashboard, click the **Message** menu.
2. Set search conditions, and then click the **\[Search]** button.
   * Search by sender ID, sender name, chat ID, nickname, or message content.
3. Click a message to view its details.
4. You can see the user ID, name, chat ID, message ID, message content, and the date the message was created.

### Delete messages <a href="#undefined" id="undefined"></a>

You can search for a specific message and delete it. The message deleted from the Search menu will also be deleted from the chat channel.

1. From the Game Chat dashboard, click **Message**.
2. Click the message you want to delete.
3. On the message view screen, select Delete and click the **\[Delete]** button.

## Archive <a href="#undefined" id="undefined"></a>

In the Archive menu, you can view and search images and files exchanged in all channels of a project. You can check the usage status, sender, chat ID, preview, file name, format, size, number of times sent, creation date, and expiration date. You can also select a specific file to ban or delete the user.

### Push notifications <a href="#undefined" id="undefined"></a>

Push notifications are messages that appear on mobile devices and are sent by application publishers. These notifications can be delivered at any time, regardless of whether the user is actively using the app or device. There are a few key things to keep in mind:

* The message payload, which is the size of the JSON, is limited to 4 KB.
* When you send notifications internationally, they are delivered at the scheduled time based on the local time in each country.\
  You can set up push notifications and view the list of sent push notifications.

## Settings <a href="#undefined" id="undefined"></a>

In the Settings menu, you can set Game Chat project information, change how you handle forbidden keywords in chats and automatic message translation status, edit member information, or grant the admin permission to specific members.

### General <a href="#undefined" id="undefined"></a>

You can view the project name, ID, API key, and set the maximum message length and the type of profanity filter restrictions.

1. You can view and copy the project ID.
2. You can copy or regenerate the API key.
3. You can set the maximum message length.
4. You can select the type of profanity filter restrictions.
   * Disabled: display the forbidden keywords without any blinding
   * Replace with \*: display the words specified as forbidden keywords as \* in a chat window
   * Block sending: do not send words specified as forbidden keywords
5. Click the **\[Use default filter]** button to automatically import the profanity examples.

### Security <a href="#undefined" id="undefined"></a>

You can set the security of the created project, as well as the allowed IPs and image types.

1. Click **Settings > Security** from the Game Chat dashboard.
2. Specify the required security settings.
   * Token authentication: grant access with a specific token
   * Add or remove allowed IPs
   * Add or delete allowed image types
   * Limit upload size
   * Set download expiration time
   * Set allowed access types
   * Set and delete white lists
3. Click the **\[Save]** button.

### Integration <a href="#undefined" id="undefined"></a>

You can set the integration status or integration of various products such as Papago, and Object Storage to the project you have created.

1. Click **Settings > Integration** from the Game Chat dashboard.
2. Select the name of the product you want to integrate.
3. Fill in the integration status and input fields for each product and click the **Save** button.

> Note
>
> For more information on how to view the client ID and client secret for setting up integration with Papago Translation, see the [Papago Translation user guide](https://guide.ncloud-docs.com/docs/en/papagotranslation-overview).

### Admin <a href="#undefined" id="undefined"></a>

You can view and edit the administrator information of the Game Chat project. However, the details of the account currently logged in can be edited from the Edit profile menu under Account information.\
To edit Admin information, follow these steps:

1. Click **Settings** > **Admin** from the Game Chat dashboard.
2. Click the member whose information you want to edit.
3. Set the member name, new password, and user status and click the **\[Save]** button.
4. If you want to designate a certain member as the dashboard admin, then activate the Admin permission icon, and click the **\[Save]** button.
5. Click the **\[Delete]** button to delete the member information.

## Activities & Files <a href="#undefined" id="undefined"></a>

In the Activities & Files menu, you can download the export result of CSV files from the Search menu for 30 days.

## Account information <a href="#undefined" id="undefined"></a>

The user icon in the upper right corner allows you to edit your account information and log out.

### Edit profile <a href="#undefined" id="undefined"></a>

Check the information of the logged-in account and change the name, profile URL, and dashboard time zone. Profile URL is used in chats.\
To edit profile information, follow these steps:

1. Click the User icon at the top right of the Game Chat dashboard and then click the Edit profile menu.
2. From the Edit profile menu, set name, profile URL, or time zone, and then click the **\[Save]** button.

### Change password <a href="#undefined" id="undefined"></a>

To change your password, follow these steps:

1. Click the User icon at the top right of the Game Chat dashboard and then click the **Edit profile** menu.
2. Click the Change password menu, enter the current and new password, and then click the **\[Save]** button.

## Dashboard logout <a href="#undefined" id="undefined"></a>

To log out from the Game Chat dashboard, click the User icon at the top right of the Game Chat dashboard, and then click **Log out**.


# Install Unity SDK

The following guides you on how to use Unity SDK. You can integrate the chat and dashboard by installing the SDK and configuring the environment.

## Required specifications

* Minimum specifications: 2020 or later (If you need support for a lower version of Unity, make an inquiry at '<cs@nbase.io>' email)
* Users of Unity Editor on 2020.3.X / 2021.1.X version should use 2020.3.15f2 or later / 2021.1.16f1 or later (Unity Editor bug fixes for AAB version builds).

## Install SDK and configure the environment

To download Ncloud Chat Unity SDK and configure your project in Unity, follow these steps:

1. [**Download**](https://github.com/nbase-io/NcloudChat-SDK-Unity/releases/) from the GitHub repository page.
2. For samples, [**download**](https://github.com/nbase-io/NcloudChat-SDK-Unity) from the GitHub repository page as well.
3. Run Unity, and create a project.
4. In Unity, click **Assets** > **Import Package** > **Custom Package...** in order.
5. Import the downloaded 'NcloudChat.Unity.SDK.\[version].unitypackage' file from the dashboard.
6. Select all files in the package, and then click the **\[Import]** button.
7. Save the project.


# Initialization

## Initialization <a href="#undefined" id="undefined"></a>

Before using Game Chat, it must be initialized. \
Add the project ID you checked in the dashboard. To initialize Game Chat, follow these steps:

1. Access the dashboard and check the project ID in the settings menu.
2. Use the following code to initialize instances.

* Import the NBaseSDK module.

```csharp
using NBaseSDK;
```

* Create an NBaseSDK Chat instance.

```csharp
NBaseSDK.Chat nc = NBaseSDK.Chat.GetInstance();
```

* Initialize NChat. \
  Enter the settings for projectId, region, and language.

```csharp
nc.initialize([PROJECT_ID], [REGION], [LANGUAGE]);
```

<table><thead><tr><th width="158">ID</th><th width="98">Type</th><th width="365">Description</th><th>Required</th></tr></thead><tbody><tr><td>PROJECT_ID</td><td>string</td><td>ID (Game Chat dashboard Project ID)</td><td>O</td></tr><tr><td>REGION</td><td>string</td><td>Region (use "kr" if not using a specific one)</td><td>O</td></tr><tr><td>LANGUAGE</td><td>string</td><td>Language code ("en", "ko", etc.)</td><td>O</td></tr></tbody></table>

## Error handling <a href="#undefined" id="undefined"></a>

* Basic error handling is to add the code inside the try... catch as follows:

```csharp
try
{
    // Write the code that may cause an error here.
    ...
}
catch (InvalidOperationException e)
{
    // Write the handling for specific error types here.
    Console.WriteLine("InvalidOperationException: {0}", e.Message);
}
catch(Exception e)
{
    // Write the general error handling here.
    Console.WriteLine("Error: {0}", e.Message);
}

```


# Login

## Login <a href="#undefined" id="undefined"></a>

After initialization is complete, you can log in by entering your username, name, and profile image address (optional).

### Access <a href="#undefined" id="undefined"></a>

```csharp
await nc.Connect(
    id: [USERNAME],
    name: [NAME],
    profile: [PROFILE_URL],
    customField: [CUSTOM_FIELD],
    token: [TOKEN]
);
```

| ID            | Type   | Description         | Required |
| ------------- | ------ | ------------------- | -------- |
| USERNAME      | string | ID                  | O        |
| NAME          | string | Nickname            | X        |
| PROFILE\_URL  | string | Profile address URL | X        |
| LANGUAGE      | string | Language code       | X        |
| CUSTOM\_FIELD | string | User-defined field  | X        |
| TOKEN         | string | Token value         | X        |

> Note
>
> * Obtain a token through the API for log-in security.
> * [API DOCS TOKEN](https://api.ncloud-docs.com/docs/en/bizapp-token-issuance) lets you use a token issued through the API.
> * If you do not want to use the token method, set **disable** in **Dashboard > Security settings > Token authentication**.

### Terminate access <a href="#undefined" id="undefined"></a>

Use the code below to disconnect from the connected Game Chat server.

```csharp
await nc.Disconnect();
```

### User information <a href="#undefined" id="undefined"></a>

* Member Data Class

| ID      | Type   | Description   |
| ------- | ------ | ------------- |
| id      | string | User ID       |
| name    | string | Username      |
| profile | string | Image address |

#### **Import user information**

Gets information about a specific ID (only the nickname is sent for security reasons).

```csharp
Hashtable filter = new Hashtable
{
    { "id", [USER_ID] }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var users = await nc.getUsers(filter, sort, option);
```

* Parameters

<table><thead><tr><th width="116">ID</th><th width="95">Type</th><th width="445">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>Search is available for all fields of a query through filtering</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>Define the filter for the fields you want to sort (ascending order "1", descending order "-1")</td><td>X</td></tr><tr><td>option</td><td>object</td><td>See the following when there are options</td><td>X</td></tr></tbody></table>

* Options

<table><thead><tr><th width="212">ID</th><th width="192">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>Start offset</td></tr><tr><td>per_page</td><td>number</td><td>The number of returns (up to 100)</td></tr></tbody></table>


# Channel

## Channel <a href="#undefined" id="undefined"></a>

In Game Chat, the channel is a virtual space where users can communicate in a group. Through channels, you can share information suitable for a specific subject or purpose, enhance teamwork, and systematize communication. Channel is a useful tool to increase business efficiency, and centralize and manage communication in a specific group. The following describes the channel functions of Game Chat.

### Main functions of channel <a href="#undefined" id="undefined"></a>

1. **Group communication**: you can create a channel and communicate with members in a specific group. It is suitable for diverse forms of groups, such as project teams, divisions, or clubs.
2. **Message and file sharing**: you can easily share various forms of files such as text messages, images, videos, and documents in the channel.
3. **Real-time update**: all activities in the channel are updated in real time so that every participant can obtain the latest information.
4. **Admin control**: the creator or admin of the channel has the right to change channel settings or add and remove users.
5. **Calls and video conferencing function**: some channels provide voice calls or video conferencing for effective communication between members.
6. **Notification settings**: you can set notifications by channel so as not to miss important messages.
7. **Search features**: you can easily search dialogs or files in the channel, so you can quickly find the information you need.

### Manage channel <a href="#undefined" id="undefined"></a>

* **Create channel**: you can create a new channel suitable for your purpose and set information such as channel name, descriptions, and members.
* **Channel invitation**: the admin of the channel can invite other users to the channel. The user who is invited can accept or decline the invitation.
* **Manage members**: the admin can set the permissions of the channel members or remove members from the channel.

### Security <a href="#undefined" id="undefined"></a>

* **Data security**: all data in the channel are encrypted and transmitted, and are stored safely in the server.
* **Personal information protection**: the information shared in the channel can be accessed only among channel members and is protected against leak to the outside.

When you use the channel function of Game Chat, you can enjoy easy communication within the organization and among individuals, and manage information effectively. These features are very useful when you manage large-scale organizations or various projects.

### Create channel <a href="#undefined" id="undefined"></a>

All conversations require you to create channels and participate in the channel to chat normally. The following guides you on how to create and subscribe to channels.

```csharp
await nc.createChannel(new NBaseSDK.Channel
{
    name = "New Channel",
    type =[TYPE],    // PUBLIC or PRIVATE
    customField = [CustomField]
});
```

<table><thead><tr><th width="163">ID</th><th width="103">Type</th><th width="368">Description</th><th>Required</th></tr></thead><tbody><tr><td>NAME</td><td>string</td><td>Channel name</td><td>O</td></tr><tr><td>TYPE</td><td>string</td><td>Channel type (PUBLIC or PRIVATE)</td><td>O</td></tr><tr><td>UniqueID</td><td>string</td><td>Unique ID</td><td>X</td></tr><tr><td>push</td><td>boolean</td><td>Push notification status</td><td>X</td></tr><tr><td>linkUrl</td><td>string</td><td>Link status</td><td>X</td></tr><tr><td>imageUrl</td><td>string</td><td>Link status</td><td>X</td></tr><tr><td>integrationId</td><td>string</td><td>Integration feature (translation, voice, etc.)</td><td>X</td></tr><tr><td>disabled</td><td>string</td><td>Channel use status</td><td>X</td></tr><tr><td>members</td><td>array</td><td>ID allowed to join if PRIVATE</td><td>X</td></tr><tr><td>CustomField</td><td>string</td><td>User-defined field, can be put as a JSON String for more versatility</td><td>X</td></tr></tbody></table>

> Note
>
> * For security, create a channel through the server instead of creating a channel on the client side.

### Subscribe to channel <a href="#undefined" id="undefined"></a>

Subscribe to the desired channel (join the room). Once you join a channel, you will join automatically when you access it again until you unsubscribe from it.

```csharp
Hashtable option = new Hashtable
{
    { "language", "en" }    // In addition to the options required for automatic translation, various other options can also be added.
};
await nc.subscribe([CHANNEL_ID], option);
```

### Unsubscribe from channels <a href="#undefined" id="undefined"></a>

Unsubscribe from the channel. You will no longer receive messages from this channel.

```csharp
await nc.unsubscribe([CHANNEL_ID]);
```

### Participant list <a href="#undefined" id="undefined"></a>

You can import the participant list (for a specific channel).

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", channelId }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var subscriptions = await nc.getSubscriptions(filter, sort, option);
foreach (var subscription in subscriptions.edges)
{
    string id = subscription.node.id.ToString();
    Console.WriteLine("[CloudChatSample] id={0}", id);
}
```

* Parameters

<table><thead><tr><th width="121">ID</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>Search is available for all fields of a query through filtering</td></tr><tr><td>sort</td><td>object</td><td>Define the filter for the fields you want to sort (ascending order "1", descending order "-1")</td></tr><tr><td>option</td><td>object</td><td>See the following when there are options</td></tr></tbody></table>

* Filter

| ID          | Type    | Description               |
| ----------- | ------- | ------------------------- |
| project\_id | String  | Project ID                |
| channel\_id | String  | Channel ID                |
| user\_id    | String  | User ID                   |
| language    | String  | Language                  |
| uniquekey   | String  | Unique Key                |
| online      | Boolean | Online Status             |
| push        | Boolean | Push Notification Enabled |
| created\_at | String  | Creation Date             |
| updated\_at | String  | Update Date               |

* Sort

<table><thead><tr><th width="193">ID</th><th width="166">Type</th><th>Description</th></tr></thead><tbody><tr><td>created_at</td><td>number</td><td>Sort Date (Ascending '1', Descending '-1')</td></tr></tbody></table>

* Options

<table><thead><tr><th width="198">ID</th><th width="163">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>Start offset</td></tr><tr><td>per_page</td><td>number</td><td>The number of returns (up to 100)</td></tr></tbody></table>

#### **Advanced**

To import only a list of online users accessing a specific channel, add "online" as "true" to the filter.

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", [CHANNEL_ID] },
    { "online" , true}
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};

var subscriptions = await nc.getSubscriptions(filter, sort, option);

```

#### **Subscribe to channel**

* Subscription Data Class

<table><thead><tr><th width="207">ID</th><th width="109">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>Unique ID</td></tr><tr><td>channel_id</td><td>string</td><td>Channel ID</td></tr><tr><td>user_id</td><td>string</td><td>Unique ID of the user</td></tr><tr><td>created_at</td><td>string</td><td>Creation date</td></tr><tr><td>online</td><td>boolean</td><td>Whether the user is online</td></tr><tr><td>push</td><td>boolean</td><td>Whether the user allows push notifications</td></tr><tr><td>language</td><td>string</td><td>Language</td></tr><tr><td>channel</td><td>string</td><td>Channel information</td></tr><tr><td>mark.user_id</td><td>string</td><td>User who sent the last message</td></tr><tr><td>mark.message_id</td><td>string</td><td>ID of the last message</td></tr><tr><td>mark.sort_id</td><td>string</td><td>Last message sort ID</td></tr><tr><td>mark.unread</td><td>string</td><td>Number of unread messages since the last message</td></tr></tbody></table>

### Channel information <a href="#undefined" id="undefined"></a>

* ChannelData data class

| ID         | Type    | Description              |
| ---------- | ------- | ------------------------ |
| totalCount | Int     | Total Number of Channels |
| channels   | Channel | Channel Data List        |

* Channel Data Class

<table><thead><tr><th width="174">ID</th><th width="113">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>Channel ID (unique)</td></tr><tr><td>project_id</td><td>string</td><td>Project ID</td></tr><tr><td>unique_id</td><td>string</td><td>Channel ID that can be set by the developer (unique)</td></tr><tr><td>name</td><td>string</td><td>Channel name</td></tr><tr><td>user_id</td><td>string</td><td>User ID (that created the channel)</td></tr><tr><td>unique_id</td><td>string</td><td>Unique ID of channel</td></tr><tr><td>default_lang</td><td>string</td><td>Default language</td></tr><tr><td>lang</td><td>string</td><td>The language of the current user</td></tr><tr><td>members</td><td>string</td><td>If private, the list of participating users</td></tr><tr><td>last_message</td><td>array</td><td>See the last message information [MessageType]</td></tr><tr><td>push</td><td>boolean</td><td>Whether push messages are supported (if the channel is private)</td></tr><tr><td>state</td><td>boolean</td><td>Channel status</td></tr><tr><td>customField</td><td>string</td><td>User-defined data</td></tr><tr><td>created_at</td><td>string</td><td>Creation date</td></tr><tr><td>updated_at</td><td>string</td><td>Renewal date</td></tr></tbody></table>

#### **Import channel data**

Use the following code to import the channel data of a project in the form of a list.

```csharp
Hashtable filter = new Hashtable
{
    { "state", true }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var channels = await nc.getChannels(filter,sort,option);
foreach (var channel in channels.edges)
{
    string id = channel.node.id.ToString();
    Console.WriteLine("[CloudChatSample] id={0}", id);
}
```

* Parameters

<table><thead><tr><th width="113">ID</th><th width="106">Type</th><th width="419">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>Search is available for all fields of a query through filtering</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>Define a filter for the fields you want to sort</td><td>X</td></tr><tr><td>option</td><td>object</td><td>See the following when there are options</td><td>X</td></tr></tbody></table>

* Filter

<table><thead><tr><th width="229">ID</th><th width="215">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>String</td><td>Channel ID</td></tr><tr><td>project_id</td><td>String</td><td>Project ID</td></tr><tr><td>name</td><td>String</td><td>Channel Name</td></tr><tr><td>user_id</td><td>String</td><td>User ID</td></tr><tr><td>unique_id</td><td>String</td><td>Unique ID</td></tr><tr><td>type</td><td>String</td><td>Channel Type</td></tr><tr><td>push</td><td>Boolean</td><td>Push Notification Enabled</td></tr><tr><td>disabled</td><td>Boolean</td><td>Active Status</td></tr><tr><td>customField</td><td>String</td><td>Custom Fields</td></tr><tr><td>link_url</td><td>String</td><td>Link URL</td></tr><tr><td>image_url</td><td>String</td><td>Image URL</td></tr><tr><td>subscribed</td><td>Boolean</td><td>Subscription Status</td></tr><tr><td>unread</td><td>Int</td><td>Number of Unread Messages</td></tr><tr><td>created_at</td><td>String</td><td>Creation Date</td></tr><tr><td>updated_at</td><td>String</td><td>Update Date</td></tr></tbody></table>

* Sort

<table><thead><tr><th width="193">ID</th><th width="168">Type</th><th>Description</th></tr></thead><tbody><tr><td>created_at</td><td>number</td><td>ort Date (Ascending '1', Descending '-1')</td></tr></tbody></table>

<br>

* Options

<table><thead><tr><th width="190">ID</th><th width="161">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>Start offset</td></tr><tr><td>per_page</td><td>number</td><td>The number of returns (up to 100)</td></tr></tbody></table>

### Individual channel <a href="#undefined" id="undefined"></a>

* You can get information about individual channels.

```csharp
Channel channel = await nc.getChannel(id);
```

### Invite user to channel <a href="#undefined" id="undefined"></a>

Invite a user to participate when the channel is private.

```csharp
await nc.addUsers(newChannelId, new string[] { "ID", "ID" });
```

### Delete user from channel <a href="#undefined" id="undefined"></a>

Delete a user who is a participant when the channel is private.

```csharp
await nc.removeUsers(channelId, new string[] { "ID", "ID" });
```

### Block user from channel <a href="#undefined" id="undefined"></a>

Block a user within a channel. It can only be used by users who have permission to create a channel, or admin with full access.

```csharp
Hashtable option = new Hashtable
{
    { "timeout", [End Time (seconds)] },
    { "reason", [Reason for Blocking] }
};
await nc.banUser(channelId, userId, options);
```

* Options Data Class

<table><thead><tr><th width="158">ID</th><th width="176">Type</th><th>Description</th></tr></thead><tbody><tr><td>timeout</td><td>string</td><td>Block time (seconds)</td></tr><tr><td>reason</td><td>string</td><td>Cause of blocking</td></tr></tbody></table>

### Unblock user from channel <a href="#undefined" id="undefined"></a>

Unblock the blocked person within the channel. It can only be used by users who have permission to create a channel, or admin with full access.

```csharp
await nc.unbanUser(channelId, userId);
```

### Delete channel <a href="#undefined" id="undefined"></a>

Delete the corresponding channel (you can delete 1 channel or multiple channels).

```csharp
Channel channel = await nc.deleteChannel([CHANNEL_ID]);
```

### Edit channel <a href="#undefined" id="undefined"></a>

Update the channel information.

```csharp
Channel channel = await nc.updateChannel([CHANNEL_ID],new NBaseSDK.Channel
{
    name = "Update Channel",
    type =[TYPE],    // PUBLIC or PRIVATE
    customField = [CustomField]
});
```


# messages

## Message <a href="#undefined" id="undefined"></a>

The message function provided by Game Chat includes various services supporting efficient communication between users. This platform is suitable for group chat as well as personal chat, and it enables a simple, fast process of sending and receiving messages. The following describes Game Chat's main message functions and their features.

### 1. Instant messaging <a href="#id-1" id="id-1"></a>

* **Real-time communication**: you can send and receive messages in real time, which minimizes communication delay.
* **Supporting multiple devices**: you can send and receive messages on various devices such as smartphones, tablets, PCs, and so on.

### 2. Group chat <a href="#id-2" id="id-2"></a>

* **Multiple participants**: you can create a group chat that many people can participate in to share information and enhance communication within the team.
* **Manage channel**: the admin can add or delete members through the group chat, and adjust the group settings.

### 3. File sharing <a href="#id-3" id="id-3"></a>

* **Supporting various file formats**: you can easily share files in diverse formats such as texts, images, videos, and documents through the chat.
* **Safe file storage**: Game Chat saves and manages files in your Object Storage, preventing any information leaks.

### 4. Message search <a href="#id-4" id="id-4"></a>

* **Keywords search**: you can use a specific keyword to search for the past conversation content in the chat.
* **Advanced filter options**: you can quickly find the messages you want to search for by applying various filters, such as date, participant, and file format.

### 5. Notification adjustments <a href="#id-5" id="id-5"></a>

* **Push notifications**: when a new message or an important update occurs, a notification is sent to the user to prevent information omission.
* **Notification setting**: you can adjust the type and frequency of notification to receive the information in a desired way.

### 6. Security and personal information protection <a href="#id-6" id="id-6"></a>

* **Data encryption**: all messages are encrypted during transmission and storage to prevent data leaks from the outside.
* **Protecting personal information**: personal information and dialogs of the user are strictly protected, and are not disclosed to any third party without the consent of the user.

The message function of Game Chat promotes easy and efficient communication of the user, and has an important role in business and daily life. These functions promote easy user communication, and enhance teamwork.

## Forward message <a href="#undefined" id="undefined"></a>

If you have created and joined a channel, you can send a new message by calling the following:

```csharp
const message = 'Hello !!!';
await nc.sendMessage(
        channelId: CHANNEL_ID,
        type:"text",
        content: message
);


// When replying to a message
await nc.sendMessage(
        channelId: CHANNEL_ID,
        type:"text",
        content: message,
        parentMessageId: [MESSAGE_ID]
        );

// When an automatic translation is required for a message
await nc.sendMessage(
        channelId: CHANNEL_ID,
        type:"text",
        content: message,
        translate: true
        );

// In a new message, the contents of the parent message are reinforced and sent with parent_message as shown below.
{
    "id": "message_id",
    "text": "Message",
    "parent_message_id": "first_message_id",
    "parent_message": {
        "id": "message_id",
        "text": "message_name",
        "sender" : {
            "id" : "Sender",
             "name" : "Sender Nickname",
             "profile" : "profile url"
        }
    }
}
```

> Note
>
> If you send/receive messages in JSON format, you can use various user-defined values.

```csharp
Hashtable messageArray = new Hashtable
{
    { "channel_id", "channelId" },
    { "state", 1 },
    { "desc" , "Desc" }
};
// Convert the message to plain text.
const jsonString = JsonConvert.SerializeObject(messageArray);
// Convert the received message to an array.
Hashtable hashtable = JsonConvert.DeserializeObject<Hashtable>(jsonString);
```

<table><thead><tr><th width="177">ID</th><th width="96">Type</th><th>Description</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>Channel ID</td></tr><tr><td>type</td><td>string</td><td>Type of the message to send (text or image)</td></tr><tr><td>MESSAGE</td><td>string</td><td>Transfer message text; can be used in various ways if utilizing JSON String</td></tr><tr><td>MENTIONS</td><td>array</td><td>ID of the user to mention</td></tr></tbody></table>

* Using Express Message: this function is only for sending messages at high speed. By removing all parts that may cause a delay, messages can be transferred 10 times faster than with the previous method. The difference from normal sendMessage is as follows:

<table><thead><tr><th width="212">Function</th><th width="230">Description</th><th width="95">Filtering</th><th width="86">Block</th><th>Translate</th></tr></thead><tbody><tr><td>sendMessage</td><td>Send normal messages</td><td>O</td><td>O</td><td>O</td></tr><tr><td>sendExpressMessage</td><td>Send express messages</td><td>X</td><td>X</td><td>X</td></tr></tbody></table>

Available to use for any service that requires real-time PvP production or high-speed broadcasting within the game.

## Upload files <a href="#undefined" id="undefined"></a>

* You can transfer files to a specific channel.
* You can only upload allowed file types by navigating to Dashboard > Settings > Security.

```csharp
await nc.sendFile([CHANNEL_ID],file);
```

<table><thead><tr><th width="220">ID</th><th width="187">Type</th><th>Description</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>Channel ID</td></tr><tr><td>file</td><td>string</td><td>File information</td></tr></tbody></table>

> Note
>
> * Object Storage must be enabled.
> * You can use it after integrating with the [Object Storage](https://www.ncloud.com/product/storage/objectStorage) product.
> * When uploading, set the upload type and upload size, etc. in **Set Project > Security Settings** in the dashboard.
> * Supported file types: all general types such as images, videos, documents, and zips are supported. For an extension that needs to be supported additionally, send inquiries through Contact us, and we will add it after reviewing its security.
> * When using the file link, the Endpoint address is <https://apps.ncloudchat.naverncp.com.\\>
>   For example, <https://apps.ncloudchat.naverncp.com/archive/\\[archiveId>]

## Message information <a href="#undefined" id="undefined"></a>

* Message Data Class

<table><thead><tr><th width="239">ID</th><th width="132">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>ID (unique)</td></tr><tr><td>message_id</td><td>string</td><td>Message ID</td></tr><tr><td>sort_id</td><td>string</td><td>ID for sorting messages</td></tr><tr><td>message_type</td><td>string</td><td>Message type</td></tr><tr><td>sender.id</td><td>string</td><td>Sender ID</td></tr><tr><td>sender.name</td><td>string</td><td>Sender name</td></tr><tr><td>sender.profile</td><td>string</td><td>Sender's profile image</td></tr><tr><td>metions</td><td>string</td><td>List of mentions</td></tr><tr><td>metions_everyone</td><td>string</td><td>Whether everyone's mentioned</td></tr><tr><td>content</td><td>string</td><td>Message</td></tr><tr><td>created_at</td><td>string</td><td>Creation date</td></tr><tr><td>sended_at</td><td>string</td><td>Sent date</td></tr></tbody></table>

### Individual message information <a href="#undefined" id="undefined"></a>

You can get information about individual messages.

```csharp
NBaseSDK.Message message = await nc.getMessage([CHANNEL_ID], [MESSAGE_ID]);
```

### All messages information <a href="#undefined" id="undefined"></a>

You can get information on all messages.

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", [CHANNEL_ID] }
};
Hashtable sort = new Hashtable
{
    { "sort_id", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var messages = await nc.getMessages(filter, sort, option);
if (messages != null)
    {
            foreach (var message in messages.edges)
        {
            string id = message.Node.message_id.ToString();
            Console.WriteLine("[CloudChatSample] id={0}", id);
        }
    }
```

* Parameters

<table><thead><tr><th width="99">ID</th><th width="89">Type</th><th width="461">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>Search is available for all fields of a query through filtering</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>Define a filter for the fields you want to sort</td><td>X</td></tr><tr><td>option</td><td>object</td><td>See the following when there are options</td><td>X</td></tr></tbody></table>

* Filter

  <table><thead><tr><th>ID</th><th width="207">Type</th><th>Description</th></tr></thead><tbody><tr><td>message_id</td><td>String</td><td>Message ID</td></tr><tr><td>channel_id</td><td>String</td><td>Channel ID</td></tr><tr><td>sort_id</td><td>String</td><td>Sort ID</td></tr><tr><td>message_type</td><td>String</td><td>Message Type입</td></tr><tr><td>embedProviders</td><td>String</td><td>Embed Provider</td></tr><tr><td>isExpress</td><td>Boolean</td><td>Immediate Message Status</td></tr><tr><td>bytes</td><td>Int</td><td>Message Byte Size</td></tr><tr><td>content</td><td>String</td><td>Message Content</td></tr><tr><td>sended_at</td><td>String</td><td>Message Send Time</td></tr><tr><td>created_at</td><td>String</td><td>Message Creation Time</td></tr></tbody></table>
* Sotr

  <table><thead><tr><th width="201">ID</th><th width="151">Type</th><th>Description</th></tr></thead><tbody><tr><td>created_at</td><td>number</td><td>Creation Date (Ascending '1', Descending '-1')</td></tr></tbody></table>
* Options

<table><thead><tr><th width="175">ID</th><th width="178">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>Start offset</td></tr><tr><td>per_page</td><td>number</td><td>Number of items returned (up to 100)</td></tr></tbody></table>

## Unread messages <a href="#undefined" id="undefined"></a>

Return the number of unread messages. Send the information of the last read message through markRead first.

```csharp
nc.markRead([CHANNEL_ID], new NBaseSDK.MarkInput
{
    user_id = USER_ID,
    message_id = MESSAGE_ID,
    sort_id = SORT_ID
});
// Return the number of unread messages after being marked.
var unread = nc.unreadCount([CHANNEL_ID]);
```

<table><thead><tr><th width="192">ID</th><th width="110">Type</th><th>Description</th></tr></thead><tbody><tr><td>USER_ID</td><td>string</td><td>Enter the user_id contained in the message</td></tr><tr><td>MESSAGE_ID</td><td>string</td><td>Enter the message_id contained in the message</td></tr><tr><td>SORT_ID</td><td>string</td><td>Enter the sort_id contained in the message</td></tr></tbody></table>

## Delete message <a href="#undefined" id="undefined"></a>

You can delete messages you sent within the channel.

```csharp
await nc.deleteMessage([CHANNEL_ID], [MESSAGE_ID]);
```

* Parameters

| ID          | Type   | Description |
| ----------- | ------ | ----------- |
| CHANNEL\_ID | string | Channel ID  |
| MESSAGE\_ID | string | Message ID  |


# Events

## Events <a href="#undefined" id="undefined"></a>

Ncloud Chat provides the Event Listener function, which can handle diverse events that occur from the client side. With this function, you can monitor many circumstances occurring in the chat application in real time and respond to them properly. The following describes the main events and how to handle events.

## Main event types <a href="#undefined" id="undefined"></a>

1. **Receive message**: triggered when a new message is received.
2. **Delete message**: triggered when a message is deleted.
3. **Error message**: triggered when an error occurs.
4. **Connected**: triggered when successfully connected to the server.
5. **Disconnected**: triggered when disconnected from the server.
6. **Typing start and end**: triggered when you start or end typing.
7. **Add and remove members**: triggered when a user is added or removed.
8. **Member suspension and withdrawal**: triggered when a user gets suspended in the channel or withdraws from the channel.

The following shows how to listen for events on the client side.

```csharp
nc.dispatcher.onMessageReceived += message =>
{
    Console.WriteLine("received a new message: ", message);
}
```

## Connect and disconnect event handler <a href="#undefined" id="undefined"></a>

With event handlers, you can receive diverse events, and implement the logic you need. The following codes show how to connect and disconnect the event handler for each event.

```csharp
// Message Received
nc.dispatcher.onMessageReceived += e =>
{
    Console.WriteLine("onMessageReceived: ", e);
};

// Message Deleted
nc.dispatcher.onMessageDeleted += e =>
{
    Console.WriteLine("onMessageDeleted: ", e);
};

// Error Message
nc.dispatcher.onErrorReceived += e =>
{
    Console.WriteLine("[CloudChatSample] onErrorReceived: ", e);
};

// Connection Successful
nc.dispatcher.onConnected += e =>
{
    Console.WriteLine("[CloudChatSample] Connected to server with id: {0} ", e);
};

// Connection Closed
nc.dispatcher.onDisconnected += e =>
{
    Console.WriteLine("Disconnected");
};

// When Typing Starts
nc.dispatcher.onStartTyping += e =>
{
    Console.WriteLine("onStartTyping: ", e);
};

// When Typing Ends
nc.dispatcher.onStopTyping += e =>
{
    Console.WriteLine("onStopTyping: ", e);
};

// When a User Subscribes to the Channel
nc.dispatcher.onMemberAdded += e =>
{
    Console.WriteLine("onMemberAdded: ", e);
};

// When a User Unsubscribes from the Channel
nc.dispatcher.onMemberLeft += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberLeft: ", e);
};

// When a User is Suspended from the Channel
nc.dispatcher.onMemberBanned += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberBanned: ", e);
};

// When a User Leaves the Channel
nc.dispatcher.onMemberDeleted += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberDeleted: ", e);
};

nc.dispatcher.onSubscriptionUpdated += e =>
{
    Console.WriteLine("[CloudChatSample] onSubscriptionUpdated: ", e);
};
```

With Event Listener, the user of Ncloud Chat can identify the change of the chat environment in real time and respond to it properly.


# Friendship

## Manage friends <a href="#undefined" id="undefined"></a>

Ncloud Chat provides functions of inviting and managing friends to facilitate social networking among users. Through this system, you can perform various friend management tasks such as inviting, accepting, refusing, and deleting friends. The following describes the main details of friend management features and how to use each function.

## Friend list <a href="#undefined" id="undefined"></a>

You can view the list of your friends and, by extension, filter and view friends in a specific status. The list is managed through paging options so that you can manage many users effectively.

```csharp
Hashtable filter = new Hashtable
{
    { "status", "accepted" },
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 },
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 },
};
var friends = await nc.getFriendships(filter, sort, option);
```

* **Filter**: filters based on the status of the friend you want to view (e.g., "accepted").
* **Sort**: sets the criteria to sort the results. Here, sorting in descending order is used based on the creation time.
* **Option**: sets the scope of data you want to view. `offset` specifies the location where the data starts, and `per_page` specifies the number of messages to be returned per page.

## Invite <a href="#undefined" id="undefined"></a>

Invites a certain friend as a friend. The user who is invited can accept or decline this request.

```csharp
var response = await nc.requestFriend(friendId);
```

* **friendId**: identifier of the user you want to invite.

## Accept <a href="#undefined" id="undefined"></a>

Accepts the friend invitation you received. Through this, two users have a mutual friendship.

```csharp
var response = await nc.acceptFriend(friendId);
```

* **friendId**: user identifier of the friend invitation you want to accept.

## Reject <a href="#undefined" id="undefined"></a>

Rejects the friend invitation you received. When you reject the request, you can't have the other person as a friend.

```csharp
var response = await nc.rejectFriend(friendId);
```

* **friendId**: user identifier of the friend invitation you want to reject.

## Delete <a href="#undefined" id="undefined"></a>

Deletes a certain user from the friend list. This task might be performed regardless of friend status or invitation status.

```csharp
var response = await nc.removeFriend(friendId);
```

* **friendId**: user identifier of the friend you want to delete.

The friend management features promote interaction among users, and has an important role in enhancing networking. Through this function, you can easily expand and manage your social network.


# Push

## Push <a href="#undefined" id="undefined"></a>

In Game Chat, push notifications are a core function that informs you of important information or updates in real time. Through this push notifications service, you don't miss any important message even when the app is in the background or the device is not activated. The following describes the push notifications functions of Game Chat.

## Main functions of push notifications <a href="#undefined" id="undefined"></a>

1. **Real-time notification**: chat-related notifications such as new messages, member changes, and event invitations are immediately sent to you.
2. **Customizable**: you can customize the format and contents of the notifications suited for the application's requirements.
3. **Multiple platforms supported**: it supports push notifications for various mobile operating systems such as iOS and Android to expand the user base.
4. **Battery and data efficiency**: it minimizes battery consumption and data usage with the recent push technology and sends notifications efficiently.
5. **Interactive notification**: you can include interactive components to allow you to respond in the notification itself directly. For example, you can reply directly to a message, or respond to an invitation.

## Implementation methods of push notifications <a href="#undefined" id="undefined"></a>

To implement the push notifications service, Game Chat API provides a few core components:

* **Register push tokens**: you can register a push token of your device to the Game Chat server to allow sending a notification to the corresponding device.
* **Manage notification settings**: you can set whether you will receive a notification depending on your preference for notifications.
* **Backend integration**: the server side can create and send push notifications in real time by integrating with the backend of Game Chat.

## Security and personal information protection <a href="#undefined" id="undefined"></a>

* **Data encryption**: all push notifications are encrypted during transfer and protected from external access.
* **Compliance with the Personal Information Protection Act**: Game Chat takes users' personal information protection very seriously, and provides notification services in accordance with related laws and regulations.

Through the push notifications function, Game Chat induces user participation, increases the application usage rate, and enhances user experience. You can be connected anytime, anywhere, so you don't miss important communication.

## Android(Kotlin)

After adding the Android app in the [Firebase Console](https://console.firebase.google.com/), download the `google-services.json` file and place it in the root folder of your project app module.\
After adding the file, include the following content in `bundle.gradle.kts`.

```kotlin
plugins {
...
    id("com.google.gms.google-services")
...
}
dependencies {
...
    implementation("com.google.firebase:firebase-messaging-ktx:23.2.1")
...
}
```

Requesting push notification permission popup.

```kotlin
import com.nbase.sdk.Permission

NChat.setEnablePush(true)
NChat.requestPermission(this, Permission.NOTIFICATION)
// It must be called before initialize.
```

Call `setPushState` to configure push notification receipt status after connecting.

```kotlin
NChat.setPushState(PushState([PUSH], [AD], [NIGHT])) { state, e ->
    if (e != null) {
        // Error
    } else {
        // Success
    }
}
```

<table><thead><tr><th width="142">ID</th><th width="132">Type</th><th>Description</th></tr></thead><tbody><tr><td>push</td><td>boolean</td><td>Push Notification On/Off (true = On)</td></tr><tr><td>ad</td><td>boolean</td><td>Must be called with true for receiving push notifications</td></tr><tr><td>night</td><td>boolean</td><td>Nighttime Push Notification On/ Off</td></tr></tbody></table>

### Android (Kotlin) Push Click Event

You can set up an Android push click handler.

```kotlin
NChat.setNotificationClickedHandler { notification ->
    val title = notification.title
    val content = notification.body
    val channel = notification.data?.get("channel") ?: ""
    val imageUrl = notification.data?.get("imageUrl") ?: ""
    val url = notification.data?.get("url") ?: ""
    val metadata = notification.data?.get("metadata") ?: ""
    
    // Define the desired action when a push notification is clicked.
}
```

## Android (Java) <a href="#androidjava" id="androidjava"></a>

1. Add the following repository in the project's `build.gradle`.

```javascript
allprojects {
    repositories {
    	...
        google()
    	// nbase repo
        maven { url "https://repo.nbase.io/repository/nbase-releases" }
	...
    }
}
```

2. Add the following content in the `build.gradle` of the app module.

```javascript
dependencies {
    ...
    implementation ("io.nbase:nbasesdk:3.0.78")
    implementation ("io.nbase:nbase-adapter-cloudchat:1.0.17")
    implementation ("com.google.firebase:firebase-messaging-ktx:23.2.1")
    ...
}
```

### **Android (Java)** Push Click Event

You can set up an Android push click handler.

```javascript
NChat.INSTANCE.setNotificationClickedHandler(notification -> {
    // Define the desired action when a push notification is clicked.
    String title = notification.getTitle();
    String content = notification.getBody();
    String channel = notification.getData() != null ? notification.getData().get("channel") : "";
});
```

#### **Android Push Data**

This is a list of values delivered through the Android push click handler.

<table><thead><tr><th width="225">Key</th><th>Description</th></tr></thead><tbody><tr><td>Title</td><td>The title set in the push message</td></tr><tr><td>Body</td><td>The content set in the push message</td></tr><tr><td>Data.channel</td><td>For chat room pushes, the CHANNEL_ID where the push occurred</td></tr></tbody></table>

iOS(Swift)

Add app push notification permissions. Go to the Target's Signing & Capabilities, click the '+' in the top left corner, and select 'Capability > Push Notifications' to add.

<figure><img src="/files/pxOzkssP7zSAorIWmDdq" alt=""><figcaption></figcaption></figure>

Create a new `AppDelegate.swift` file or define the following content in the existing `AppDelegate.swift`.

```swift
import UIKit
import NChat

class AppDelegate: NSObject, UIApplicationDelegate {
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Push Notification Permission Request
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            print("Permission granted: \(granted)")
        }
        
        UNUserNotificationCenter.current().delegate = self
        application.registerForRemoteNotifications()
        
        // Main Window Configuration
        window = UIWindow(frame: UIScreen.main.bounds)
        let initialViewController = UIViewController()
        initialViewController.view.backgroundColor = .white
        window?.rootViewController = initialViewController
        window?.makeKeyAndVisible()
        
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // Convert the device token to a string
        let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
        let token = tokenParts.joined()
        
        // To receive push notifications in the sandbox environment, set sandbox: true.
        NChat.setPushToken(token: token, sandbox: false)
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("RegisterForRemoteNotifications Failed: \(error.localizedDescription)")
    }
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        if #available(iOS 14.0, *) {
            completionHandler([.banner, .list, .sound, .badge])
        } else {
            completionHandler([.alert, .sound, .badge])
        }
    }
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        do {
            try handleNotificationClick(userInfo: userInfo, actionIdentifier: response.actionIdentifier)
        } catch let error as NotificationError {
            print("NotificationError: \(error.localizedDescription)")
        } catch {
            print("UnexpectedError: \(error.localizedDescription)")
        }

        // Call the push notification handling function of the NChat library.
        NChat.handlePushNotification(userInfo: userInfo)
        completionHandler()
    }
}

// Define notification-related errors.
enum NotificationError: LocalizedError {
    case invalidUserInfo(String)
    case navigationError(String)

    var errorDescription: String? {
        switch self {
        case .invalidUserInfo(let message):
            return "잘못된 사용자 정보: \(message)"
        case .navigationError(let message):
            return "네비게이션 오류: \(message)"
        }
    }
}

extension UIViewController {
    func topMostViewController() -> UIViewController {
        if let presented = self.presentedViewController {
            return presented.topMostViewController()
        }
        if let navigation = self as? UINavigationController {
            return navigation.visibleViewController?.topMostViewController() ?? navigation
        }
        if let tab = self as? UITabBarController {
            return tab.selectedViewController?.topMostViewController() ?? tab
        }
        return self
    }
}
```

> Note\
> For push notifications in the sandbox environment, use\
> `NChat.setPushToken(token: token, sandbox: true)`\
> The `sandbox` value must be set to true for notifications to be received correctly.

Call `setPushState` to configure the push notification receipt status after connecting.

```swift
NChat.setPushState(push: true, ad: true, night: true) { result in
    switch(result)
    {
    case .success(let status) :
        // Success
        break;
    case .failure(let error) :
        // Failure
        break;
    }
}
```

<table><thead><tr><th width="138">ID</th><th width="134">Type</th><th>Description</th></tr></thead><tbody><tr><td>push</td><td>boolean</td><td>Push Notification On/ Off (true = On)</td></tr><tr><td>ad</td><td>boolean</td><td>Must be called with true for receiving push notifications</td></tr><tr><td>night</td><td>boolean</td><td>Nighttime Push Notification On/Offff</td></tr></tbody></table>

### **iOS (Swift) Push Click Event**

You can set up an iOS push click handler.\
Define it in `AppDelegate.swift` as shown in the example below.

```swift
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?
    // Notification Click Handling Function
    private func handleNotificationClick(userInfo: [AnyHashable: Any], actionIdentifier: String) throws {
        if actionIdentifier == UNNotificationDefaultActionIdentifier {
            showNotificationPopup(with: userInfo)
        } else {
            handleCustomAction(actionIdentifier, userInfo: userInfo)
        }
    }

    // Custom Action Handling Function
    private func handleCustomAction(_ actionIdentifier: String, userInfo: [AnyHashable: Any]) {
        switch actionIdentifier {
        case "ACTION_1":
            showNotificationPopup(with: userInfo, title: "ACTION_1")
        case "ACTION_2":
            showNotificationPopup(with: userInfo, title: "ACTION_2")
        default:
            print("actionIdentifier: \(actionIdentifier)")
        }
    }

    // Function to Display Notification Popup
    private func showNotificationPopup(with userInfo: [AnyHashable: Any], title: String = "알림") {
        DispatchQueue.main.async {
            let alertController = UIAlertController(title: title, message: "알림 수신됨", preferredStyle: .alert)

            // Add the contents of userInfo to the message
            for (key, value) in userInfo {
                alertController.message?.append("\n\(key): \(value)")
            }

            let okAction = UIAlertAction(title: "확인", style: .default, handler: nil)
            alertController.addAction(okAction)

            // Find the key window to display the popup
            if let keyWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
                if let topViewController = keyWindow.rootViewController?.topMostViewController() {
                    topViewController.present(alertController, animated: true, completion: nil)
                }
            } else {
                print("Unable to find the key window")
            }
        }
    }
}
```

#### iOS Push Data&#x20;

This is a list of values delivered through the iOS push click handler.

<table><thead><tr><th width="209">Key</th><th>Description</th></tr></thead><tbody><tr><td>Title</td><td>The title set in the push message</td></tr><tr><td>Body</td><td>The content set in the push message</td></tr><tr><td>channel</td><td>For chat room pushes, the CHANNEL_ID where the push occurred</td></tr></tbody></table>


# Import and export

## Import and export <a href="#undefined" id="undefined"></a>

Large-scale migration services can be largely performed in 2 ways. We recommend that you use the premium services for large-scale migration (free).

1. **Migration through hard conversion**:
   * Service interruption is required, and you must upgrade an application.
   * Reserve the best time to interrupt the service.
   * Export related data in the correct import format of the Game Chat platform.
   * Import the data to Game Chat through the Game Chat dashboard.
   * Validate and check data integrity.

Through this procedure, you can manage the migration process effectively and make a better start of a new chat service on the Game Chat platform. With premium support, you can proceed with these steps more easily by communicating with the engineering team in real time.

## Import <a href="#undefined" id="undefined"></a>

1. You can enter a large volume of data through API.
2. If you forward the data converted into the data format (JSON) suitable for Game Chat, you can add data in bulk at a specified time. Premium support services are recommended.

## Export <a href="#undefined" id="undefined"></a>

Each menu has export, and the exported data can be downloaded in Help => Activities & Files.


# Pinned message

## Pinned message <a href="#undefined" id="undefined"></a>

In a chat, Pinned Message is a function that pins important messages in a chat room or a group chat to the top of the chat window. This function helps participants see the message easily whenever they open the chat room, and not miss important information or notifications. The following describes the main characteristics of pinned messages and how to use them.

### How to use pinned messages <a href="#undefined" id="undefined"></a>

* **Meeting schedule notice**: sets the schedule of regular meetings or important events as a pinned message to help participants not forget their schedule.
* **Important document links**: pins the links of important documents and materials to allow all participants to access them easily.
* **Rules and guides sharing**: sets the rules of the chat room or project guides as a pinned message to allow new participants to check the guides easily.
* **Urgent notification**: allows sharing the content that needs to be forwarded urgently or any changes with a pinned message.

The pinned messages function is provided in various communication platforms. When you use it effectively, you can enhance the efficiency of team communication.

### Create pinned message <a href="#undefined" id="undefined"></a>

It is a function that pins an important message to the top of the chat application so that users can easily see it. The following C# code shows how to pin messages in the chat channel.

```csharp
var newPin = await nc.createPin(channelId, messageId, pinned, pinnedAt, expiredAt);
```

* `channelId`: the unique identifier of the chat channel where the message will be pinned.
* `pinned`: contents of a message to be pinned.
* `pinnedAt`: displays the time when the message is pinned.
* `expiredAt`: the time when the message will be unpinned.

When you use this function, you can easily highlight important messages in a specific chat channel.

### Edit pinned message <a href="#undefined" id="undefined"></a>

It is a function to update the information of the existing pinned messages. You can change the contents of the message, and the time when the message is pinned and will be unpinned.

```csharp
var updatedPin = await nc.updatePin(id, channelId, pinned, pinnedAt, expiredAt);
```

* `channelId`: ID of the channel where there are messages to be edited.
* `pinned`: the edited message content.
* `pinnedAt`: the time when the message is newly pinned.
* `expiredAt`: the newly set time when the message will be unpinned.

This code is used to change the details of the messages already pinned. It is useful when the importance of the message is changed or the time set for the message to be pinned needs to be changed.

### Pinned message information <a href="#undefined" id="undefined"></a>

It is a function to view the information related to pinning certain messages. You can check the status of the pinned message, and the time when the message is pinned and will be unpinned.

```csharp
var pin = await nc.getPin(channelId, messageId);
```

* `channelId`: ID of the channel from which to retrieve information.
* `messageId`: the unique identifier of the pinned message.

Through this function, you can check the current status of a specific message, which helps the admin or users manage messages in the channel effectively.

### Pinned message list <a href="#undefined" id="undefined"></a>

It is a function that views the list of all messages currently pinned in the chat channel. This function supports paging, so the data can be processed efficiently even in a large-scale channel. Users can set `offset` and `per_page` to bring up the data in the desired range.

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", channelId },
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 },
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 },
};
var pins = await nc.getPins(channelId, filter, sort, option);
```

#### **Parameter descriptions**

* **Filter**: defines the conditions for filtering the data to be viewed. For example, you can view pinned messages in a specific channel.
* **Sort**: defines how to sort the results list. Here, sorting in descending (-1) order is used based on the creation time (`created_at`).
* **Option**: defines the options to be used when viewing. `offset` specifies the location where the view starts, and `per_page` specifies the number of messages to be shown per page.

#### **Options details**

<table><thead><tr><th width="118">ID</th><th width="102">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>Start location where the data will be brought up.</td></tr><tr><td>per_page</td><td>number</td><td>The number of messages to be returned per page, and up to 100 messages can be set.</td></tr></tbody></table>

If you use this function, the channel manager can easily monitor and manage important messages in the channel. Also, the channel manager can quickly find and sort pinned messages based on the specific user or time, which helps operate the channel efficiently.


# External integration

## External integration <a href="#undefined" id="undefined"></a>

Integrating with external services or diverse product lines in the chat application improves user experience, and allows more functions to be provided. For example, you can integrate translation services, AI-based content recommendations, and product recommendations. The following describes how to integrate these functions with the chat application:

### External integration example <a href="#undefined" id="undefined"></a>

* Integrating with translation services: if you need multilingual support in the chat application, you can integrate translation services such as Papago Translation API. When you enter a message, the message is translated through API and the result is displayed in a chat room.
* AI-based content recommendations: AI can recommend personalized content by analyzing your chat content and behavior patterns. For example, it can recommend films or TV programs suited to your interests such as Netflix's recommendation system.
* Automated customer support: you can introduce a chatbot to handle basic customer inquiries automatically. The AI chatbot can understand your questions to provide proper answers or connect you to a human agent, if necessary.

Through this integration, the chat application can expand beyond a simple message exchange tool to a platform that integrates diverse services and provides a rich user experience.

### External integration service list <a href="#undefined" id="undefined"></a>

* Push (NPush)
* Translation (Papago)
* Analyze image
* Analyze emotion
* HyperClova X
* Object Storage


# Usage examples

## Example

### Ncloudchat React example

All sources are open in GitHub. You can download [GitHub sources](https://github.com/nbase-io/CloudChat-JS-Demo) and use them through [https://www.ncloudchat.com](https://www.ncloudchat.com/).

### Full simple code example <a href="#undefined" id="undefined"></a>

This is an example of connecting, creating a channel, and sending a subscription message to the created channel.

```csharp

// Initialization 
CloudChat nc = CloudChat.GetInstance();
await nc.initialize([PROJECT_ID]);
nc.dispatcher.onMessageReceived += e =>
{
    Console.WriteLine("received a new message: ", e);
};
await nc.Connect(
    userId: 'guest@company',
    name: 'Guest',
    profile: 'https://image_url',
    customField: 'json',
);
// Create channel
var channel = await nc.createChannel(new CloudChatSDK.Channel
{
    name = "New Channel",
    type = "PUBLIC",    // PUBLIC or PRIVATE
    customField = "customField"
});
var channel = await nc.createChannel({type:'PUBLIC', name:'First Channel', customField:'customField'});
var channel_id = channel.createChannel.channel.id.ToString();
// Subscribe to channel
await nc.subscribe(channel_id);
// Send message
var response = await nc.sendMessage(
        channelId: channel_id, 
        type:"text", 
        content: message
    );
```


# Troubleshooting

The following describes the errors that may occur while you use the service and how to troubleshoot them.

## 1. When creating a channel, I get a message that reads "Unable to verify address." <a href="#id-1" id="id-1"></a>

This error occurs when the link\_url you’ve entered is not in the default URL form. Do not enter an address at all or enter the correct address.

## 2. I can’t upload my image. <a href="#id-2" id="id-2"></a>

For security reasons, you can’t upload image types that aren’t allowed.

In **Dashboard > Settings > Allowed Image Upload Types**, enter the MIME TYPE to be allowed such as image/webp, image/heic, image/heic-sequence, image/heif, image/heif-sequence, image/svg+xml ,image/bmp, image/gif, image/jpeg, image/png.

Object Storage must be enabled.

* You can use it after integrating with [Object Storage](https://www.ncloud.com/product/storage/objectStorage) product.

## 3. All messages are received. <a href="#id-3" id="id-3"></a>

If you are subscribed to various channels, you receive messages from all those channels.\
You can distinguish them through channelId.

```javascript
nc.bind('onMessageReceived',function(channel, message) {
// If you are subscribed to various channels, this is where you receive messages from all those channels.
// Channels to be shown to customers need to be distinguished through channel.
if(channel == current_channel) {
console.log(message);
}
});
```


# Game Chat(日本語)


# V3の使用を開始

## ダッシュボードメニュー <a href="#undefined" id="undefined"></a>

ダッシュボードでは、アクセス状況、メッセージ、統計などチャットの運用状況を一目で把握できます。日付を選択してグラフを確認できます。

ダッシュボードのメニューは次の通りです。

| 項目                 | 説明                                    |
| ------------------ | ------------------------------------- |
| ① **ホーム**          | サービス使用量と使用状況の確認                       |
| ② **分析**           | ユーザーと同時アクセス者の分析                       |
| ③ **ユーザー**         | ユーザーの確認と利用停止ユーザーの管理                   |
| ④ **チャット**         | チャットチャンネルの追加とチャンネルの管理                 |
| ⑤ **メッセージ**        | 期間単位でチャットメッセージの検索とエクセル抽出              |
| ⑥ **アーカイブ**        | チャット間でやりとりしたすべてのファイル(画像/動画)などを確認      |
| ⑦ **プッシュ通知**       | プッシュ送信と履歴確認                           |
| ⑧ **設定**           | プロジェクトの一般、セキュリティ、連携サービス、ダッシュボード管理者の設定 |
| ⑨ **アクティビティとファイル** | 検索メニューでデータをエクスポートした履歴の確認              |
| ⑩ **ガイド**          | Game Chat ご利用ガイドに移動                   |

## ユーザー <a href="#undefined" id="undefined"></a>

ユーザーメニューでは、ダッシュボードに登録されたユーザー情報を確認したり、特定ユーザーのチャット利用を停止したり、すべてのチャットから退会させることができます。

### ユーザー情報の確認 <a href="#undefined" id="undefined"></a>

Game Chatダッシュボードに登録されたユーザーの情報を確認する方法は、次の通りです。

1. Game Chatダッシュボードで **ユーザー** > **複数ユーザー** メニューをクリックします。
2. ユーザーの詳細情報を確認するには、ユーザー IDをクリックします。
3. 画面のポップアップで詳細情報を確認します。
   * ユーザーの名前、プロファイル URL、アクセスした国、IPアドレス、モデル、デバイス ID、登録日、最終ログイン日などの機能確認や、カスタムフィールドとノート機能を提供
4. ユーザー情報を変更するには、項目を変更した後に **\[保存]** ボタンをクリックします。

### ユーザーの退会 <a href="#undefined" id="undefined"></a>

特定ユーザーを退会させる方法は、次の通りです。

1. Game Chatダッシュボードで **ユーザー** > **複数ユーザー** メニューをクリックします。
2. 退会させるユーザー IDをクリックします。
3. 画面にユーザー詳細情報が表示されたら、 **\[削除]** ボタンをクリックします。
4. ポップアップの確認画面が表示されたら、 **\[削除]** ボタンをクリックします。

### ユーザーの検索 <a href="#undefined" id="undefined"></a>

Game Chatダッシュボードに登録されたユーザーを検索する方法は、次の通りです。

1. Game Chatダッシュボードで **ユーザー** > **複数ユーザー** メニューをクリックします。
2. 検索の条件を設定し、 **\[検索]** ボタンをクリックします。
   * ユーザー ID、名前、IPアドレスを条件に検索可能
3. 検索結果を確認します。

### ユーザーの利用停止 <a href="#undefined" id="undefined"></a>

特定ユーザーが一定期間チャットを使用できないように設定できます。停止された複数ユーザーメニューでは、利用停止中のユーザーを確認したり、検索できます。\
特定のユーザーのチャット利用を停止する方法は、次の通りです。

1. Game Chatダッシュボードで **ユーザー** > **停止された複数ユーザー** メニューをクリックします。
2. 右側にある **\[追加]** ボタンをクリックします。
3. 追加ポップアップが表示されたら、ユーザー IDを検索して一時停止と永久停止、基本言語を設定できます。
4. 利用停止したいユーザーをすべてのチャンネルからも追放するには、 **すべてのチャットから追放する** チェックボックスをクリックします。
5. ユーザー ID、利用停止の理由、利用停止期間を設定して **\[追加]** ボタンをクリックします。

## チャット <a href="#undefined" id="undefined"></a>

チャットメニューでは、チャンネルを確認してチャットメッセージを送信できます。

### チャットチャンネルの追加 <a href="#undefined" id="undefined"></a>

新しいチャットチャンネルを追加する方法は、次の通りです

1. Game Chatダッシュボードで **チャンネル** メニューをクリックします。
2. **\[追加]** ボタンをクリックします。
3. チャンネルは **公開チャット** と **非公開チャット** に分けて作成できます( **公開** は最大200,000人が参加できるチャットチャンネルであり、 **非公開** は1:Nでプライベートなチャンネルを作成できます)。
4. チャンネル名と固有 IDを入力し、 **\[追加]** ボタンをクリックします。
   * 固有 IDの入力時に SDKでその値を利用してチャンネルにアクセス可能
   * プッシュと自動翻訳を選択でき、連携で追加サービスを連携して使用できます。
5. チャンネルが作成されたか確認します。

### チャットチャンネルの設定 <a href="#undefined" id="undefined"></a>

特定のチャットチャンネルに参加中のユーザーを確認したり、チャンネル情報を変更または削除する方法は、次の通りです。

1. Game Chatダッシュボードで **チャンネル** メニューをクリックします。
2. チャンネルを選択した後、チャンネル画面右上にある **...** アイコンをクリックします。
3. コンテキストメニューが表示されたら、タスクを選択します。
   * **サブスクライバー** : チャットチャンネルに参加したユーザーリストを確認するときにクリック
   * **変更** : チャットチャンネル情報を変更するときにクリック
   * **削除** : チャットチャンネルを削除するときにクリック

### 画像メッセージの送信 <a href="#undefined" id="undefined"></a>

特定のチャットチャンネルに参加中のユーザーを確認したり、チャンネル情報を変更または削除する方法は、次の通りです。

1. Game Chatダッシュボードで **チャンネル** メニューをクリックします。
2. チャンネルを選択した後、チャットメッセージの作成フィールド右にあるファイル添付アイコンをクリックします。

> 参考
>
> サポート画像タイプ: image/bmp、image/gif、image/jpeg、image/png、image/webp、image/heic、image/heic-sequence、image/heif、image/heif-sequence、image/svg+xml

## メッセージ <a href="#undefined" id="undefined"></a>

メッセージメニューでは、プロジェクトのすべてのチャンネルでやり取りしたメッセージを確認・検索できます。ID、ハンドルネーム、メッセージ、チャンネル ID、メッセージ送信日時により検索できます。また、メッセージリストを CSVファイルでダウンロードできます。

### メッセージ検索とメッセージ詳細情報の確認 <a href="#undefined" id="undefined"></a>

メッセージの詳細情報を確認する方法は、次の通りです。

1. Game Chatダッシュボードで **メッセージ** メニューをクリックします。
2. 検索の条件を設定し、 **\[検索]** ボタンをクリックします。
   * 送信者 ID、送信者名、チャット ID、ハンドルネーム、メッセージ内容を条件に検索可能
3. 詳細情報を確認するメッセージをクリックします。
4. そのメッセージが登録されたユーザー ID、名前、チャット ID、メッセージ ID、メッセージ内容、作成日を確認できます。

### メッセージ削除 <a href="#undefined" id="undefined"></a>

特定メッセージを検索して削除できます。検索メニューで削除したメッセージは、そのチャットチャンネルからも削除されます。

1. Game Chatダッシュボードで **メッセージ** をクリックします。
2. 削除するメッセージをクリックします。
3. メッセージ表示画面で削除を選択し、 **\[削除]** ボタンをクリックします。

## アーカイブ <a href="#undefined" id="undefined"></a>

アーカイブメニューでは、プロジェクトのすべてのチャンネルでやり取りした画像とファイルを確認・検索できます。使用有無、送信者、チャット ID、プレビュー、ファイル名、フォーマット、サイズ、送信数、作成日、終了日を確認できます。特定ファイルを選択してユーザーを使用停止・削除できます。

## プッシュ通知 <a href="#undefined" id="undefined"></a>

プッシュ通知は、アプリパブリッシャから送信され、モバイル機器に表示されるメッセージです。この通知は、ユーザーのアプリ・機器の有効化の使用有無に関係なく、いつでも送信できます。いくつかの主な事項を確認します。

* メッセージペイロードは JSONのサイズで、4KBに制限されます。
* 国外に通知する場合、予約された時間を基準に各国の現地時間よって送信されます。\
  プッシュ通知を設定し、送信されたプッシュ通知リストを確認できます。

## 設定 <a href="#undefined" id="undefined"></a>

設定メニューでは、Game Chatプロジェクト情報を設定したり、チャット禁止ワードとメッセージの自動翻訳の有無を設定できます。また、会員情報を変更したり、特定の会員に管理者権限を付与できます。

### 一般 <a href="#undefined" id="undefined"></a>

プロジェクト名、ID、APIキー確認とメッセージの最大長さ、不適切な言語フィルタの制限タイプを設定できます。

1. プロジェクト IDを確認・コピーできます。
2. APIキーをコピー・再作成できます。
3. メッセージの最大長さを設定します。
4. 不適切な言語フィルタの制限タイプを選択します。
   * 使用しない: 禁則ワードに指定された単語もそのまま表示
   * *に置換: 禁則ワードに指定された単語はチャット画面に*と表示
   * メッセージ送信ブロック: 禁則ワードに指定された単語は送信しない
5. 禁則ワードの例を自動で読み取るには、 **\[基本フィルタの使用]** ボタンをクリックします。

### セキュリティ <a href="#undefined" id="undefined"></a>

作成したプロジェクトのセキュリティと許可 IPアドレス、画像タイプを指定できます。

1. Game Chatダッシュボードで **設定 > セキュリティ** をクリックします。
2. セキュリティで必要な設定を指定します。
   * トークン認証: 特定トークンでアクセス権限を付与
   * 許可された IPアドレスの追加・削除
   * 許可された画像タイプの追加・削除
   * アップロードサイズの制限
   * ダウンロード期限切れ時間の指定
   * 許可されたアクセスタイプの設定
   * ホワイトリストの指定・削除
3. **\[保存]** ボタンをクリックします。

### 連携 <a href="#undefined" id="undefined"></a>

作成したプロジェクトに Papago、Object Storageなどの様々なサービスの連携ステータス・連携を設定できます。

1. Game Chatダッシュボードで **設定 > 連携** をクリックします。
2. 連携で必要なサービス名を選択します。
3. 連携サービス別に連携有無と入力フィールドを入力し、 **保存** ボタンをクリックします。

#### 参考

Papago Translationと連携するための Client IDと Client Secretを確認する方法は、[Papago Translation ご利用ガイド](https://guide.ncloud-docs.com/docs/ja/papagotranslation-overview)をご参照ください。

### 管理者 <a href="#undefined" id="undefined"></a>

Game Chatプロジェクトの管理者情報を確認・変更できます。ただし、現在アクセス中のアカウントの詳細情報は、アカウント情報のプロファイル変更メニューで変更できます。\
管理者情報を変更する方法は、次の通りです。

1. Game Chatダッシュボードで **設定** > **管理者** メニューをクリックします。
2. 情報を変更する会員をクリックします。
3. 会員名、新しいパスワード、使用有無のステータスを設定して **\[保存]** ボタンをクリックします。
4. 特定の会員をダッシュボードの管理者に設定するには、管理者権限アイコンを有効ステータスに変更し、 **\[保存]** ボタンをクリックします。
5. 会員情報を削除するには、 **\[削除]** ボタンをクリックします。

## アクティビティとファイル <a href="#undefined" id="undefined"></a>

アクティビティとファイルメニューでは、検索メニューから csvでエクスポートした結果を30日間ダウンロードできます。

## アカウント情報 <a href="#undefined" id="undefined"></a>

右上のユーザーアイコンでは、アカウント情報を変更してログアウトできます。

#### プロファイル変更 <a href="#undefined" id="undefined"></a>

ログインしたアカウントの情報を確認し、名前とプロファイル URL、ダッシュボードの時間帯を変更できます。プロファイル URLはチャット時に使用されます。\
プロファイル情報を変更する方法は次の通りです。

1. Game Chatダッシュボード右上のユーザーアイコンをクリックした後、プロファイル変更メニューをクリックします。
2. プロフィール変更メニューで名前またはプロファイル URL、時間帯を設定して **\[保存]** ボタンをクリックします。

### パスワード変更 <a href="#undefined" id="undefined"></a>

パスワードを変更する方法は次の通りです。

1. Game Chatダッシュボード右上のユーザーアイコンをクリックした後、 **プロファイル変更** メニューをクリックします。
2. パスワード変更メニューをクリックし、現在のパスワードと変更後のパスワードを入力して **\[保存]** ボタンをクリックします。

## ダッシュボードからのログアウト <a href="#undefined" id="undefined"></a>

Game Chatダッシュボードからログアウトするには、Game Chatダッシュボード右上のユーザーアイコンをクリックした後に **ログアウト** をクリックします。


# Unity SDK のインストール

Unity SDKの使用方法をご案内します。 SDKをインストールして環境を構成することで、チャットとダッシュボードを連携できます。

## システム要件

* 最小仕様: 2020以降(下位バージョンの Unityサポートが必要な場合は、'<cs@nbase.io>' までお問い合わせください)。
* 2020.3.X/2021.1.Xバージョンの Unityエディタのユーザーの場合は、2020.3.15f2以降/2021.1.16f1以降のバージョンを使用してください(AABバージョンビルド時の Unityエディタバグ修正バージョン)。

## SDKのインストールと環境設定

Game Chat Unity SDKをダウンロードし、Unityでプロジェクトを構成する方法は次の通りです。

1. GitHubリポジトリページで [**ダウンロード**](https://github.com/nbase-io/NcloudChat-SDK-Unity/releases/) します。
2. サンプルも GitHubリポジトリページで [**ダウンロード**](https://github.com/nbase-io/NcloudChat-SDK-Unity) します。
3. Unityプログラムを実行し、プロジェクトを作成します。
4. Unityで **Assets** > **Import Package** > **Custom Package...** メニューを順にクリックします。
5. ダッシュボードでダウンロードした「GameChat.Unity.SDK.\[version].unitypackage」ファイルを読み取ります。
6. パッケージにあるすべてのファイルを選択した後、 **\[Import]** ボタンをクリックします。
7. プロジェクトを保存します。


# 初期化

## 初期化 <a href="#undefined" id="undefined"></a>

Game Chatを使用する前に初期化します。ダッシュボードから確認したプロジェクト IDを追加します。Game Chatを初期化する方法は、次の通りです。

1. ダッシュボードにアクセスし、設定メニューでプロジェクト IDを確認します。
2. インスタンスを初期化するには、以下のコードを使用します。

* NBaseSDKモジュールをインポートします。

```csharp
using NBaseSDK;
```

* NBaseSDK Chatインスタンスを作成します。

```csharp
NBaseSDK.Chat nc = NBaseSDK.Chat.GetInstance();
```

* プロジェクト IDとリージョン、言語コードで Ncloud Chatを初期化します。

```csharp
nc.initialize([PROJECT_ID], [REGION], [LANGUAGE]);
```

<table><thead><tr><th width="158">ID</th><th width="110">Type</th><th width="371">Description</th><th>Required</th></tr></thead><tbody><tr><td>PROJECT_ID</td><td>string</td><td>ID(Game Chatダッシュボードの Project ID)</td><td>O</td></tr><tr><td>REGION</td><td>string</td><td>リージョン(別途使用する場合以外は、「kr」で使用)</td><td>O</td></tr><tr><td>LANGUAGE</td><td>string</td><td>言語コード(「ja」、「ko」など)</td><td>O</td></tr></tbody></table>

## エラー処理 <a href="#undefined" id="undefined"></a>

* 基本的なエラー処理は以下のように try ...catch内にコードを追加します。

```csharp
try
{
    // ここに、エラーが発生し得るコードを作成します。
    ...
}
catch (InvalidOperationException e)
{
    // ここに、特定エラータイプの処理を作成します。
    Console.WriteLine("InvalidOperationException: {0}", e.Message);
}
catch(Exception e)
{
    // ここに、一般的なエラー処理を作成します。
    Console.WriteLine("Error: {0}", e.Message);
}
```


# ログイン

## ログイン <a href="#undefined" id="undefined"></a>

初期化の完了後にユーザー名、名前、プロファイル画像アドレス(オプション)を入力してアクセスできます。

### アクセス

```csharp
await nc.Connect(
    id: [USERNAME],
    name: [NAME],
    profile: [PROFILE_URL],
    customField: [CUSTOM_FIELD],
    token: [TOKEN]
);
```

| ID            | Type   | Description    | Required |
| ------------- | ------ | -------------- | -------- |
| USERNAME      | string | ID             | O        |
| NAME          | string | ハンドルネーム        | X        |
| PROFILE\_URL  | string | プロファイルアドレス URL | X        |
| LANGUAGE      | string | 言語コード          | X        |
| CUSTOM\_FIELD | string | ユーザー定義フィールド    | X        |
| TOKEN         | string | トークン値          | X        |

> 参考
>
> * ログイン時に、セキュリティのために APIからトークンを発行することをお勧めします。
> * [API DOCS TOKEN](https://api.ncloud-docs.com/docs/ja/bizapp-token-issuance) APIから発行したトークンを使用できます。
> * トークン方式を使用しない場合、 **ダッシュボード > セキュリティ設定 > Token認証** を **使用しない** に設定します。

### アクセス終了 <a href="#undefined" id="undefined"></a>

接続された Game Chatサーバとの接続を解除するには、以下のコードを使用します。

```csharp
await nc.Disconnect();
```

### ユーザー情報 <a href="#undefined" id="undefined"></a>

* Member Data Class

<table><thead><tr><th width="188">ID</th><th width="187">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>ユーザー ID</td></tr><tr><td>name</td><td>string</td><td>ユーザー名</td></tr><tr><td>profile</td><td>string</td><td>画像アドレス</td></tr></tbody></table>

#### **ユーザー情報を取得する**

特定の IDに関する情報を取得します(セキュリティ上、ハンドルネームのみ転送します)。

```csharp
Hashtable filter = new Hashtable
{
    { "id", [USER_ID] }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var users = await nc.getUsers(filter, sort, option);
```

* Parameters

<table><thead><tr><th width="117">ID</th><th width="91">Type</th><th width="434">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>クエリをフィルタ。すべてのフィールドに対して検索可能</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>ソートしたいフィールドのフィルタを定義(昇順「1」、「降順「-1」)</td><td>X</td></tr><tr><td>option</td><td>object</td><td>オプションが存在する場合、以下を参照</td><td>X</td></tr></tbody></table>

* Options

<table><thead><tr><th width="241">ID</th><th width="209">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>開始 offset</td></tr><tr><td>per_page</td><td>number</td><td>リターン数(最大100個)</td></tr></tbody></table>


# チャンネル

## チャンネル <a href="#undefined" id="undefined"></a>

Game Chatでチャンネルは、ユーザーがグループでコミュニケーションできる仮想空間です。チャンネルを通じてユーザーは特定のトピックや目的に合わせて情報を共有し、チームワークを強化してコミュニケーションを組織化できます。チャンネルは業務効率を高め、特定のグループ内のコミュニケーションを一元化して管理できる便利なツールです。以下は Game Chatのチャンネル機能の詳細な説明です。

### チャンネルの主な機能 <a href="#undefined" id="undefined"></a>

1. **グループコミュニケーション** : チャンネルを作成し、特定のグループのメンバーとコミュニケーションできます。この機能は、プロジェクトチーム、部署、クラブなど様々な形のグループに適しています。
2. **メッセージとファイル共有** : チャンネル内では、テキストメッセージ、画像、動画、文書など様々な形式のファイルを簡単に共有できます。
3. **リアルタイム更新** : チャンネル内のすべてのアクティビティはリアルタイムで更新され、すべての参加者が最新の情報に触れることができます。
4. **管理者制御** : チャンネルの作成者または管理者は、チャンネルの設定を変更したりユーザーを追加/削除する権限があります。
5. **通話とビデオ会議機能** : 一部のチャンネルでは音声通話やビデオ会議をサポートし、メンバー間の会話をより効果的に行うことができます。
6. **通知設定** : ユーザーはチャンネルごとに通知を設定して、重要なメッセージを見逃さないようにすることができます。
7. **検索機能** : チャンネル内の会話やファイルを簡単に検索できるので、必要な情報を素早く見つけることができます。

### チャンネル管理 <a href="#undefined" id="undefined"></a>

* **チャンネル作成** : ユーザーは目的に合ったチャンネルを新たに作成でき、チャンネル名、説明、メンバーなどの情報を設定できます。
* **チャンネル招待** : チャンネルの管理者は、他のユーザーをチャンネルに招待できます。招待されたユーザーは、招待を承諾または拒否できます。
* **メンバー管理** : 管理者はチャンネルメンバーの権限を設定したり、メンバーをチャンネルから削除できます。

### セキュリティ <a href="#undefined" id="undefined"></a>

* **データセキュリティ** : チャンネル内のすべてのデータは暗号化されて送信され、サーバに安全に保存されます。
* **個人情報保護** : チャンネル内で共有される情報は、チャンネルメンバー間でのみアクセス可能で、外部に流出しないように保護されます。

Game Chatのチャンネル機能を活用することで、組織内または個人的なコミュニケーションを円滑にし、情報を効果的に管理できます。このような特性は、特に大規模な組織や様々なプロジェクトを管理する際に非常に役立ちます。

### チャンネル作成 <a href="#undefined" id="undefined"></a>

すべての会話はチャンネルを作成する必要があり、チャンネル内に参加することで正常にチャットできます。以下で、チャンネルを作成して登録する方法をご案内します。

```csharp
await nc.createChannel(new NBaseSDK.Channel
{
    name = "New Channel",
    type =[TYPE],    // PUBLIC or PRIVATE
    customField = [CustomField]
});
```

| ID            | Type    | Description                          | Required |
| ------------- | ------- | ------------------------------------ | -------- |
| NAME          | string  | チャンネル名                               | O        |
| TYPE          | string  | チャンネルの種類(PUBLIC or PRIVATE)          | O        |
| UniqueID      | string  | 固有 ID                                | X        |
| push          | boolean | プッシュ通知の有無                            | X        |
| linkUrl       | string  | リンクの有無                               | X        |
| imageUrl      | string  | リンクの有無                               | X        |
| integrationId | string  | 連携機能(翻訳、ボイスなど)                       | X        |
| disabled      | string  | チャンネルの使用有無                           | X        |
| members       | array   | PRIVATEの場合、参加できる ID                  | X        |
| CustomField   | string  | ユーザー定義フィールド、JSON Stringで入力すると様々に活用可能 | X        |

> 参考
>
> * セキュリティのためにクライアントからチャンネルを作成するより、サーバからチャンネルを作成することをお勧めします。

### チャンネル登録 <a href="#undefined" id="undefined"></a>

ご希望のチャンネルに登録(ルームに参加)します。登録を解除するまで、参加しているチャンネルに再アクセス時にも自動的に参加します。

```csharp
Hashtable option = new Hashtable
{
    { "language", "ja" }    //自動翻訳時に必要なオプション以外にも様々なオプションを追加できます。
};
await nc.subscribe([CHANNEL_ID], option);
```

### チャンネル登録解除 <a href="#undefined" id="undefined"></a>

当該チャンネルへの登録を解除します。当該チェンネルからメッセージを受信できません。

```csharp
await nc.unsubscribe([CHANNEL_ID]);
```

### 参加者リスト <a href="#undefined" id="undefined"></a>

(特定チャンネルに対し)参加者リストを取得できます。

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", channelId }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var subscriptions = await nc.getSubscriptions(filter, sort, option);
foreach (var subscription in subscriptions.edges)
{
    string id = subscription.node.id.ToString();
    Console.WriteLine("[CloudChatSample] id={0}", id);
}
```

* Parameters

<table><thead><tr><th width="119">ID</th><th width="90">Type</th><th>Description</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>クエリをフィルタ。すべてのフィールドに対して検索可能</td></tr><tr><td>sort</td><td>object</td><td>ソートしたいフィールドのフィルタの定義(昇順「1」、降順「-1」)</td></tr><tr><td>option</td><td>object</td><td>オプションが存在する場合、以下を参照</td></tr></tbody></table>

* Options

<table><thead><tr><th width="174">ID</th><th width="189">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>開始 offset</td></tr><tr><td>per_page</td><td>number</td><td>リターン数(最大100個)</td></tr></tbody></table>

#### **応用編**

特定チャンネルに対しオンラインアクセスステータスの訪問者リストのみ取得するには、filterに onlineを trueで追加します。

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", [CHANNEL_ID] },
    { "online" , true}
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};

var subscriptions = await nc.getSubscriptions(filter, sort, option);
```

#### **チャンネル登録**

* Subscription Data Class

<table><thead><tr><th width="221">ID</th><th width="139">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>ユニーク ID</td></tr><tr><td>channel_id</td><td>string</td><td>チャンネル ID</td></tr><tr><td>user_id</td><td>string</td><td>ユーザーの固有 ID</td></tr><tr><td>created_at</td><td>string</td><td>作成日</td></tr><tr><td>online</td><td>boolean</td><td>オンライン状態の有無</td></tr><tr><td>push</td><td>boolean</td><td>プッシュ参加の有無</td></tr><tr><td>language</td><td>string</td><td>アクセス言語</td></tr><tr><td>channel</td><td>string</td><td>チャンネル情報</td></tr><tr><td>mark.user_id</td><td>string</td><td>最後にメッセージを送信したユーザー</td></tr><tr><td>mark.message_id</td><td>string</td><td>最後のメッセージ ID</td></tr><tr><td>mark.sort_id</td><td>string</td><td>最後のメッセージソート ID</td></tr><tr><td>mark.unread</td><td>string</td><td>最後のメッセージ以降に、未読のメッセージ数</td></tr></tbody></table>

### チャンネル情報 <a href="#undefined" id="undefined"></a>

* Channel Data Class

<table><thead><tr><th width="190">ID</th><th width="118">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>チャンネル ID(unique)</td></tr><tr><td>project_id</td><td>string</td><td>プロジェクト ID</td></tr><tr><td>unique_id</td><td>string</td><td>開発会社で設定できるチャンネル ID(unique)</td></tr><tr><td>name</td><td>string</td><td>チャンネル名</td></tr><tr><td>user_id</td><td>string</td><td>(チャンネルを作成した)ユーザー ID</td></tr><tr><td>unique_id</td><td>string</td><td>チャンネルの固有 ID</td></tr><tr><td>default_lang</td><td>string</td><td>基本言語</td></tr><tr><td>lang</td><td>string</td><td>現在接続中のユーザーの言語</td></tr><tr><td>members</td><td>string</td><td>Privateの場合、参加したユーザーリスト</td></tr><tr><td>last_message</td><td>array</td><td>最後のメッセージ情報[MessageType]を参照</td></tr><tr><td>push</td><td>boolean</td><td>プッシュメッセージのサポート有無(Privateチャンネルの場合)</td></tr><tr><td>state</td><td>boolean</td><td>チャンネルステータス</td></tr><tr><td>customField</td><td>string</td><td>ユーザー定義データ</td></tr><tr><td>created_at</td><td>string</td><td>作成日</td></tr><tr><td>updated_at</td><td>string</td><td>更新日</td></tr></tbody></table>

#### **チャンネルデータを取得する**

プロジェクトのチャンネルデータをリスト形式で取得するには、以下のコードを使用します。

```csharp
Hashtable filter = new Hashtable
{
    { "state", true }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var channels = await nc.getChannels(filter,sort,option);
foreach (var channel in channels.edges)
{
    string id = channel.node.id.ToString();
    Console.WriteLine("[CloudChatSample] id={0}", id);
}
```

* Parameters

<table><thead><tr><th width="106">ID</th><th width="106">Type</th><th width="439">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>クエリをフィルタ。すべてのフィールドに対して検索可能</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>ソートしたいフィールドのフィルタの定義</td><td>X</td></tr><tr><td>option</td><td>object</td><td>オプションが存在する場合、以下を参照</td><td>X</td></tr></tbody></table>

* Options

<table><thead><tr><th width="221">ID</th><th width="213">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>開始 offset</td></tr><tr><td>per_page</td><td>number</td><td>リターン数(最大100個)</td></tr></tbody></table>

### 個別チャンネル <a href="#undefined" id="undefined"></a>

* 個別チャンネルに関する情報を取得できます。

```csharp
Channel channel = await nc.getChannel(id);
```

### チャンネル内にユーザーを招待 <a href="#undefined" id="undefined"></a>

PRIVATEチャンネルの場合、参加を希望するユーザーを招待します。

```csharp
await nc.addUsers(newChannelId, new string[] { "ID", "ID" });
```

### チャンネル内でユーザーを削除 <a href="#undefined" id="undefined"></a>

PRIVATEチャンネルの場合、参加しているユーザーを削除します。

```csharp
await nc.removeUsers(channelId, new string[] { "ID", "ID" });
```

### チャンネル内でユーザーをブロック <a href="#undefined" id="undefined"></a>

チャンネル内でユーザーをブロックします。チャンネルを作成した権限を持つユーザーや、全体管理者のみ使用できます。

```csharp
Hashtable option = new Hashtable
{
    { "timeout", [終了時間(秒)] },
    { "reason", [ブロック理由] }
};
await nc.banUser(channelId, userId, options);
```

* Options Data Class

<table><thead><tr><th width="204">ID</th><th width="189">Type</th><th>Description</th></tr></thead><tbody><tr><td>timeout</td><td>string</td><td>ブロック時間(seconds)</td></tr><tr><td>reason</td><td>string</td><td>ブロック理由</td></tr></tbody></table>

### チャンネル内でユーザーブロックを解除 <a href="#undefined" id="undefined"></a>

チャンネル内でブロックしたユーザーのブロックを解除します。チャンネルを作成した権限を持つユーザーや、全体管理者のみ使用できます。

```csharp
await nc.unbanUser(channelId, userId);
```

### チャンネル削除 <a href="#undefined" id="undefined"></a>

当該チャンネルを削除します(1つまたは複数同時に削除できます)。

```csharp
Channel channel = await nc.deleteChannel([CHANNEL_ID]);
```

### チャンネル変更 <a href="#undefined" id="undefined"></a>

チャンネル情報を更新します。

```csharp
Channel channel = await nc.updateChannel([CHANNEL_ID],new NBaseSDK.Channel
{
    name = "Update Channel",
    type =[TYPE],    // PUBLIC or PRIVATE
    customField = [CustomField]
});
```


# メッセージ

## メッセージ

Game Chatが提供するメッセージ機能は、ユーザー間の効果的なコミュニケーションをサポートする様々なサービスを含みます。このプラットフォームは、個人的な会話だけでなくグループでの会話にも適しており、メッセージの送受信を簡単かつ迅速に行うことができます。以下は Game Chatの主なメッセージ機能とその特徴です。

### 1. 即時メッセージング <a href="#id-1" id="id-1"></a>

* **リアルタイムコミュニケーション** : ユーザーはリアルタイムでメッセージを送受信でき、コミュニケーションの遅延を最小限に抑えます。
* **マルチデバイス対応** : ユーザーはスマートフォン、タブレット、PCなど様々なデバイスでメッセージを送受信できます。

### 2. グループチャット <a href="#id-2" id="id-2"></a>

* **複数の参加者** : ユーザーは複数の人が参加するグループチャットを作成して情報を共有し、チーム内のコミュニケーションを容易にすることができます。
* **チャンネル管理** : 管理者はグループチャットを介してメンバーを追加したり削除し、グループの設定を調整できます。

### 3. ファイル共有 <a href="#id-3" id="id-3"></a>

* **様々なファイル形式をサポート** : テキスト、画像、動画、文書など様々な形式のファイルをチャットで簡単に共有できます。
* **安全なファイル保存** : Game Chatはお客様所有の Object Storage内にファイルを保存管理するため、外部への情報流出を防ぎます。

### 4. メッセージ検索 <a href="#id-4" id="id-4"></a>

* **キーワード検索** : チャット内で特定のキーワードを使って過去の会話内容を検索できます。
* **高度なフィルタオプション** : 日付、参加者、ファイルタイプなど様々なフィルタを適用して、目的のメッセージを素早く検索できます。

### 5. 通知とその調整 <a href="#id-5" id="id-5"></a>

* **プッシュ通知** : 新しいメッセージや重要なアップデートがあるときにユーザーに通知を送信し、情報の漏れを防ぎます。
* **通知設定** : ユーザーは通知の種類と頻度を調整でき、希望する方法で情報を受け取ることができます。

### 6. セキュリティと個人情報保護 <a href="#id-6" id="id-6"></a>

* **データ暗号化** : すべてのメッセージは送信と保存の過程で暗号化され、外部からのデータ漏洩を防止します。
* **個人情報保護** : ユーザーの個人情報や会話内容は厳重に保護され、ユーザーの同意なしに第三者に開示されることはありません。

Game Chatのメッセージ機能はユーザーのコミュニケーションを円滑かつ効率的にし、仕事や日常生活において重要な役割を果たします。これらの機能によりユーザーはより簡単にコミュニケーションできるようになり、チームワークの強化に大きく貢献します。

## メッセージ送信 <a href="#undefined" id="undefined"></a>

チャンネルを作成して登録したら、以下のように呼び出して新しいメッセージを送信します。

```csharp
const message = 'Hello !!!';
await nc.sendMessage(
        channelId: CHANNEL_ID,
        type:"text",
        content: message
);


// メッセージにコメントを送る場合
await nc.sendMessage(
        channelId: CHANNEL_ID,
        type:"text",
        content: message,
        parentMessageId: [MESSAGE_ID]
        );

// メッセージに自動翻訳をする場合
await nc.sendMessage(
        channelId: CHANNEL_ID,
        type:"text",
        content: message,
        translate: true
        );

// 新規メッセージから下記のように parent_messageに親メッセージの内容を補強して送ります。
{
    "id": "message_id",
    "text": "Message",
    "parent_message_id": "first_message_id",
    "parent_message": {
        "id": "message_id",
        "text": "message_name",
        "sender" : {
            "id" : "Sender",
             "name" : "Sender Nickname",
             "profile" : "profile url"
        }
    }
}
```

> 参考
>
> messageは JSON形式で送信/受信すると、様々なユーザー定義の値を使用できます。

```csharp
Hashtable messageArray = new Hashtable
{
    { "channel_id", "channelId" },
    { "state", 1 },
    { "desc" , "Desc" }
};
// メッセージをプレーンテキストに変換します。
const jsonString = JsonConvert.SerializeObject(messageArray);
// 受信したメッセージを Arrayに変換します。
Hashtable hashtable = JsonConvert.DeserializeObject<Hashtable>(jsonString);
```

<table><thead><tr><th width="161">ID</th><th width="103">Type</th><th>Description</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>チャンネル ID</td></tr><tr><td>type</td><td>string</td><td>送信するメッセージの種類(text、image)</td></tr><tr><td>MESSAGE</td><td>string</td><td>送信メッセージのテキスト、JSON Stringを活用すると、様々な用途で使用可能</td></tr><tr><td>MENTIONS</td><td>array</td><td>メンションするユーザー ID</td></tr></tbody></table>

* Express Messageを使用する: 高速でメッセージを送信するための関数です。時間がかかる可能性のある部分をすべてスキップし、従来より10倍速くメッセージを送信できます。一般 sendMessageとの違いは、次の通りです。

<table><thead><tr><th width="208">Function</th><th width="201">Description</th><th width="132">フィルタリング</th><th width="105">ブロック</th><th>翻訳</th></tr></thead><tbody><tr><td>sendMessage</td><td>一般メッセージの送信</td><td>O</td><td>O</td><td>O</td></tr><tr><td>sendExpressMessage</td><td>クイックメッセージの送信</td><td>X</td><td>X</td><td>X</td></tr></tbody></table>

ゲーム内でリアルタイム PvPを制作したり、高速の Broadcastingが必要なすべてのサービスに利用できます。

## ファイルアップロード <a href="#undefined" id="undefined"></a>

* 特定チャンネルにファイルを送信できます。
* ダッシュボード > 設定 > セキュリティ > 許可されたファイルタイプのみアップロードできます。

```csharp
await nc.sendFile([CHANNEL_ID],file);
```

<table><thead><tr><th width="218">ID</th><th width="176">Type</th><th>Description</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>チャンネル ID</td></tr><tr><td>file</td><td>string</td><td>ファイル情報</td></tr></tbody></table>

> 参考
>
> * オブジェクトストレージが有効になっている必要があります。
> * [Object Storage](https://www.ncloud.com/product/storage/objectStorage)サービスと連携すると使用できます。
> * アップロード時にダッシュボードの **プロジェクト設定 > セキュリティ設定** でアップロードタイプと容量などを設定します。
> * サポートファイルタイプ: 画像、動画、文書、圧縮などの一般的なタイプをすべてサポートし、追加でサポートが必要な拡張子は、お問い合わせからご連絡いただければ、セキュリティ検討後に追加いたします。
> * ファイルリンクを利用する場合、Endpointアドレスは <https://apps.ncloudchat.naverncp.comです。\\>
>   例) <https://apps.ncloudchat.naverncp.com/archive/\\[archiveId>]

## メッセージ情報 <a href="#undefined" id="undefined"></a>

* Message Data Class

<table><thead><tr><th width="211">ID</th><th width="182">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>ID(unique)</td></tr><tr><td>message_id</td><td>string</td><td>メッセージ ID</td></tr><tr><td>sort_id</td><td>string</td><td>メッセージソートのための ID</td></tr><tr><td>message_type</td><td>string</td><td>メッセージ種類</td></tr><tr><td>sender.id</td><td>string</td><td>送信者 ID</td></tr><tr><td>sender.name</td><td>string</td><td>送信者の名前</td></tr><tr><td>sender.profile</td><td>string</td><td>送信者のプロファイル画像</td></tr><tr><td>metions</td><td>string</td><td>メンションされたリスト</td></tr><tr><td>metions_everyone</td><td>string</td><td>全体メンションの有無</td></tr><tr><td>content</td><td>string</td><td>メッセージ</td></tr><tr><td>created_at</td><td>string</td><td>作成日</td></tr><tr><td>sended_at</td><td>string</td><td>送信日</td></tr></tbody></table>

### 個別メッセージ情報 <a href="#undefined" id="undefined"></a>

個別メッセージに関する情報を取得できます。

```csharp
NBaseSDK.Message message = await nc.getMessage([CHANNEL_ID], [MESSAGE_ID]);
```

### 全体メッセージ情報 <a href="#undefined" id="undefined"></a>

全体メッセージ情報を取得できます。

* MessageData data class

| ID         | Type    | Description  |
| ---------- | ------- | ------------ |
| totalCount | Int     | メッセージの総数     |
| messages   | Message | メッセージのデータリスト |

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", [CHANNEL_ID] }
};
Hashtable sort = new Hashtable
{
    { "sort_id", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var messages = await nc.getMessages(filter, sort, option);
if (messages != null)
    {
            foreach (var message in messages.edges)
        {
            string id = message.Node.message_id.ToString();
            Console.WriteLine("[CloudChatSample] id={0}", id);
        }
    }
```

* Parameters

<table><thead><tr><th width="120">ID</th><th width="108">Type</th><th width="403">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>クエリをフィルタ。すべてのフィールドに対して検索可能</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>ソートしたいフィールドのフィルタの定義</td><td>X</td></tr><tr><td>option</td><td>object</td><td>オプションが存在する場合、以下を参照</td><td>X</td></tr></tbody></table>

* Filter

| ID             | Type    | Description  |
| -------------- | ------- | ------------ |
| message\_id    | String  | メッセージ ID     |
| channel\_id    | String  | チャンネル ID     |
| sort\_id       | String  | ソート ID       |
| message\_type  | String  | メッセージタイプ     |
| embedProviders | String  | エンベッドのプロバイダ  |
| isExpress      | Boolean | クイックメッセージの有無 |
| bytes          | Int     | メッセージのバイトサイズ |
| content        | String  | メッセージの内容     |
| sended\_at     | String  | メッセージの送信時間   |
| created\_at    | String  | メッセージの作成時間   |

* Sort

| ID          | Type   | Description       |
| ----------- | ------ | ----------------- |
| created\_at | number | 作成日(昇順「1」、降順「-1」) |

* Options

| ID        | Type   | Description   |
| --------- | ------ | ------------- |
| offset    | number | 開始 offset     |
| per\_page | number | リターン数(最大100個) |

## 未読メッセージ <a href="#undefined" id="undefined"></a>

未読メッセージ数をリターンします。最初に markReadから最後に読んだメッセージ情報を転送します。

```csharp
nc.markRead([CHANNEL_ID], new NBaseSDK.MarkInput
{
    user_id = USER_ID,
    message_id = MESSAGE_ID,
    sort_id = SORT_ID
});
// マークした以降の未読メッセージの総数をリターンします。
var unread = nc.unreadCount([CHANNEL_ID]);
```

<table><thead><tr><th width="230">ID</th><th width="210">Type</th><th>Description</th></tr></thead><tbody><tr><td>USER_ID</td><td>string</td><td>メッセージに含まれた user_idを入力</td></tr><tr><td>MESSAGE_ID</td><td>string</td><td>メッセージに含まれた message_idを入力</td></tr><tr><td>SORT_ID</td><td>string</td><td>メッセージに含まれた sort_idを入力</td></tr></tbody></table>

## メッセージ削除 <a href="#undefined" id="undefined"></a>

当該チャンネル内に自分が送ったメッセージを削除できます。

```csharp
await nc.deleteMessage([CHANNEL_ID], [MESSAGE_ID]);
```

* Parameters

| ID          | Type   | Description |
| ----------- | ------ | ----------- |
| CHANNEL\_ID | string | チャンネル ID    |
| MESSAGE\_ID | string | メッセージ ID    |


# イベント

## イベント <a href="#undefined" id="undefined"></a>

Game Chatでは、クライアント側で発生する様々なイベントを処理できるイベントリスナー(Event Listener)機能を提供します。この機能により、ユーザーはチャットアプリケーション内で起こる様々な状況をリアルタイムで監視し、適切に反応することができます。以下は、主なイベントとイベント処理方法についての説明です。

## 主なイベントタイプ <a href="#undefined" id="undefined"></a>

1. **メッセージ受信** : 新しいメッセージを受信したときにトリガーされます。
2. **メッセージ削除** : メッセージが削除されたときにトリガーされます。
3. **エラーメッセージ** : エラーが発生したときにトリガーされます。
4. **アクセス成功** : サーバへのアクセスが成功したときにトリガーされます。
5. **アクセス終了** : サーバアクセスが終了したときにトリガーされます。
6. **タイピング開始/終了** : ユーザーがタイピングを開始または終了したときにそれぞれトリガーされます。
7. **メンバー追加/削除** : チャンネルにユーザーが追加または削除されたときにトリガーされます。
8. **メンバー停止/退会** : ユーザーがチャンネルから停止されたり退会したときにトリガーされます。

次は、クライアント側からイベントを受信する方法です。

```csharp
nc.dispatcher.onMessageReceived += message =>
{
    Console.WriteLine("received a new message: ", message);
}
```

## イベントハンドラ接続と解除 <a href="#undefined" id="undefined"></a>

イベントハンドラを使用して様々なイベントを受信し、必要なロジックを実装できます。以下のコードは、各イベントに対するイベントハンドラの接続と解除方法を示しています。

```csharp
// メッセージ受信
nc.dispatcher.onMessageReceived += e =>
{
    Console.WriteLine("onMessageReceived: ", e);
};

// メッセージ削除
nc.dispatcher.onMessageDeleted += e =>
{
    Console.WriteLine("onMessageDeleted: ", e);
};

// エラーメッセージ
nc.dispatcher.onErrorReceived += e =>
{
    Console.WriteLine("[CloudChatSample] onErrorReceived: ", e);
};

// アクセス成功
nc.dispatcher.onConnected += e =>
{
    Console.WriteLine("[CloudChatSample] Connected to server with id: {0} ", e);
};

// アクセス終了
nc.dispatcher.onDisconnected += e =>
{
    Console.WriteLine("Disconnected");
};

// タイピングを開始する場合
nc.dispatcher.onStartTyping += e =>
{
    Console.WriteLine("onStartTyping: ", e);
};

// タイピングを終了する場合
nc.dispatcher.onStopTyping += e =>
{
    Console.WriteLine("onStopTyping: ", e);
};

// ユーザーがチャンネルを登録した場合
nc.dispatcher.onMemberAdded += e =>
{
    Console.WriteLine("onMemberAdded: ", e);
};

// ユーザーがチャンネル登録を解除した場合
nc.dispatcher.onMemberLeft += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberLeft: ", e);
};

// チャンネルからユーザーが停止された場合
nc.dispatcher.onMemberBanned += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberBanned: ", e);
};

// チャンネルからユーザーが退会した場合
nc.dispatcher.onMemberDeleted += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberDeleted: ", e);
};

nc.dispatcher.onSubscriptionUpdated += e =>
{
    Console.WriteLine("[CloudChatSample] onSubscriptionUpdated: ", e);
};
```

イベントリスナーを活用することで、Game Chatユーザーはチャット環境の変化をリアルタイムで把握し、適切に対応することができます。


# 友達

## 友達管理 <a href="#undefined" id="undefined"></a>

Game Chatは友達を招待して管理する機能を提供し、ユーザー間のソーシャルネットワーキングを容易にします。このシステムにより、ユーザーは友達の招待、承諾、拒否、削除など、様々な友達管理を行うことができます。以下は、友達管理機能の主な詳細と各機能の使用方法です。

## 友達リスト <a href="#undefined" id="undefined"></a>

ユーザーの友達リストを照会でき、特定のステータスの友達のみフィルタリングして照会することもできます。リストはページングオプションで管理されるため、多数のユーザーを効果的に管理できます。

```csharp
Hashtable filter = new Hashtable
{
    { "status", "accepted" },
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 },
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 },
};
var friends = await nc.getFriendships(filter, sort, option);
```

* **filter** : 照会する友達のステータス(例: 「accepted」)を基準にフィルタリングします。
* **sort** : 結果をソートする基準を設定します。ここでは、作成時間を基準に降順でソートします。
* **option** : 照会するデータの範囲を設定します。`offset`はデータ開始位置、`per_page`はページごとに返す項目数です。

## 招待 <a href="#undefined" id="undefined"></a>

特定のユーザーを友達に招待します。招待されたユーザーは、このリクエストを承諾または拒否できます。

```csharp
var response = await nc.requestFriend(friendId);
```

* **friendId** : 招待したいユーザーの識別子です。

## 承諾 <a href="#undefined" id="undefined"></a>

受け取った友達の招待を承諾します。これにより、二人のユーザーは相互に友達関係になります。

```csharp
var response = await nc.acceptFriend(friendId);
```

* **friendId** : 承諾する友達招待のユーザー識別子です。

## リジェクト <a href="#undefined" id="undefined"></a>

受け取った友達の招待を拒否します。このリクエストを拒否すると、相手と友達関係が成立しません。

```csharp
var response = await nc.rejectFriend(friendId);
```

* **friendId** : 拒否する友達招待のユーザー識別子です。

## 削除 <a href="#undefined" id="undefined"></a>

友達リストから特定のユーザーを削除します。このタスクは、友達や招待のステータスに関係なく行えます。

```csharp
var response = await nc.removeFriend(friendId);
```

* **friendId** : 削除する友達のユーザー識別子です。

友達管理機能は、ユーザー間の相互作用を促進し、ネットワーキングを強化する上で重要な役割を果たします。この機能により、ユーザーは自分のソーシャルネットワークをより簡単に拡張して管理できます。

<br>


# プッシュ

## プッシュ <a href="#undefined" id="undefined"></a>

Game Chatでプッシュ通知は、ユーザーに重要な情報やアップデートをリアルタイムで通知する重要な機能です。このプッシュ通知サービスにより、ユーザーはアプリがバックグラウンドにあるときやデバイスが無効ステータスのときでも、重要なメッセージを見逃すことはありません。以下は Game Chatのプッシュ通知機能の詳細な説明です。

## プッシュ通知の主な機能 <a href="#undefined" id="undefined"></a>

1. **リアルタイム通知** : 新しいメッセージ、メンバー変更、イベント招待などのチャット関連の通知をユーザーに即座に送信します。
2. **カスタマイズ可能** : 通知の形式と内容をアプリケーションの要件に合わせてカスタマイズできます。
3. **マルチプラットフォーム対応** : iOS、Androidなど様々なモバイル OSにプッシュ通知をサポートし、ユーザー基盤を広げることができます。
4. **バッテリーとデータ効率** : 最新のプッシュ技術を使用して、バッテリー消費とデータ使用を最小限に抑えながら、効率的に通知を配信します。
5. **会話型通知** : ユーザーが通知自体で直接対応できるように会話型要素を含めることができます。例えば、メッセージに直接返信したり、招待に応じたりできます。

## プッシュ通知の実装方法 <a href="#undefined" id="undefined"></a>

プッシュ通知サービスを実装するために、Game Chat APIはいくつかの核心要素を提供します:

* **プッシュトークン登録** : ユーザーデバイスのプッシュトークンを Game Chatサーバに登録し、そのデバイスに通知を送信できるようにします。
* **通知設定管理** : ユーザーは自分の通知の好みに応じて、通知の受信有無を設定できます。
* **バックエンド統合** : サーバ側では Game Chatのバックエンドと統合して、リアルタイムでプッシュ通知を作成・送信できます。

## セキュリティと個人情報保護 <a href="#undefined" id="undefined"></a>

* **データ暗号化** : すべてのプッシュ通知は送信中に暗号化され、外部からのアクセスから保護されます。
* **個人情報保護方針の遵守** : Game Chatはユーザーの個人情報保護を非常に重要視し、関連する法律および規制を遵守して通知サービスを提供します。

プッシュ通知機能により Game Chatはユーザーエンゲージメントを促進し、アプリの使用率を高めてユーザーエクスペリエンスを向上させることに大きく貢献します。ユーザーは重要なコミュニケーションを見逃すことなく、いつでもどこでもつながることができます。

## Android(Kotlin)

[Firebase Console](https://console.firebase.google.com/)で Androidアプリを追加した後、ダウンロードした「google-services.json」ファイルをプロジェクトアプリモジュールのルートフォルダに追加します。

ファイルの追加後に bundle.gradle.kts内に以下の内容を追加します。

```none
plugins {
...
    id("com.google.gms.google-services")
...
}
dependencies {
...
    implementation("com.google.firebase:firebase-messaging-ktx:23.2.1")
...
}
```

プッシュ許可権限のポップアップをリクエストします。

```kotlin
import com.nbase.sdk.Permission

NChat.setEnablePush(true)
NChat.requestPermission(this, Permission.NOTIFICATION)
// initialize前に呼び出す必要があります。
```

Connect後にプッシュ受信有無を設定するため、setPushStateを呼び出します。

```kotlin
NChat.setPushState(PushState([PUSH], [AD], [NIGHT])) { state, e ->
    if (e != null) {
        // エラー
    } else {
        // 成功
    }
}
```

| ID    | Type    | Description            |
| ----- | ------- | ---------------------- |
| push  | boolean | プッシュ受信 On/Off(true=On) |
| ad    | boolean | プッシュ受信のため、必ず trueで呼び出す |
| night | boolean | 夜間プッシュ受信 On/Off        |

## **iOS(Swift)**

アプリのプッシュ送信権限を追加します。Targetの Signing & Capabilitiesで、左上の+ Capability > Push Notificationsを選択して追加します。

<figure><img src="/files/4pRImUX2xSaE1P01RVa4" alt=""><figcaption></figcaption></figure>

AppDelegate.swift作成

```swift
import UIKit
import NChat

class AppDelegate: NSObject, UIApplicationDelegate {
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // プッシュ通知権限のリクエスト
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            print("Permission granted: \(granted)")
        }

        UNUserNotificationCenter.current().delegate = self
        application.registerForRemoteNotifications()

        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // APNsトークンを文字列に変換
        let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
        let token = tokenParts.joined()

        // sandbox環境でプッシュを受信するには sandbox: true
        NChat.setPushToken(token: token, sandbox: false)
    }
}
```

Connect後にプッシュ受信有無を設定するため、setPushStateを呼び出します。

```swift
NChat.setPushState(push: true, ad: true, night: true) { result in
    switch(result)
    {
    case .success(let status) :
        // 成功
        break;
    case .failure(let error) :
        // 失敗
        break;
    }
}
```

| ID    | Type    | Description            |
| ----- | ------- | ---------------------- |
| push  | boolean | プッシュ受信 On/Off(true=On) |
| ad    | boolean | プッシュ受信のため、必ず trueで呼び出す |
| night | boolean | 夜間プッシュ受信 On/Off        |


# インポート&エクスポート

## インポート&エクスポート <a href="#undefined" id="undefined"></a>

大容量マイグレーションサービスには大きく2つの方法があり、大規模なマイグレーションの場合はプレミアムサポートを受けることができます(無料)。

1. **ハードウェア移行によるマイグレーション** :

* サービス停止が必要で、お客様はアプリケーションをアップグレードする必要があります。
* サービスを一時停止する最適な時間を予約します。
* 関連データを Game Chatプラットフォームの正しいインポート形式でエクスポートします。
* Game Chatダッシュボードからデータを Game Chatにインポートします。
* データの完全性を検証・確認します。

このような手順により、マイグレーションプロセスを効果的に管理し、Game Chatプラットフォームで新しいチャットサービスを円滑に開始することができます。プレミアムサポートにより、エンジニアリングチームとリアルタイムでコミュニケーションを取りながら、このようなプロセスをより簡単に進めることができます。

### インポート <a href="#undefined" id="undefined"></a>

1. APIを通じて大量のデータを入力できます。
2. Game Chatに合うデータフォーマット(JSON)に変換して渡すことで、指定された時間にデータを一括で追加できます。プレミアムサポートサービスを受けることをお勧めします。

### エクスポート <a href="#undefined" id="undefined"></a>

各メニューごとにエクスポートが存在し、エクスポートしたデータはヘルプ => アクティビティとファイルからダウンロードできます。


# 固定メッセージ

## 固定メッセージ <a href="#undefined" id="undefined"></a>

チャットで固定メッセージ(Pinned Message)とは、チャットルームやグループ会話で重要なメッセージをチャンネルや会話ウィンドウの上部に固定する機能を指します。この機能は、参加者がそのチャットを開くたびに簡単に見ることができ、重要な情報や通知を見逃さないようにするのに役立ちます。以下は、固定メッセージの主な特徴と活用方法についての説明です。

### 固定メッセージの活用方法 <a href="#undefined" id="undefined"></a>

* **会議日程のお知らせ** : 定期的な会議や重要なイベントの日程を固定メッセージに設定し、参加者が日程を忘れないようにします。
* **重要文書のリンク** : 重要な文書や資料のリンクを固定して、すべての参加者が簡単にアクセスできるようにします。
* **ルールとガイドラインの共有** : チャットルームのルールやプロジェクトのガイドラインを固定メッセージとして設定し、新しい参加者も簡単にガイドラインを確認できるようにします。
* **緊急速報** : 緊急に伝えるべき内容や変更点を固定メッセージで素早く共有できます。

固定メッセージ機能は様々なコミュニケーションプラットフォームで提供されており、これを効果的に活用することでチームコミュニケーションの効率を大幅に向上させることができます。

### 固定メッセージ作成 <a href="#undefined" id="undefined"></a>

チャットアプリケーションで重要なメッセージをユーザーが簡単に見られるように上部に固定する機能です。以下の C#コードは、チャットチャンネルでメッセージを固定する方法を示しています。

```csharp
var newPin = await nc.createPin(channelId, messageId, pinned, pinnedAt, expiredAt);
```

* `channelId`: メッセージが固定されるチャットチャンネルの固有 IDです。
* `pinned`: 固定するメッセージの内容です。
* `pinnedAt`: メッセージが固定された時刻を示します。
* `expiredAt`: メッセージの固定が解除される時刻です。

この関数を使用すると、特定のチャットチャンネル内で重要なメッセージを簡単にハイライトして表示できます。

### 固定メッセージ変更 <a href="#undefined" id="undefined"></a>

既存の固定メッセージの情報を更新するための機能です。メッセージの内容、固定時刻、または有効期限を変更できます。

```csharp
var updatedPin = await nc.updatePin(id, channelId, pinned, pinnedAt, expiredAt);
```

* `channelId`: 変更するメッセージがあるチャンネルの IDです。
* `pinned`: 変更されたメッセージの内容です。
* `pinnedAt`: メッセージが新しく固定された時刻です。
* `expiredAt`: メッセージ固定の新しい有効期限です。

このコードは、既に固定されたメッセージの詳細を変更するときに使用され、メッセージの重要性が変更されたり固定時間を調整する必要がある場合に便利です。

### 固定メッセージ情報 <a href="#undefined" id="undefined"></a>

特定メッセージの固定関連情報を照会する機能です。これにより、メッセージの固定ステータス、固定時刻、有効期限などを確認できます。

```csharp
var pin = await nc.getPin(channelId, messageId);
```

* `channelId`: 情報を照会するチャンネルの IDです。
* `messageId`: 固定されたメッセージの固有 IDです。

この関数を通じて特定のメッセージが現在どのようなステータスであるかを確認でき、管理者やユーザーがチャンネル内のメッセージをより効果的に管理するのに役立ちます。

### 固定メッセージリスト <a href="#undefined" id="undefined"></a>

チャットチャンネルで現在固定されているすべてのメッセージのリストを照会する機能です。この関数はページングをサポートし、大規模なチャンネルでも効率的にデータを処理できます。`offset`と `per_page`を設定することで、ユーザーは希望する範囲のデータを取得できます。

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", channelId },
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 },
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 },
};
var pins = await nc.getPins(channelId, filter, sort, option);
```

#### **パラメータの説明**

* **filter** : 照会するデータをフィルタリングするための条件を定義します。例えば、特定のチャンネルで固定メッセージを照会できます。
* **sort** : 結果リストのソート方法を定義します。ここでは、作成時間(`created_at`)を基準に降順(-1)ソートを使用します。
* **option** : 照会時に使用するオプションを定義します。`offset`は照会開始位置、`per_page`はページごとに表示されるメッセージの数を指定します。

#### **オプションの詳細**

<table><thead><tr><th width="148">ID</th><th width="112">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>データをインポートする開始位置です。</td></tr><tr><td>per_page</td><td>number</td><td>1ページあたりに返すメッセージの数、最大100個まで設定可能です。</td></tr></tbody></table>

この機能を使用すると、チャンネル管理者はチャンネル内で重要なメッセージを簡単にモニタリングして管理できます。また、特定のユーザーや時間基準で固定メッセージを素早く検索・ソートでき、チャンネルの効率的な運用に役立ちます。


# 外部連携

## 外部連携 <a href="#undefined" id="undefined"></a>

チャットアプリケーションで外部サービスや様々なサービス群と連携することでユーザーエクスペリエンスを向上させ、より多くの機能を提供することができます。例えば、翻訳サービス、AIベースのコンテンツ推奨、サービス推奨などを統合できます。以下は、これらの機能をチャットアプリケーションに統合する方法の説明です:

### 外部連携の例 <a href="#undefined" id="undefined"></a>

* 翻訳サービス連携: チャットアプリケーションで多言語サポートが必要な場合、Papago翻訳 APIなどの翻訳サービスを連携できます。ユーザーがメッセージを入力すると、APIを介してそのメッセージを翻訳し、結果をチャットウィンドウに表示できます。
* AIベースのコンテンツ推奨: ユーザーのチャット内容と行動パターンを分析し、AIがパーソナライズ化されたコンテンツを推奨できます。例えば、Netflixの推薦システムのように、ユーザーの興味に合った映画やテレビ番組を推薦できます。
* カスタマーサポートの自動化: チャットボットを導入し、基本的なお客様のお問い合わせを自動的に処理できます。AIチャットボットはユーザーの質問を理解し、適切な回答を提供したり、必要に応じて人の相談員に繋げることができます。

このような連携により、チャットアプリケーションは単純なメッセージ交換ツールを超えて様々なサービスを統合し、豊かなユーザーエクスペリエンスを提供するプラットフォームに拡張できます。

### 外部連携サービスリスト <a href="#undefined" id="undefined"></a>

* プッシュ(NPush)
* 翻訳(Papago)
* 画像解析
* 感情分析
* HyperClova X
* Object Storage


# ユースケース

## ユースケース

### Ncloudchat Reactのユースケース

GitHubには全ソースが公開されているため [GitHubソース](https://github.com/nbase-io/CloudChat-JS-Demo)をダウンロードでき、[https://www.ncloudchat.com](https://www.ncloudchat.com/)を通じて利用することができます。

### 全体サンプルコードのユースケース <a href="#undefined" id="undefined"></a>

アクセスしてチャンネルを作成し、そのチャンネルに登録メッセージを送信するユースケースです。

```csharp

// 初期化 
CloudChat nc = CloudChat.GetInstance();
await nc.initialize([PROJECT_ID]);
nc.dispatcher.onMessageReceived += e =>
{
    Console.WriteLine("received a new message: ", e);
};
await nc.Connect(
    userId: 'guest@company',
    name: 'Guest',
    profile: 'https://image_url',
    customField: 'json',
);
// チャンネル作成
var channel = await nc.createChannel(new CloudChatSDK.Channel
{
    name = "New Channel",
    type = "PUBLIC",    // PUBLIC or PRIVATE
    customField = "customField"
});
var channel = await nc.createChannel({type:'PUBLIC', name:'First Channel', customField:'customField'});
var channel_id = channel.createChannel.channel.id.ToString();
// チャンネル登録
await nc.subscribe(channel_id);
// メッセージ送信
var response = await nc.sendMessage(
        channelId: channel_id, 
        type:"text", 
        content: message
    );
```


# Troubleshooting

サービス使用中に発生する可能性のある問題とその解決方法について説明します。

## 1. チャンネル作成時に「アドレスが確認できません。」 <a href="#id-1" id="id-1"></a>

当該エラーは link\_url入力時に当該アドレスが基本アドレスシステム(URL)ではない場合に発生します。アドレスを入力しないか、有効なアドレスを入力します。

## 2. 画像がアップロードできません。 <a href="#id-2" id="id-2"></a>

セキュリティ強化のために許可されたタイプでなければアップロードできません。

**ダッシュボード > 設定 > 画像アップロード許可タイプ**から image/webp、image/heic、image/heic-sequence、image/heif、image/heif-sequence、image/svg+xml、image/bmp、image/gif、image/jpeg、image/pngのように許可する MIME TYPEを入力します。

オブジェクトストレージが有効になっている必要があります。

* [Object Storage](https://www.ncloud.com/product/storage/objectStorage)商品と連携すると使用できます。

## 3. すべてのメッセージを受信します。 <a href="#id-3" id="id-3"></a>

複数のチャンネルに参加している場合に、そのチャンネルからのすべてのメッセージを受信します。\
channelIdから区分できます。

```javascript
nc.bind('onMessageReceived',function(channel, message) {
// 複数のチャンネルに参加している場合に、すべてのチャンネルからのメッセージを受信します。
// channelから顧客に表示するチャンネルを区分します。
if(channel == current_channel) {
console.log(message);
}
});
```


# Game Chat(中文)


# 开始使用V3

Game Chat 대시보드에서 채팅을 운영하고 관리하는 방법, 채팅과 관련된 통계를 확인하는 방법과 네이버 클라우드 플랫폼의 다양한 서비스와 연동하는 방법을 설명합니다.

## 仪表板菜单

在仪表板上，您可以一目了然地了解聊天的运营情况，例如连接状态、消息和统计数据。您可以选择日期来查看图表。

仪表板菜单如下：

| 项目      | 说明                         |
| ------- | -------------------------- |
| ① 主页    | 查看服务使用量和使用情况               |
| ② 分析    | 用户和同时在线人数分析                |
| ③ 用户    | 查看用户并管理被禁用的用户              |
| ④ 聊天    | 添加和管理聊天频道                  |
| ⑤ 消息    | 按时间段搜索聊天消息并导出为Excel        |
| ⑥ 存档    | 查看聊天中交换的所有文件（图片/视频等）       |
| ⑦ 推送通知  | 发送推送通知并查看记录                |
| ⑧ 设置    | 项目的一般设置、安全设置、关联产品和仪表板管理员设置 |
| ⑨ 活动与文件 | 在搜索菜单中查看导出的数据记录            |
| ⑩ 指南    | 跳转到Game Chat使用指南           |

## 用户 <a href="#undefined" id="undefined"></a>

在用户菜单中，您可以查看已注册用户的信息，并可以停止特定用户的聊天使用或将其从所有聊天中移除。

### 查看用户信息 <a href="#undefined" id="undefined"></a>

要查看Game Chat仪表板上注册用户的信息，请执行以下操作：

1. 点击Game Chat仪表板中的“用户” > “用户列表”菜单。
2. 要查看用户的详细信息，请点击用户ID。
3. 在弹出的窗口中查看详细信息。
   * 您可以查看用户的姓名、个人资料URL、接入国家、IP、型号、设备ID、注册日期、最后登录日期等信息，并提供自定义字段和备注功能。
4. 要修改用户信息，请在相关项中进行修改后，点&#x51FB;**\[保存]**&#x6309;钮

### 用户退会 <a href="#undefined" id="undefined"></a>

要将特定用户退会，请按照以下步骤操作：

1. &#x20;在Game Chat仪表板中，点击“用户” > “用户列表”菜单。
2. 点击要退会的用户ID。
3. 当用户的详细信息显示在屏幕上时，点击\[删除]按钮。
4. 确认弹窗出现时，再次点击\[删除]按钮。

### 用户搜索 <a href="#undefined" id="undefined"></a>

要搜索已注册的用户，请按照以下步骤操作：

1. 在Game Chat仪表板中，点击“用户” > “用户列表”菜单。
2. 设置搜索条件，然后点击\[搜索]按钮。
   * 可以根据用户ID、姓名或IP进行搜索。
3. 查看搜索结果。

### **用户停用**

您可以设置特定用户在一定时间内无法使用聊天功能。在“停用用户”菜单中，您可以查看和搜索已停用的用户。

要停用特定用户，请按照以下步骤操作：

1. 在Game Chat仪表板中，点击“用户” > “停用用户”菜单。
2. 点击右侧的\[添加]按钮。
3. 在弹出的窗口中，搜索用户ID并设置停用类型（临时停用或永久停用）及默认语言。
4. 如果要将用户从所有频道中移除，请勾选“从所有聊天中退出”复选框。
5. 设置用户ID、停用原因和停用期限，然后点击\[添加]按钮。

## **聊天**

在聊天菜单中，您可以查看频道并发送聊天消息。

### **添加聊天频道**

添加新的聊天频道的方法如下：

1. 在 Game Chat 控制面板中点击频道菜单。
2. 点击 \[添加] 按钮。
3. 频道可以分为公开聊天和私人聊天进行创建。 (公开聊天最多可容纳 200,000 人参与，而私人聊天则可以创建 1:N 的私密频道。)
4. 输入频道名称和唯一 ID，然后点击 \[添加] 按钮。
   * 输入唯一 ID 后，SDK 可以使用该值访问频道。
   * 可以选择推送和自动翻译功能，并且可以与附加产品进行集成。
5. 请确认频道是否已成功创建。

### **聊天频道设置**

要查看特定聊天频道中的参与用户、修改或删除频道信息，请按照以下步骤操作：

1. 在 Game Chat 控制面板中点击频道菜单。
2. 选择频道后，点击频道屏幕右上角的 ... 图标。
3. 当弹出上下文菜单时，选择所需的操作。
   * 订阅者：点击查看参与聊天频道的用户列表
   * 修改：点击修改聊天频道的信息
   * 删除：点击删除聊天频道

### **发送图片消息**

要发送图片消息，请按照以下步骤操作：

1. 在 Game Chat 控制面板中点击频道菜单。
2. 选择频道后，点击聊天消息输入框右侧的文件附件图标。

> 参考
>
> 支持的图片类型：image/bmp, image/gif, image/jpeg, image/png, image/webp, image/heic, image/heic-sequence, image/heif, image/heif-sequence, image/svg+xml

## 消息 <a href="#undefined" id="undefined"></a>

在消息菜单中，您可以查看和搜索项目中所有频道的消息。您可以根据 ID、昵称、消息内容、频道 ID 和消息发送时间进行搜索，并且可以将消息列表下载为 CSV 文件。

### 消息搜索和消息详细信息查看 <a href="#undefined" id="undefined"></a>

查看消息详细信息的方法如下：

1. 在 Game Chat 控制面板中点击消息菜单。
2. 设置搜索条件，然后点击 \[搜索] 按钮。
   * 可以根据发件人 ID、发件人名称、聊天 ID、昵称、消息内容进行搜索。
3. 点击要查看详细信息的消息。
4. 您可以查看该消息的用户 ID、用户名、聊天 ID、消息 ID、消息内容和创建日期。

### **消息删除**

您可以搜索特定消息并将其删除。通过搜索菜单删除的消息将在相应的聊天频道中也被删除。

1. 在 Game Chat 控制面板中点击消息菜单。
2. 点击要删除的消息。
3. 在消息查看屏幕上选择删除，然后点击 \[删除] 按钮。

## **归档**

在归档菜单中，您可以查看和搜索项目中所有频道交换的图片和文件。您可以查看文件的使用情况、发件人、聊天 ID、预览、文件名、格式、大小、传输次数、创建日期和到期日期。您还可以选择特定文件以禁用用户或删除文件。

## **推送通知**

推送通知是由应用程序发布者发送的，在移动设备上显示的消息。这些通知可以随时发送给用户，无论他们是否积极使用应用程序或设备。请注意以下几点：

* JSON 格式的消息负载大小限制为 4KB。
* 向国外发送通知时，会根据预约时间以各国的本地时间进行传送。\
  您可以设置推送通知并查看已发送的推送通知列表。

## 设置

在设置菜单中，您可以配置 Game Chat 项目的信息，设置聊天禁用词和消息自动翻译功能，修改会员信息，或将管理员权限授予特定会员。

### 一般

在“一般”设置中，您可以检查和设置项目名称、ID、API 密钥、消息最大长度和禁用词过滤限制类型。

1. 可以查看和复制项目 ID。
2. 可以复制或重新生成 API 密钥。
3. 设置消息的最大长度。
4. 选择禁用词过滤限制类型：
   * 不使用：禁用词仍然会原样显示
   * 替换为 \*：禁用词在聊天框中将显示为 \*
   * 阻止消息发送：禁用词不会被发送
5. 若要自动导入禁用词示例，请点击 \[使用默认过滤器] 按钮。

### 安全

您可以为创建的项目指定安全设置，包括允许的 IP 和图片类型。

1. 在 Game Chat 控制面板中点击“设置” > “安全”。
2. 配置所需的安全设置：
   * **令牌认证**：通过特定令牌授予访问权限
   * 添加或删除允许的 IP
   * 添加或删除允许的图片类型
   * 设置上传大小限制
   * 指定下载过期时间
   * 设置允许的访问类型
   * 指定和删除白名单
3. 点击 \[保存] 按钮。

### 集成

您可以为创建的项目设置 Papago、Object Storage 等各种服务的集成状态或进行集成配置。

1. 在 Game Chat 控制面板中点击“设置” > “集成”。
2. 选择所需的集成服务。
3. 对于每个集成服务，配置集成状态和输入字段，然后点击“保存”按钮。

> **参考**\
> 有关检查 [Papago Translation](https://guide.ncloud-docs.com/docs/en/papagotranslation-overview) 集成所需的 Client ID 和 Client Secret 的方法，请参阅 Papago Translation 使用指南。

### 管理员

您可以查看和修改 Game Chat 项目的管理员信息。但是，当前登录帐户的详细信息可以在帐户信息的个人资料修改菜单中进行修改。

修改管理员信息的方法如下：

1. 在 Game Chat 控制面板中点击“设置” > “管理员”菜单。
2. 点击要修改信息的会员。
3. 设置会员名称、新密码和使用状态，然后点击 \[保存] 按钮。
4. 要将特定会员设置为控制面板的管理员，请将管理员权限图标设置为激活状态，然后点击 \[保存] 按钮。
5. 要删除会员信息，请点击 \[删除] 按钮。

## 活动和文件

在“活动和文件”菜单中，您可以下载在搜索菜单中导出的 CSV 文件结果，下载时间为 30 天。

## 账户信息

在右上角的用户图标中，您可以修改账户信息和执行注销操作。

### 个人资料修改

您可以查看登录账户的信息，并修改姓名、个人资料 URL 和仪表板时区。个人资料 URL 在聊天时使用。

修改个人资料信息的方法如下：

1. 点击 Game Chat 控制面板右上角的用户图标，然后点击“个人资料修改”菜单。
2. 在个人资料修改菜单中，设置姓名、个人资料 URL 和时区，然后点击 \[保存] 按钮。

### 密码更改

更改密码的方法如下：

1. 点击 Game Chat 控制面板右上角的用户图标，然后点击“个人资料修改”菜单。
2. 点击“密码更改”菜单，输入当前密码和新密码，然后点击 \[保存] 按钮。

## 仪表板注销

要从 Game Chat 控制面板注销，请点击 Game Chat 控制面板右上角的用户图标，然后点击“注销”。


# Unity SDK 安装

以下是关于 Unity SDK 使用的指南。通过安装 SDK 并配置环境，您可以将聊天功能与仪表板进行集成

## 系统要求

* 最低要求：Unity 2020 及以上版本（如果需要支持较旧版本的 Unity，请通过邮件联系 '<cs@nbase.io>'）
* 对于使用 Unity 编辑器版本 2020.3.X 或 2021.1.X 的用户，请使用 2020.3.15f2 或更高版本 / 2021.1.16f1 或更高版本（针对 AAB 版本构建的 Unity 编辑器修复版本）。

## SDK 安装与环境配置

以下是下载 Game Chat Unity SDK 并在 Unity 中配置项目的方法：

1. 请从 GitHub 仓库页面下载 SDK。
2. 示例代码也请从 GitHub 仓库页面下载。
3. 启动 Unity 程序并创建一个项目。
4. 在 Unity 中依次点击 **Assets > Import Package > Custom Package...** 菜单。
5. 导入从控制面板下载的 `GameChat.Unity.SDK.[version].unitypackage` 文件。
6. 选择包中的所有文件后，点击 \[Import] 按钮。
7. 保存项目。

<br>


# 初始化

## 初始化

在使用 Game Chat 之前，您需要进行初始化。 请添加从控制面板确认的项目 ID。初始化 Game Chat 的方法如下：

1. 访问控制面板，并在设置菜单中确认项目 ID。
2. 要初始化实例，请使用以下代码：

* 导入 NBaseSDK 模块。

```csharp
using NBaseSDK;
```

* 创建 NBaseSDK Chat 实例。

```csharp
NBaseSDK.Chat nc = NBaseSDK.Chat.GetInstance();
```

* 使用项目 ID、区域和语言代码初始化 Game Chat。

```csharp
nc.initialize([PROJECT_ID], [REGION], [LANGUAGE]);
```

<table><thead><tr><th width="151">ID</th><th width="86">Type</th><th width="381">Description</th><th>Required</th></tr></thead><tbody><tr><td>PROJECT_ID</td><td>string</td><td>ID (Game Chat Dashboard Project ID)</td><td>O</td></tr><tr><td>REGION</td><td>string</td><td>区域（如果没有特别使用其他区域，请使用“kr”）</td><td>O</td></tr><tr><td>LANGUAGE</td><td>string</td><td>语言代码（例如 "en", "zh", "kr" 等）</td><td>O</td></tr></tbody></table>

## 错误处理

* 基本的错误处理可以通过将代码添加到以下的 try ... catch 结构中进行。

```csharp
try
{
    // 在此处编写可能会发生错误的代码。
    ...
} 
catch (InvalidOperationException e)
{
    // 在此处处理特定类型的错误。
    Console.WriteLine("InvalidOperationException: {0}", e.Message);
}
catch(Exception e)
{
    // 在此处处理一般错误。
    Console.WriteLine("Error: {0}", e.Message);
}
```


# 登录

## 登录

初始化完成后，您可以通过输入用户名、姓名和可选的个人资料图片地址进行连接。

### 连接

```csharp
await nc.Connect(
    id: [USERNAME],
    name: [NAME],
    profile: [PROFILE_URL],
    customField: [CUSTOM_FIELD],
    token: [TOKEN]
);
```

<table><thead><tr><th width="233">ID</th><th width="126">Type</th><th width="249">Description</th><th>Required</th></tr></thead><tbody><tr><td>USERNAME</td><td>string</td><td>用户ID</td><td>O</td></tr><tr><td>NAME</td><td>string</td><td>昵称</td><td>X</td></tr><tr><td>PROFILE_URL</td><td>string</td><td>个人资料图片地址 URL</td><td>X</td></tr><tr><td>LANGUAGE</td><td>string</td><td>语言代码</td><td>X</td></tr><tr><td>CUSTOM_FIELD</td><td>string</td><td>自定义字段</td><td>X</td></tr><tr><td>TOKEN</td><td>string</td><td>令牌值</td><td>X</td></tr></tbody></table>

> 参考
>
> * 为了安全登录，建议通过 API 获取令牌。
> * 您可以通过 [TOKEN API 文档](https://api.ncloud-docs.com/docs/en/bizapp-token-issuance)中描述的 API 来使用已颁发的令牌。
> * 如果不使用令牌方式，请在控制面板 > 安全设置 > 令牌认证 中设置为不使用。

### 断开连接

要断开与已连接的 Game Chat 服务器的连接，请使用以下代码。

```csharp
await nc.Disconnect();
```

### 用户信息

* Member Data Class

<table><thead><tr><th width="181">ID</th><th width="216">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>사용자 ID</td></tr><tr><td>name</td><td>string</td><td>사용자 이름</td></tr><tr><td>profile</td><td>string</td><td>이미지 주소</td></tr></tbody></table>

#### 获取用户信息

获取特定用户ID的信息（出于安全考虑，只传递昵称）。

```csharp
Hashtable filter = new Hashtable
{
    { "id", [USER_ID] }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var users = await nc.getUsers(filter, sort, option);
```

* Parameters

<table><thead><tr><th width="111">ID</th><th width="93">Type</th><th width="440">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>可以对所有字段进行搜索。</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>定义要排序字段的过滤器（升序为 "1"，降序为 "-1"）。</td><td>X</td></tr><tr><td>option</td><td>object</td><td>如有可选项，请参阅下方参考内容。</td><td>X</td></tr></tbody></table>

* Options

<table><thead><tr><th width="207">ID</th><th width="208">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>起始offset</td></tr><tr><td>per_page</td><td>number</td><td>返回的数量（最多 100 个）</td></tr></tbody></table>


# 频道

## 频道

在 Game Chat 中，频道是用户可以以小组形式进行交流的虚拟空间。通过频道，用户可以根据特定主题或目的共享信息、增强团队合作以及组织沟通。频道是提高工作效率、集中管理特定小组内沟通的有用工具。以下是 Game Chat 频道功能的详细说明。

### 频道的主要功能

1. **小组沟通**：您可以创建频道与特定小组的成员进行交流。这适用于项目团队、部门、俱乐部等各种形式的小组。
2. **消息和文件共享**：在频道内，您可以轻松共享文本消息、图片、视频、文档等多种形式的文件。
3. **实时更新**：频道内的所有活动实时更新，确保所有参与者都能获取最新信息。
4. **管理员控制**：频道的创建者或管理员拥有更改频道设置、添加/删除用户的权限。
5. **通话和视频会议功能**：某些频道支持语音通话或视频会议，使成员之间的对话更加高效。
6. **通知设置**：用户可以为每个频道设置通知，以确保不会错过重要消息。
7. **搜索功能**：可以轻松搜索频道内的对话或文件，快速找到所需的信息。

### 频道管理

* **创建频道**：用户可以创建新的频道以满足特定目的，并设置频道名称、描述、成员等信息。
* **频道邀请**：频道的管理员可以邀请其他用户加入频道。被邀请的用户可以接受或拒绝邀请。
* **成员管理**：管理员可以设置频道成员的权限或从频道中移除成员。

### 安全

* **数据安全**：频道内的所有数据都经过加密传输，并安全地存储在服务器上。
* **隐私保护**：频道内共享的信息仅在频道成员之间可访问，并受到保护，防止外部泄露。

利用 Game Chat 的频道功能，您可以顺畅地进行组织内或个人之间的沟通，并有效地管理信息。这些特性在管理大型组织或各种项目时尤其有用。

### 频道创建

所有对话都需要创建频道并加入频道才能正常进行聊天。以下是创建和订阅频道的方法指南。

```csharp
await nc.createChannel(new NBaseSDK.Channel
{
    name = "New Channel",
    type =[TYPE],    // PUBLIC or PRIVATE
    customField = [CustomField]
});
```

<table><thead><tr><th width="175">ID</th><th width="128">Type</th><th width="350">Description</th><th>Required</th></tr></thead><tbody><tr><td>NAME</td><td>string</td><td>频道名称</td><td>O</td></tr><tr><td>TYPE</td><td>string</td><td>频道类型 ( PUBLIC or PRIVATE )</td><td>O</td></tr><tr><td>UniqueID</td><td>string</td><td>唯一 ID</td><td>X</td></tr><tr><td>push</td><td>boolean</td><td>推送通知是否启用</td><td>X</td></tr><tr><td>linkUrl</td><td>string</td><td>链接是否启用</td><td>X</td></tr><tr><td>imageUrl</td><td>string</td><td>链接是否启用</td><td>X</td></tr><tr><td>integrationId</td><td>string</td><td>集成功能（翻译、语音等）</td><td>X</td></tr><tr><td>disabled</td><td>string</td><td>频道使用状态</td><td>X</td></tr><tr><td>members</td><td>array</td><td>如果是 PRIVATE，允许参与的 ID</td><td>X</td></tr><tr><td>CustomField</td><td>string</td><td>自定义字段：可以以 JSON 字符串形式添加，灵活使用各种功能</td><td>X</td></tr></tbody></table>

> 参考
>
> 为了安全考虑，建议通过服务器而不是客户端创建频道。

### 频道订阅

加入您感兴趣的频道（参与房间）。一旦加入的频道，在取消订阅之前，即使重新连接，也会自动参与其中。

```csharp
Hashtable option = new Hashtable
{
    { "language", "en" }    // 自动翻译时，除了所需的选项外，还可以添加各种其他选项。
};
await nc.subscribe([CHANNEL_ID], option);
```

### 取消频道订阅

取消对该频道的订阅。您将不再收到该频道的消息。

```csharp
await nc.unsubscribe([CHANNEL_ID]);
```

### 参与者列表

（对于特定频道）可以获取参与者列表。

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", channelId }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var subscriptions = await nc.getSubscriptions(filter, sort, option);
foreach (var subscription in subscriptions.edges)
{
    string id = subscription.node.id.ToString();
    Console.WriteLine("[CloudChatSample] id={0}", id);
}
```

* Parameters

<table><thead><tr><th width="147">ID</th><th width="125">Type</th><th>Description</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>可以对所有字段进行搜索。</td></tr><tr><td>sort</td><td>object</td><td>定义要排序字段的过滤器（升序为 "1"，降序为 "-1"）。</td></tr><tr><td>option</td><td>object</td><td>如有可选项，请参阅下方参考内容。</td></tr></tbody></table>

* Options

<table><thead><tr><th width="152">ID</th><th width="124">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>起始 offset</td></tr><tr><td>per_page</td><td>number</td><td>返回的数量（最多 100 个）</td></tr></tbody></table>

### 应用示例

如果仅需获取特定频道中在线的用户列表，请在过滤器中将 online 设置为 true。

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", [CHANNEL_ID] },
    { "online" , true}
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};

var subscriptions = await nc.getSubscriptions(filter, sort, option);

```

#### 频道订阅

* Subscription Data Class

  <table><thead><tr><th width="215">ID</th><th width="153">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>唯一标识符</td></tr><tr><td>channel_id</td><td>string</td><td>频道 ID</td></tr><tr><td>user_id</td><td>string</td><td>用户唯一 ID</td></tr><tr><td>created_at</td><td>string</td><td>创建日期</td></tr><tr><td>online</td><td>boolean</td><td>在线状态</td></tr><tr><td>push</td><td>boolean</td><td>推送订阅状态</td></tr><tr><td>language</td><td>string</td><td>接入语言</td></tr><tr><td>channel</td><td>string</td><td>频道信息</td></tr><tr><td>mark.user_id</td><td>string</td><td>最后发送消息的用户</td></tr><tr><td>mark.message_id</td><td>string</td><td>最后消息的 ID</td></tr><tr><td>mark.sort_id</td><td>string</td><td>最后消息的排序 ID</td></tr><tr><td>mark.unread</td><td>string</td><td>最后消息之后未读的消息数量</td></tr></tbody></table>

### 频道信息 <a href="#undefined" id="undefined"></a>

* Channel Data Class

<table><thead><tr><th width="243">ID</th><th width="148">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>频道 ID (unique)</td></tr><tr><td>project_id</td><td>string</td><td>项目 ID</td></tr><tr><td>unique_id</td><td>string</td><td>开发者设置的频道 ID (unique)</td></tr><tr><td>name</td><td>string</td><td>频道名称</td></tr><tr><td>user_id</td><td>string</td><td>（创建频道的）用户 ID</td></tr><tr><td>unique_id</td><td>string</td><td>频道唯一 ID</td></tr><tr><td>default_lang</td><td>string</td><td>默认语言</td></tr><tr><td>lang</td><td>string</td><td>当前连接用户的语言</td></tr><tr><td>members</td><td>string</td><td>如果是 Private，参与用户列表</td></tr><tr><td>last_message</td><td>array</td><td>最后消息信息 [MessageType] 参考</td></tr><tr><td>push</td><td>boolean</td><td>推送消息支持状态（对于私有频道）</td></tr><tr><td>state</td><td>boolean</td><td>频道状态</td></tr><tr><td>customField</td><td>string</td><td>用户自定义数据</td></tr><tr><td>created_at</td><td>string</td><td>创建日期</td></tr><tr><td>updated_at</td><td>string</td><td>更新时间</td></tr></tbody></table>

#### 获取频道数据

要以列表形式获取项目的频道数据，请使用以下代码。

```csharp
Hashtable filter = new Hashtable
{
    { "state", true }
};
Hashtable sort = new Hashtable
{
    { "created_at", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var channels = await nc.getChannels(filter,sort,option);
foreach (var channel in channels.edges)
{
    string id = channel.node.id.ToString();
    Console.WriteLine("[CloudChatSample] id={0}", id);
}
```

* Parameters

<table><thead><tr><th width="123">ID</th><th width="90">Type</th><th width="393">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>可以对所有字段进行搜索。</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>定义要排序字段的过滤器</td><td>X</td></tr><tr><td>option</td><td>object</td><td>如有可选项，请参阅下方参考内容。</td><td>X</td></tr></tbody></table>

* Options

<table><thead><tr><th width="170">ID</th><th width="167">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>起始 offset</td></tr><tr><td>per_page</td><td>number</td><td>返回的数量（最多 100 个）</td></tr></tbody></table>

### 单个频道

可以获取单个频道的信息。

```csharp
Channel channel = await nc.getChannel(id);
```

### 频道内用户邀请

对于 PRIVATE 频道，邀请想要加入的用户。

```csharp
await nc.addUsers(newChannelId, new string[] { "ID", "ID" });
```

### 频道内用户删除

对于 PRIVATE 频道，删除已参与的用户。

```csharp
await nc.removeUsers(channelId, new string[] { "ID", "ID" });
```

### 频道内用户封禁

在频道内封禁用户。仅具备频道创建权限的用户或全体管理员可以使用此功能。

```csharp
Hashtable option = new Hashtable
{
    { "timeout", [封禁时间（秒）] },
    { "reason", [封禁原因] }
};
await nc.banUser(channelId, userId, options);
```

* Options Data Class

<table><thead><tr><th width="195">ID</th><th width="186">Type</th><th>Description</th></tr></thead><tbody><tr><td>timeout</td><td>string</td><td>封禁时间 (seconds)</td></tr><tr><td>reason</td><td>string</td><td>封禁原因</td></tr></tbody></table>

### 解除频道内用户封禁

解除对频道内被封禁用户的封禁。只有具备频道创建权限的用户或全体管理员可以使用此功能。

```csharp
await nc.unbanUser(channelId, userId);
```

### 删除频道

删除指定的频道（可以删除一个或多个频道）。

```csharp
Channel channel = await nc.deleteChannel([CHANNEL_ID]);
```

### 修改频道

更新频道信息。

```csharp
Channel channel = await nc.updateChannel([CHANNEL_ID],new NBaseSDK.Channel
{
    name = "Update Channel",
    type =[TYPE],    // PUBLIC or PRIVATE
    customField = [CustomField]
});
```


# 消息功能

## 消息功能

Game Chat 提供的消息功能包括支持用户间有效沟通的多种服务。该平台适用于个人对话以及群组对话，使发送和接收消息的过程变得简单快捷。以下是 Game Chat 的主要消息功能及其特点：

### 1. **即时消息**

* **实时沟通**：用户可以实时发送和接收消息，从而将沟通延迟降至最低。
* **多设备支持**：用户可以在智能手机、平板电脑、PC 等多种设备上进行消息的发送和接收。

### 2. **群组聊天**

* **多个参与者**：用户可以创建多个参与者的群组聊天，以便共享信息并简化团队内部的沟通。
* **频道管理**：管理员可以通过群组聊天添加或删除成员，并调整群组的设置。

### 3. **文件共享**

* **支持多种文件格式**：可以通过聊天轻松共享文本、图片、视频、文档等多种格式的文件。
* **安全的文件存储**：Ncloud Chat 将文件保存在客户拥有的 Object Storage 中，从而防止信息外泄。

### 4. **消息搜索**

* **关键词搜索**：在聊天中使用特定关键词来搜索过去的对话内容。
* **高级过滤选项**：可以应用日期、参与者、文件类型等各种过滤器，以快速找到所需的消息。

### **5. 通知与通知调整**

* **推送通知**：当有新消息或重要更新时，会向用户发送通知，以防止信息遗漏。
* **通知设置**：用户可以调整通知的类型和频率，以便以所需的方式接收信息。

### **6. 安全与隐私保护**

* **数据加密**：所有消息在传输和存储过程中都进行加密，以防止数据泄露。
* **隐私保护**：用户的个人信息和对话内容受到严格保护，未经用户同意不会向第三方公开。

Game Chat 的消息功能使用户的沟通变得顺畅和高效，在工作和日常生活中发挥了重要作用。这些功能帮助用户更轻松地进行沟通，并在增强团队合作方面做出了巨大贡献。

## 消息传递

创建并加入频道后，可以通过以下方式发送新消息。

```csharp
const message = 'Hello !!!';
await nc.sendMessage(
        channelId: CHANNEL_ID, 
        type:"text", 
        content: message
);


// 回复消息时
await nc.sendMessage(
        channelId: CHANNEL_ID, 
        type:"text", 
        content: message, 
        parentMessageId: [MESSAGE_ID]
        );

// 如果需要对消息进行自动翻译
await nc.sendMessage(
        channelId: CHANNEL_ID, 
        type:"text", 
        content: message, 
        translate: true
        );

// 在新消息中，通过以下方式补充父消息的内容，并传递 parent_message。
{
    "id": "message_id",
    "text": "Message",
    "parent_message_id": "first_message_id",
    "parent_message": { 
        "id": "message_id", 
        "text": "message_name",
        "sender" : {
            "id" : "Sender",
             "name" : "Sender Nickname",
             "profile" : "profile url"
        }
    }
}
```

> 备注
>
> 消息以 JSON 格式发送/接收，可以使用各种自定义值。

```csharp
Hashtable messageArray = new Hashtable
{
    { "channel_id", "channelId" },
    { "state", 1 },
    { "desc" , "Desc" }
};
// 将消息转换为普通文本。
const jsonString = JsonConvert.SerializeObject(messageArray);
// 将接收到的消息转换为数组。
Hashtable hashtable = JsonConvert.DeserializeObject<Hashtable>(jsonString);
```

<table><thead><tr><th width="195">ID</th><th width="100">Type</th><th>Description</th></tr></thead><tbody><tr><td>CHANNEL_ID</td><td>string</td><td>频道 ID</td></tr><tr><td>type</td><td>string</td><td>发送的消息类型(text, image)</td></tr><tr><td>MESSAGE</td><td>string</td><td>发送消息时，可以使用文本或 JSON 字符串以实现多种用途。</td></tr><tr><td>MENTIONS</td><td>array</td><td>提及的用户 ID</td></tr></tbody></table>

* 使用 Express Message \
  Express Message 函数专门用于快速发送消息。它跳过所有可能导致时间延迟的部分，使消息发送速度比常规 sendMessage 快 10 倍。其与常规 sendMessage 的区别如下：

<table><thead><tr><th width="209">Function</th><th width="165">Description</th><th>过滤</th><th>屏蔽</th><th>翻译</th></tr></thead><tbody><tr><td>sendMessage</td><td>常规消息发送</td><td>O</td><td>O</td><td>O</td></tr><tr><td>sendExpressMessage</td><td>快速消息发送</td><td>X</td><td>X</td><td>X</td></tr></tbody></table>

可以用于游戏中的实时 PvP 制作或任何需要高速广播的服务。

## 文件上传

* 您可以将文件发送到特定的频道。
* 在大屏幕中选择设置 > 安全 > 允许的文件类型，仅允许上传被允许的文件类型。

```csharp
await nc.sendFile([CHANNEL_ID],file);
```

| ID          | Type   | Description |
| ----------- | ------ | ----------- |
| CHANNEL\_ID | string | 频道 ID       |
| file        | string | 文件信息        |

> 备注
>
> * 必须启用对象存储功能。
> * 仅在与[对象存储](https://www.ncloud.com/product/storage/objectStorage)服务集成后可以使用。
> * 在上传时，请在大屏幕项目设置 > 安全设置中配置上传类型和上传大小等设置。
> * 支持的文件类型：支持所有常见类型，包括图像、视频、文档、压缩文件等。如需支持额外的扩展名，请通过“<cs@nbase.io>”进行询问，我们会在安全审查后添加支持。
> * 使用文件链接时，端点地址为 <https://apps.ncloudchat.naverncp.com。> 例如: <https://apps.ncloudchat.naverncp.com/archive/\\[archiveId>]

## 消息信息 <a href="#undefined" id="undefined"></a>

* Message Data Class

<table><thead><tr><th width="269">ID</th><th width="170">Type</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>string</td><td>ID (unique)</td></tr><tr><td>message_id</td><td>string</td><td>消息 ID</td></tr><tr><td>sort_id</td><td>string</td><td>消息排序 ID</td></tr><tr><td>message_type</td><td>string</td><td>消息类型</td></tr><tr><td>sender.id</td><td>string</td><td>发件人 ID</td></tr><tr><td>sender.name</td><td>string</td><td>发件人姓名</td></tr><tr><td>sender.profile</td><td>string</td><td>发件人头像</td></tr><tr><td>metions</td><td>string</td><td>提及列表</td></tr><tr><td>metions_everyone</td><td>string</td><td>是否全体提及</td></tr><tr><td>content</td><td>string</td><td>消息内容</td></tr><tr><td>created_at</td><td>string</td><td>创建日期</td></tr><tr><td>sended_at</td><td>string</td><td>发送日期</td></tr></tbody></table>

### 单条消息信息

可以获取单条消息的详细信息。

```csharp
NBaseSDK.Message message = await nc.getMessage([CHANNEL_ID], [MESSAGE_ID]);
```

### 全部消息信息

可以获取所有消息的详细信息。

```csharp
Hashtable filter = new Hashtable
{
    { "channel_id", [CHANNEL_ID] }
};
Hashtable sort = new Hashtable
{
    { "sort_id", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var messages = await nc.getMessages(filter, sort, option);
if (messages != null)
    {
            foreach (var message in messages.edges)
        {
            string id = message.Node.message_id.ToString();
            Console.WriteLine("[CloudChatSample] id={0}", id);
        }
    }
```

* Parameters

<table><thead><tr><th width="161">ID</th><th width="113">Type</th><th width="346">Description</th><th>Required</th></tr></thead><tbody><tr><td>filter</td><td>object</td><td>可以对所有字段进行搜索。</td><td>O</td></tr><tr><td>sort</td><td>object</td><td>定义要排序字段的过滤器</td><td>X</td></tr><tr><td>option</td><td>object</td><td>如有可选项，请参阅下方参考内容。</td><td>X</td></tr></tbody></table>

* Options

<table><thead><tr><th width="200">ID</th><th width="160">Type</th><th>Description</th></tr></thead><tbody><tr><td>offset</td><td>number</td><td>起始 offset</td></tr><tr><td>per_page</td><td>number</td><td>返回的数量（最多 100 个）</td></tr></tbody></table>

## 未读消息

返回未读消息的数量。 \
首先通过 markRead 传递最后一条已读消息的信息。

```csharp
nc.markRead([CHANNEL_ID], new NBaseSDK.Mark 
{
    user_id = USER_ID, 
    message_id = MESSAGE_ID,
    sort_id = SORT_ID
});
// 返回标记之后的所有未读消息的总数。
var unread = nc.unreadCount([CHANNEL_ID]);
```

<table><thead><tr><th width="219">ID</th><th width="188">Type</th><th>Description</th></tr></thead><tbody><tr><td>USER_ID</td><td>string</td><td>消息中包含的 user_id 输入</td></tr><tr><td>MESSAGE_ID</td><td>string</td><td>消息中包含的 message_id 输入</td></tr><tr><td>SORT_ID</td><td>string</td><td>消息中包含的 sort_id 输入</td></tr></tbody></table>

## 消息删除

可以删除我在该频道内发送的消息。

```csharp
await nc.deleteMessage([CHANNEL_ID], [MESSAGE_ID]);
```

* Parameters

| ID          | Type   | Description |
| ----------- | ------ | ----------- |
| CHANNEL\_ID | string | 频道 ID       |
| MESSAGE\_ID | string | 消息 ID       |


# 事件

## 事件

在 Game Chat 中，提供了处理客户端发生的各种事件的事件监听器（Event Listener）功能。通过该功能，用户可以实时监控聊天应用内发生的多种情况，并作出适当反应。以下是主要事件类型及其处理方法的说明。

## 主要事件类型

1. **消息接收**: 当接收到新的消息时触发。
2. **消息删除**: 当消息被删除时触发。
3. **错误消息**: 当发生错误时触发。
4. **连接成功**: 当成功连接到服务器时触发。
5. **连接结束**: 当服务器连接结束时触发。
6. **打字开始/结束**: 当用户开始或结束打字时分别触发。
7. **成员添加/移除**: 当用户被添加到或从频道中移除时触发。
8. **成员停用/退出**: 当用户在频道中被停用或退出时触发。

以下是如何在客户端接收事件的方法。

```csharp
nc.dispatcher.onMessageReceived += message =>
{
    Console.WriteLine("received a new message: ", message);
}
```

## 事件处理程序的连接与解除

使用事件处理程序可以接收各种事件，并实现所需的逻辑。 \
以下代码展示了如何连接和解除每个事件的事件处理程序。

```csharp
// 消息接收
nc.dispatcher.onMessageReceived += e =>
{
    Console.WriteLine("onMessageReceived: ", e);
};

// 消息删除
nc.dispatcher.onMessageDeleted += e =>
{
    Console.WriteLine("onMessageDeleted: ", e);
};

// 错误消息
nc.dispatcher.onErrorReceived += e =>
{
    Console.WriteLine("[CloudChatSample] onErrorReceived: ", e);
};

// 连接成功
nc.dispatcher.onConnected += e =>
{
    Console.WriteLine("[CloudChatSample] Connected to server with id: {0} ", e);
};

// 连接结束
nc.dispatcher.onDisconnected += e =>
{
    Console.WriteLine("Disconnected");
};

// 开始输入时
nc.dispatcher.onStartTyping += e =>
{
    Console.WriteLine("onStartTyping: ", e);
};

// 结束输入时
nc.dispatcher.onStopTyping += e =>
{
    Console.WriteLine("onStopTyping: ", e);
};

// 用户在频道中订阅时
nc.dispatcher.onMemberAdded += e =>
{
    Console.WriteLine("onMemberAdded: ", e);
};

// 用户在频道中取消订阅时
nc.dispatcher.onMemberLeft += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberLeft: ", e);
};

// 用户在频道中被禁言时
nc.dispatcher.onMemberBanned += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberBanned: ", e);
};

// 用户在频道中退出时
nc.dispatcher.onMemberDeleted += e =>
{
    Console.WriteLine("[CloudChatSample] onMemberDeleted: ", e);
};
```

通过利用事件监听器，游戏聊天用户可以实时了解聊天环境的变化并作出适当的响应。




---

[Next Page](/llms-full.txt/1)

