Programming/Node.js

[node.js] slack bot 만들기 + typescript

통통만두 2022. 2. 4. 11:27
반응형

제가 속한 연구개발실은 매일 오전 10시에 slack에서 온라인 스크럼을 진행하고 있습니다.

매번 시간에 맞춰서 slack에 글을 쓰는 것도 번거롭고 깜빡할 때도 있어서 이번 기회에 slack bot을 만들어서 알림을 보내도록 만들어봤습니다.

slack에 bot을 추가하는 방법이나 node-schedule, typescript 등등에 대한 내용은 인터넷에 찾아보면 자료가 많으니 여기서는 제가 구현한 소스코드를 공유해드리는 것으로 할게요.

 

Development environment.

  • node v14.16.1
  • typescript
  • node-schedule
  • moment
  • mac

 

package.json

{
  "name": "jarvis",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "start": "nodemon --exec ts-node",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "marsland@hanmail.net",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^17.0.14",
    "@types/node-schedule": "^1.3.2",
    "ts-node": "^10.4.0",
    "typescript": "^4.5.5"
  },
  "dependencies": {
    "@slack/web-api": "^6.6.0",
    "moment": "^2.29.1",
    "node-schedule": "^2.1.0"
  }
}

※ scripts start 에 nodemon으로 실행하게 해놨는데 저는 전역으로 설치해서 해당 파일에 명시가 되어 있지 않습니다. 아래 명령어를 통해서 전역으로 설치하시든지, 아니면 디펜던시에 추가 또는 그냥 node 로 스크립트를 바꿔주시면 되겠습니다.

// 전역 설치
npm i -g nodemon

// 디펜던시 추가
npm i nodemon

 

반응형

 

index.ts

import { WebClient } from '@slack/web-api';
import * as schedule from 'node-schedule';
import 'moment/locale/ko';
import * as moment from 'moment';

const web = new WebClient('token here!!!');

const channelId = 'CPSMYN0JX';

console.log('I \'m ready!!');

const scheduler = schedule.scheduleJob('0 0 10 * * MON-FRI', async () => {
    const response = await web.chat.postMessage({
        channel: channelId,
        text: `${ moment().format('YYYY-MM-DD (dd)') } 온라인 스크럼 스레드`,
        //icon_url: 'https://avatars.slack-edge.com/2022-02-03/3073641821856_cd988ff9ca10c60d939a_48.jpg',
        //username: 'jarvis'
        as_user: true
    });
});

※ token 값은 본인이 사용하는 slack 워크스페이스에 만든 bot의 토큰을 넣어주시면 됩니다.

 

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "ES2017",
    "moduleResolution": "node",
    "sourceMap": false,
    "allowJs": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
      "*": [
        "node_modules/*"
      ]
    }
  },
  "compileOnSave": true,
  "include": ["*.ts"],
  "exclude": [
    "node_modules",
  ]
}
반응형