Skip to content
coooldoggy.dev

NodeJs로 사용자 수 알림 SlackBot만들기

Nodejs1 min read

코드작성

아침마다 MySqlWorkbench를 실행해서 사용자수를 쿼리하기 귀찮아서 NodeJs로 사용자 수를 슬랙 메시지로 보내주는 Bot을 만들기로 했다..

NodeJS는 잘모르지만 기능이 간단하니까 할 수는 있을 것이라고 생각하고 도전!!

Slack Webhook

코드를 사용해서 Slack 메시지를 보내려면 일단 Slack WebHook을 설정해줘야한다.

브랜디 랩스 블로그 의 글을 보고 설정했다.

코드에 Slack 플러그인과 WebHook URL을 선언하고 Slack 객체를 만들어 Webhook을 설정한다.

1const Slack = require("slack-node");
2
3var slackwebhook = "https://hooks.slack.com/services/";
4
5const slack = new Slack();
6
7slack.setWebhook(slackwebhook);

메시지를 보낼 함수를 만들어준다. 메시지를 보내고 메시지 보내기에 실패하면 mysql과 연결을 끊는다.

1const send = async (message) => {
2 slack.webhook({
3 username: '사용자수 알림이',
4 text: message,
5 channel: '#service'
6 }, function (err, response) {
7 console.log(response);
8 connection.end();
9 });
10}

SQL

핵심으로 원하는 기능이 SQL 쿼리를 실행해서 사용자 수를 알려주는 것이기 때문에 DB와 연결하여 쿼리를 하는 기능이 필요하다.

MySQL 플러그인 선언

1var mysql = require("mysql");

MySQL에 연결하기 위해 필요한 정보들도 선언한다.

1var connection = mysql.createConnection({
2 host: "HOST URL",
3 user:"USER ID",
4 password:"PW",
5 database:"DB NAME"
6});

CRON JOB

매일 아침 8시 30분에 알림을 받고 싶어서 Cron Job을 이용해서 작업주기를 설정하였다. 월화수목금 아침 8시 30분에 "select count(*) from user" 쿼리를 수행 한 뒤 메시지를 보낸다.

1const cron = require('node-cron');
2const schedule = require('node-schedule');
3
4schedule.scheduleJob('30 8 * * 1,2,3,4,5', function () {
5 connection.connect(function (err) {
6 if (err) {
7 throw err;
8 } else {
9 connection.query("select count(*) from user", function (err, rows, fields) {
10 if (!err) {
11 console.log(rows[0]);
12 send(new Date() + " 사용자수 :" + JSON.stringify(rows));
13 } else {
14 console.log(err);
15 }
16
17 });
18 }
19 });
20 connection.end();
21})

Full code

1var mysql = require("mysql");
2const Slack = require("slack-node");
3const cron = require('node-cron');
4const schedule = require('node-schedule');
5var slackwebhook = "https://hooks.slack.com/services/";
6const slack = new Slack();
7slack.setWebhook(slackwebhook);
8
9
10var connection = mysql.createConnection({
11 host: "HOST URL",
12 user:"USER ID",
13 password:"PW",
14 database:"DB NAME"
15});
16
17const send = async (message) => {
18 slack.webhook({
19 username: '사용자수 알림이',
20 text: message,
21 channel: '#service'
22 }, function (err, response) {
23 console.log(response);
24 connection.end();
25 });
26}
27
28schedule.scheduleJob('30 8 * * 1,2,3,4,5', function () {
29 connection.connect(function (err) {
30 if (err) {
31 throw err;
32 } else {
33 connection.query("select count(*) from user", function (err, rows, fields) {
34 if (!err) {
35 console.log(rows[0]);
36 send(new Date() + " 사용자수 :" + JSON.stringify(rows));
37 } else {
38 console.log(err);
39 }
40
41 });
42 }
43 });
44 connection.end();
45})

Deploy

EC2에 git 설치

1sudo yum install git
2git init
3git config --global user.name "your username"
4git config --global user.email [your mail address]

EC2에 nvm 설치

1curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
2
3. ~/.nvm/nvm.sh

EC2에 node 설치

1nvm install node

Node 설치 후 Version 확인

1node -e "console.log('Running Node.js ' + process.version)"

EC2에 Repository clone

1git clone + [repository 주소]

pm2로 실행

pm2 설치

1sudo npm install -g pm2

node app실행

1pm2 start app.js

app이 실행중인지 확인하려면 아래 명령어 사용

1pm2 status