TIL/개인 TIL
TIL :: Slack-Bot
두캔두잇
2023. 11. 15. 15:21
슬랙 봇 연결 서비스 로직
@Injectable()
export class SlackService {
private web: WebClient;
constructor(private configService: ConfigService) {
const token = this.configService.get<string>('환경변수에 설정한 토큰값');
this.web = new WebClient(token);
}
async sendSlackMessage(message: string): Promise<void> {
try {
const result = await this.web.chat.postMessage({
channel: '채널명 설정',
text: message,
});
console.log('Message sent: ', result.ts);
} catch (error) {
console.error('Error sending message to Slack: ', error);
}
}
}
ConfigService를 주입시켜 환경변수에 접근을 한다. 그리고나서 configservice를 통해 환경변수에 저장시킨 SLACK_BOT_TOKEN이라는 값을 가져와 WebClient 를 생성한다. (WebClient는 slack api를 사용하기 위한 라이브러리이다)
그리고 sendSlackMessage라는 함수를 만들어서 타입을 설정해주고 webclient의 postMessage 라는 메서드를 사용해서 채널을 설정해주고 매개변수로 지정한 (message: string ) 메세지를 text 에 설정을 하고 메세지를 보낼 수 있다. 그리고 콘솔에 성공적으로 메세지가 전송이 되었다면 타임스탬프(result.ts)를 포함하는 객체를 반환하도록 만들어준다.
# 느낀 점
간단한듯하면서도 처음 사용을해서 익숙치 않지만 오픈 API들을 많이 사용하다보면 적응이 될 것 같다.