본문 바로가기

Programming/채팅

Rocket chat을 이용한 서버구축

Rocket.chat 홈페이지: rocket.chat/

 

Rocket.Chat - The Leading Communication Hub

Lead with a Communication Hub that allows total control of your data. All in one platform: team collaboration, omnichannel engagement, DevOps and ChatOps.

rocket.chat

Rocket chat documentation: docs.rocket.chat/

 

Welcome to Rocket.Chat Docs

Here you can find all the docs about Rocket.Chat server and client.

docs.rocket.chat

Rocket chat은 중소규모 그룹을 위한 오픈 소스 채팅 플랫폼이며, 슬랙과 매우 유사한 UI를 지니고 있다.
무료로 이용가능한 오픈소스 플랫폼이며, 소스의 변경 및 재배포 역시 가능하기에 많은 회사에서 사내 채팅 플랫폼으로도 활용중이다.

 

1. Rocket chat 설치

Rocket chat 설치는 위의 documentation에서 다양한 방법 등을 소개하고 있지만, 이것저것 따라해본 결과 docker를 이용하여 설치하는 것이 제일 간편하다. (별도의 환경 설정을 해줄 필요가 하나도 없다는 점)

1-1. Docker 설치

https://hub.docker.com/editions/community/docker-ce-desktop-mac

 

Docker Desktop for Mac - Docker Hub

Docker Desktop for Mac Docker Desktop for Mac is an easy-to-install desktop app for building, debugging, and testing Dockerized apps on a Mac. Docker Desktop for Mac is a complete development environment deeply integrated with the Mac OS Hypervisor framewo

hub.docker.com

위 사이트에서 docker를 다운받아 설치한 후, 아래의 명령어를 입력하여 잘 설치되었는 지 확인한다.

docker --version

>> Docker version 19.03.13, build 4484c46d9d

 

1-2. Docker image 다운로드 (Rocket chat, Mongo DB 다운로드)

# rocket.chat 이미지 다운로드
docker pull rocket.chat
 
# mongodb 이미지 다운로드
docker pull mongo:4.0

# 잘 설치되었는 지 확인하기
docker images

 

1-3. Image 실행하기. (Rocket chat, Mongo DB 설치)

# mongo instance 시작
docker run --name db -d mongo:4.0 --smallfiles --replSet rs0 --oplogSize 128

# mongo replica set 시작
docker exec -ti db mongo --eval "printjson(rs.initiate())"

# rocket.chat을 http://localhost:3000에서 구동
docker run --name rocketchat -p 3000:3000 --link db --env ROOT_URL=http://localhost --env MONGO_OPLOG_URL=mongodb://db:27017/local -d rocket.chat

========

# 외부 MONGO URL을 override 하고자 할 경우, 아래의 mongodb://mymongourl/mydb에 대신 삽입
docker run --name rocketchat -p 80:3000 --env ROOT_URL=http://localhost --env MONGO_URL=mongodb://mymongourl/mydb --env MONGO_OPLOG_URL=mongodb://mymongourl:27017/local -d rocket.chat

========

# 잘 돌아가는 지 확인

docker ps
>>CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
>>############        rocket.chat         "node main.js"           2 hours ago         Up 2 hours          0.0.0.0:3000->3000/tcp   rocketchat
>>############        mongo:4.0           "docker-entrypoint.s…"   2 hours ago         Up 2 hours          27017/tcp                db

# http://localhost:3000 - home 화면 (시작 시 관리자 가입 및 설정)
# http://localhost:3000/admin - admin 관리자 화면

 

간단하게 rocket chat 사용을 위한 세팅이 마무리 되었다.

 

2. REST-API를 활용한 Rocket chat 관리

2-1. Auth-Token, User-Id 생성

로그인 없이 REST API를 통해 서버와 통신하기 위해서는 사용자의 토큰과 사용자 ID가 있어야한다.

http://localhost:3000에서 로그인 한 후,
Profile -> My Account -> Security -> Personal Access Tokens 혹은
프로필 -> 내 계정 -> 개인접근토큰에서 추가를 하여 토큰과 사용자ID를 생성한다.

