Node.JS

[Nest] Slack Webhook

5kiran 2023. 6. 5.
반응형

 

https://api.slack.com/messaging/webhooks

 

Sending messages using Incoming Webhooks

Creating an Incoming Webhook gives you a unique URL to which you send a JSON payload with the message text and some options....

api.slack.com

1. Nest에서 Slack으로 알림 보내기

[Nest] Slack Webhook - 1. Nest에서 Slack으로 알림 보내기

앱을 생성했다면 이제 webhook수신 설정을 해준다

수신 설정을 해주면 아래와 같은 url을 받을 수 있다

https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX

이제 코드로 가보자

우선 라이브러리를 설치해줘야한다.

npm i nestjs-slack-webhook @slack/webhook

라이브러리 설치가 완료됬다면 웹훅을 사용할 모듈에 SlackModule을 import해줘야한다.

여러가지 방식이 있겠지만 필자는 forRoot를 통해 바로 url을 주입하였다

import { SlackModule } from 'nestjs-slack-webhook';

@Module({
  imports: [
    SlackModule.forRoot({
      url: 'https://hooks.slack.com/services/T********/B********/*****************',
    }),
  ],
  controllers: [NotificationController],
  providers: [],
})
export class NotificationModule {}

모듈을 import하고 이제 실제로 슬랙으로 메세지를 보낼 service로 넘어가서 아래와 같이 DI를 해주고 notification 함수를 호출하면 webhook수신 설정을 해둔 채널에 테스트 메세지를 받을 수 있다

@Injectable()
export class NotificationImplementation {
  constructor(
    @InjectSlack() private readonly slack: IncomingWebhook,
  ) {}
  
  notification(){
  	this.slack.send({
    	text: '테스트 메세지'
    })
  }
}

 

반응형

댓글