메시지 보내기

GitpleLive의 Javascript SDK를 어떻게 사용하는지 알아보는 튜토리얼 입니다. 초기화, 채널 생성/입장, 메시지 보내기/받기를 통해 전반적인 흐름을 이해할 수 있도록 돕기 위한 문서입니다.
STEP 1
Library 로드
<script src="https://{API_HOST}/sdk/gitple-live-sdk-v{VERSION}.min.js"></script>
STEP 2
초기화
초기화 시에 connect을 하기 위해 세션 토큰의 발행이 필요합니다. 토큰 발행 시 유효기간을 정할 수 있습니다. api 호출을 통해 받은 세션 토큰을 이용하여 깃플 라이브에 접속을 할 수 있으며 핸들러 함수를 통해 서비스에서 일어나는 이벤트에 대응할 수 있습니다. 생략된 더 많은 이벤트들은 SDK - Javascript 메뉴를 참고해주세요.
const app_id = 'app_id';
const url = 'https://{API_HOST}';
const user_id = 'user_id';
const userInfo = {user_id};

let gitplelive = null;

// Api를 통해 받은 세션 토큰 변수
// 세션 토큰을 얻기 위해 front-end에서 Api를 호출하지 않고 서버에서 호출해 사용해야합니다.  
let session_token;

function gitpleLiveInit() {
    const config = {app_id, url, session_token};
    gitplelive = new GitpleLive.Client(config);

    gitplelive.connectUser(userInfo).catch(err => {
        console.log(err);
    });

    /**
     * 이벤트 핸들러 등록
     */

    // 연결됨
    gitplelive.on("connected", () => {
        console.log("GitpleLive Connect");
    });

    // 연결 종료됨
    gitplelive.on("disconnected", () => {
        console.log("GitpleLive Disconnect");
    });

    // 재연결 시작
    gitplelive.on("reconnectTry", () => {
        console.log("GitpleLive reconnectTry");
    });

    // 재연결 성공
    gitplelive.on("reconnectSucceed", () => {
        console.log("GitpleLive reconnectSucceed");
    });

    // 재연결 실패
    gitplelive.on("reconnectFailed", () => {
        console.log("GitpleLive reconnectFailed");
        gitplelive.disconnectUser();
    });

    gitplelive.on("error", (error) => {
        console.log("GitpleLive Error:");
        console.log(error)
    });

    // (이하 이벤트 생략)
}

window.onload = function () {
    startGitpleLive();
}
STEP 3
채널 생성
채널을 생성해야 회원들이 그 채널에 입장 하고 메시지를 주고 받을 수 있습니다. reuse 프로퍼티가 true일 경우 기존에 이미 만들어진 채널에 같은 멤버들이 있다면 채널을 새로 만들지 않고 기존 채널을 재활용할 수 있습니다.
[팁] user1과 user2의 일대일 채팅방이 있다면 채널 아이디를 'user1_user2'와 같이 구성한다면 좀 더 쉽게 채널을 관리할 수 있습니다.

Request

fetch(url, {
    method: "POST",
    headers: {
        "Content-type": "application/json",
        "APP_ID": app_id,
        "APP_API_KEY": app_key
    },
    body: JSON.stringify({
        "channel_id": "channel_1",
        "name": "channel_1",
        "profile_url": "myimage.png",
        "members": [
            "user_1", "user_2"
        ],
        "reuse": false,
        "meta": {}
    })
})
.then((response) => response.json())
.then((data) => console.log(data));
주의사항: 사용자1과 사용자2의 참여로 생성된 채널이라도 다른 사용자가 1번이라도 참여했다가 퇴장한 경우엔 reuse로 재활용할 수 없습니다.

Response

{
  "channel_id": "channel_1",
  "name": "channel_1",
  "profile_url": "myimage.png",
  "type": "group",
  "freeze": false,
  "total_message_count": 0,
  "total_file_count": 0,
  "created_at": 1660115878567,
  "updated_at": 1660115878567,
  "members": [
    {
      "user_id": "user_1",
      "name": "user_1"
    },
    {
        "user_id": "user_2",
        "name": "user_2"
    }
  ]
}
STEP 4
사용자 생성
채널에 입장해보려면 사용자가 필요합니다. 사용자를 생성합니다.

Request

const url = "https://{API_HOST}/v1/users";

fetch(url, {
    method: "POST",
    headers: {
        "Content-type": "application/json",
        "APP_ID": app_id,
        "APP_API_KEY": app_key
    },
    body: JSON.stringify({
        "user_id": "user_3",
        "name": "user_3",
        "profile_url": "",
        "meta": {}
    })
})
.then((response) => response.json())
.then((data) => console.log(data));
}

Response

{
  "user_id": "user_3",
  "name": "user_3",
  "profile_url": "",
  "created_at": 1660119828633,
  "updated_at": 1660119828633
}

Response

200 Success

STEP 5
채널 입장
만들어진 채널에 새로운 회원을 참여시켜봅니다.

Request

const url = "https://{API_HOST}/v1/group/channels/channel_1/join";

fetch(url, {
    method: "PUT",
    headers: {
        "Content-type": "application/json",
        "APP_ID": app_id,
        "APP_API_KEY": app_key
    },
    body: JSON.stringify({
        "member": "user_3"
    })
})
.then((response) => response.json())
.then((data) => console.log(data));

Response

200 Success

STEP 6
메시지 보내기
채널에 메시지를 보냅니다. 메시지가 성공적으로 보내지면, 사용자 정보와 메시지 정보가 반환됩니다.

Request

const url = "https://{API_HOST}/v1/group/channels/channel_1/messages";

fetch(url, {
    method: "POST",
    headers: {
        "Content-type": "application/json",
        "APP_ID": app_id,
        "APP_API_KEY": app_key
    },
    body: JSON.stringify({
        "user_id": "user_1",
        "content": "안녕하세요",
        "meta": {}
    })
})
.then((response) => response.json())
.then((data) => console.log(data));

Response

{
  "user": {
    "user_id": "user_1",
    "name": "user_1",
    "profile_url": "user_1.png",
    "created_at": 1660024377478,
    "updated_at": 1660115878576
  },
  "type": "text",
  "content": "안녕하세요",
  "created_at": 1660122025159,
  "updated_at": 1660122025159,
  "message_id": 4,
  "channel_id": "channel_1"
}
STEP 7
메시지 받기
Step6에서 메시지를 보냈을 때(또는 다른 사용자에 의해) group_message_send 이벤트 핸들러로 부터 channel과 message데이터가 오게됩니다. 두개의 데이터를 통해 채널에 새로 전송된 메시지를 보여줄 수 있습니다.
gitplelive.on("group:message_send", (message, channel) => {
    console.log("=== group:message_send ===");
    console.log("channel:", channel);
    console.log("message:", message);
});

results matching ""

    No results matching ""