아래와 같은 안내창이 나타날 것이다.

나중에 토큰을 볼 수 없으므로 주의해서 토큰을 저장하십시오.
토큰 : ######################################
사용자 ID : #########################

2-2. Auth-Token, User-Id Post Request를 이용하여 생성

# Create Token

curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     -H "Content-type:application/json" \
     http://localhost:3000/api/v1/users.createToken \
     -d '{ "userId": "BsNr28znDkG8aeo7W" }'

2-3. Token 유효기간

Token에 대한 유효기간이 존재하는 것 같으나 Token 정확한 유효기간에 대한 별다른 문서의 언급 아래 외에는 찾을 수 없었다.
하지만 stack overflow에서 해당 유효기간이 존재하지 않는다는 게시글이 있었다.
링크 >> stackoverflow.com/questions/45866612/rocket-chat-never-expire-auth-token

About token expiration date
As the token expires, you have to call the login method again in order to obtain a new token with a new expiration date.
NB: You don't have to wait until the token is expired before asking for a new token.

토큰이 만료되면 로그인 방법을 다시 호출해야 새 만료 날짜가 있는 새 토큰을 얻을 수 있습니다.
NB: 새 토큰을 요청하기 전에 토큰이 만료될 때까지 기다릴 필요가 없습니다.

 

 

2-2. 사용자 생성 / 변경 / 삭제

X-Auth-Token과, X-User-Id에 각각 위에서 설정한 관리자의 토큰과 사용자 ID를 대신 입력해준다.

2-2-1. 사용자 생성

# 사용자 생성 요청
curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     -H "Content-type:application/json" \
     http://localhost:3000/api/v1/users.create \
     -d '{"name": "name", "email": "email@user.tld", "password": "anypassyouwant", "username": "uniqueusername"}'
     
# 응답 예시
{
   "user": {
      "_id": "BsNr28znDkG8aeo7W",
      "createdAt": "2016-09-13T14:57:56.037Z",
      "services": {
         "password": {
            "bcrypt": "$2a$10$5I5nUzqNEs8jKhi7BFS55uFYRf5TE4ErSUH8HymMNAbpMAvsOcl2C"
         }
      },
      "username": "uniqueusername",
      "emails": [
         {
            "address": "email@user.tld",
            "verified": false
         }
      ],
      "type": "user",
      "status": "offline",
      "active": true,
      "roles": [
         "user"
      ],
      "_updatedAt": "2016-09-13T14:57:56.175Z",
      "name": "name",
      "settings": {}
   },
   "success": true
}

Create User

2-2-2. 사용자 변경

사용자 정보 변경시에는, 위에서 사용자 생성 시 생성된 user의 id를 고윳값으로 입력해주어야 한다.
추가적으로 "error":"TOTP Required [totp-required]"과 같은 에러가 나타났었는데, 이 경우에는 2FA 인증 토큰을 발행하여 해당 토큰을 입력하여주면 에러 없이 실제로 바뀐 결과를 볼 수 있다.

# 사용자 변경 요청
curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     -H "Content-type:application/json" \
     http://localhost:3000/api/v1/users.update \
     -d '{"userId": "BsNr28znDkG8aeo7W", "data": { "name": "new name", "email": "newemail@user.tld" }}'

 

2-2-3. 사용자 삭제

# 사용자 삭제 요청
curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     -H "Content-type:application/json" \
     http://localhost:3000/api/v1/users.delete \
     -d '{"userId": "BsNr28znDkG8aeo7W"}'

 

2-3. 채팅 타입별(개인, 단체, 공지) 사용방법(메시지 전송, 메시지 수신 등)

2-3-1. 채팅방 생성

curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     -H "Content-type: application/json" \
     http://localhost:3000/api/v1/channels.create \
     -d '{ "name": "channelname" }'

2-3-2. 채팅방 초대

curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     -H "Content-type: application/json" \
     http://localhost:3000/api/v1/channels.invite \
     -d '{ "roomId": "ByehQjC44FwMeiLbX", "userId": "nSYqWzZ4GsKTX4dyK" }'

2-3-3. 메시지 전송

curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     -H "Content-type:application/json" \
     http://localhost:3000/api/v1/chat.sendMessage \
     -d '{"message": { "rid": "Xnb2kLD2Pnhdwe3RH", "msg": "This is a test!" }}'

2-3-4. 메시지 조회

# msg id를 알 경우(해당 메시지 조회)
curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     -H "Content-type:application/json" \
     http://localhost:3000/api/v1/chat.getMessage?msgId=7aDSXtjMA3KPLxLjt
     
# room id를 알 경우(해당 방에서 일어난 대화 조회)
curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     http://localhost:3000/api/v1/channels.messages?roomId=ByehQjC44FwMeiLbX

-----------

2-3-5. Direct message 전송

curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     -H "Content-type: application/json" \
     http://localhost:3000/api/v1/im.create \
     -d '{ "username": "rocket.cat" }'

2-3-6. Direct message 조회

# room id를 알 경우,
curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     http://localhost:3000/api/v1/im.messages?roomId=ByehQjC44FwMeiLbX

2-3-5. Direct message 종료

curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     -H "Content-type: application/json" \
     http://localhost:3000/api/v1/im.close \
     -d '{ "roomId": "ByehQjC44FwMeiLbX" }'


2-4. 지원하는 notification 수단(webhook, push message 등) 및 사용방법

 

2-3-1. Room notification  (해당 대화방에 관련된 noti 저장 및 알람)

curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
     -H "X-User-Id: aobEdbYhXfu5hkeqG" \
     -H "Content-type: application/json" \
     http://localhost:3000/api/v1/rooms.saveNotification \
     -d '{"roomId": "5of4weEXaH7yncxz9", "notifications" :{ "desktopNotifications": "all", "disableNotifications": "0", \
     "emailNotifications": "nothing", "audioNotificationValue": "beep", "desktopNotificationDuration": "2", "audioNotifications": "all", \
       "unreadAlert": "nothing", "hideUnreadStatus": "all", "mobilePushNotifications": "mentions"} }'

 

2-3-2. Integration webhook

Incoming webhook

admin page > integration > incoming webhook integrations

1. 활성화 >> 활성화
2. Channel에 게시 >> 어떤 채널에 외부에서 들어오늘 알람을 보여줄 지 선택
3. 스크립트 활성화 밑 아래 스크립트 복사

/* exported Script */
/* globals console, _, s */

/** Global Helpers
 *
 * console - A normal console instance
 * _       - An underscore instance
 * s       - An underscore string instance
 */

class Script {
  /**
   * @params {object} request
   */
  process_incoming_request({ request }) {
    // request.url.hash
    // request.url.search
    // request.url.query
    // request.url.pathname
    // request.url.path
    // request.url_raw
    // request.url_params
    // request.headers
    // request.user._id
    // request.user.name
    // request.user.username
    // request.content_raw
    // request.content

    // console is a global helper to improve debug
    console.log(request.content);

    return {
      content:{
        text: request.content.text
        // "attachments": [{
        //   "color": "#FF0000",
        //   "author_name": "Rocket.Cat",
        //   "author_link": "https://open.rocket.chat/direct/rocket.cat",
        //   "author_icon": "https://open.rocket.chat/avatar/rocket.cat.jpg",
        //   "title": "Rocket.Chat",
        //   "title_link": "https://rocket.chat",
        //   "text": "Rocket.Chat, the best open source chat",
        //   "fields": [{
        //     "title": "Priority",
        //     "value": "High",
        //     "short": false
        //   }],
        //   "image_url": "https://rocket.chat/images/mockup.png",
        //   "thumb_url": "https://rocket.chat/images/mockup.png"
        // }]
       }
    };

    // return {
    //   error: {
    //     success: false,
    //     message: 'Error example'
    //   }
    // };
  }
}

4. integration 저장
5. Webhook URL이 생성됨
위에서 생성된 URL에 다음과 같이 example message post 가능.

curl -X POST -H 'Content-Type: application/json' --data '{"text":"Example message","attachments":[{"title":"Rocket.Chat","title_link":"https://rocket.chat","text":"Rocket.Chat, the best open source chat","image_url":"/images/integration-attachment-example.png","color":"#764FA5"}]}' http://localhost:3000/hooks/SfvZBqen6sFhjQMoQ/C5JZN2joJohY7FyKWX8o4gEzBT9BX7mjyZ7wNxxqWktQvhu2

 

Outcoming webhook

admin page >> integration >> outgoing webhook integration

# 이벤트 트리거 (Event trigger 설정)

1. 메시지 전송
2. 채팅방 생성
3. 채팅방 입장
4. 채팅방 퇴장
5. 사용자 생성

위의 경우에 notification을 설정할 수 있다.

# 채널

1. all_public_channels 모든 공개 채널에서 수신
2. all_private_groups 모든 비공개 그룹에서 수신
3. all_direct_messages 모든 1:1 메시지 수신

위의 경우에 notification을 설정할 수 있다.

# 토큰

아무렇게나 설정을 하여도 조회가 가능하다.
토큰의 역할은 request body에 정보를 담을 수 있는 역할로 활용할 수 있는 것으로 보인다.

# URLs

post request를 보내고자 하는 URL 주소 설정


# post request body example

>> 
POST /? - - ms - -
{
  token: 'outgoing',
  bot: false,
  channel_id: 'XXXXX64JQSxhu82ATcY8micm4YtNPMWmw',
  message_id: 'XXXXwLsB5rqcQqnpK9',
  timestamp: '2020-12-22T13:54:35.293Z',
  user_id: 'TcY8micm4XXXXXXXX',
  user_name: 'XXXXXX423',
  text: 'hi',
  siteUrl: 'http://localhost:3000'
}

추가적으로 고급설정에서 URL에 post 실패 시, 반복 request 요청 횟수를 설정할 수도 있다.

 

0. Login

# 유저이름을 활용한 로그인
curl -H "Content-type:application/json" \
      http://localhost:3000/api/v1/login \
      -d '{ "user": "myusername", "password": "mypassword" }'

# 이메일을 활용한 로그인
curl -H "Content-type:application/json" \
      http://localhost:3000/api/v1/login \
      -d '{ "user": "my@email.com", "password": "mypassword" }'
      
# 2FA 인증해야하는 경우
ex)
curl -H "Content-type:application/json" \
      http://localhost:3000/api/v1/login \
      -d '{ "user": "myusername", "password": "mypassword", "code": "224610" }'

1. Voice Call
Rocket chat에서는 화상 혹은 음성 대화를 위해서는 Jitsi Meet를 이용하여야 한다.

2. Read counter

# 개인메시지 direct message counter

curl -H "X-Auth-Token: 8h2mKAwxB3AQrFSjLVKMooJyjdCFaA7W45sWlHP8IzO" \
     -H "X-User-Id: ew28FnZqipDpvKw3R" \
     -H "Content-type: application/json" \
     http://localhost:3000/api/v1/im.counters?roomId=RtycPC29hqLJfT9xjew28FnZqipDpvKw3R
     
>> {
  "joined":true,
  "members":2,
  "unreads":0,
  "unreadsFrom":"2018-02-21T21:08:51.026Z",
  "msgs":0,
  "latest":"2018-02-21T21:08:51.026Z",
  "userMentions":0,
  "success":true
}
# 채널 channel counter

curl -H "X-Auth-Token: 8h2mKAwxB3AQrFSjLVKMooJyjdCFaA7W45sWlHP8IzO" \
     -H "X-User-Id: ew28FnZqipDpvKw3R" \
     -H "Content-type: application/json" \
     http://localhost:3000/api/v1/channels.counters?roomId=GENERAL
     
>>
{
  "joined":true,
  "members":78,
  "unreads":2,
  "unreadsFrom":"2018-02-23T17:15:51.907Z",
  "msgs":304,
  "latest":"2018-02-23T17:17:03.110Z",
  "userMentions":0,
  "success":true
}