프론트엔드

Google Chat API message sender Hook

카엔입니다 2022. 7. 26. 21:57

프로젝트에서 로그가 발생할때 원하는 구글 챗 스페이스에 알림 메세지를 보내는 함수

코드 샘플

const statusList = ["SUCCESS", "ERROR"];

async function webhook(log, status, label) {
	try {
		const fetch = require("node-fetch");
		const webhookURL = "SPACE WEBHOOK URL";

		const data = JSON.stringify({
			text: `[${label} / ${statusList[status]}] \\n${log}`,
		});

		let resp;
		await fetch(webhookURL, {
			method: "POST",
			headers: {
				"Content-Type": "application/json; charset=UTF-8",
			},
			body: data,
		}).then((response) => {
			resp = response;
			console.log(response);
		});
		return resp;
	} catch (err) {
		console.log(err);
	}
}

module.exports = webhook;

사용법

1. 원하는 구글 챗 스페이스 클릭

2. 스페이스명 옆 화살표 클릭 후 웹훅 관리 클릭

3. 생성할 웹훅 이름과 아바타 사진 선택 후 저장

 

4. 생성된 URL 복사
ex) https://chat.googleapis.com/v1/spaces/AAAAll11

 

5. 위 코드 샘플에 webhookURL 변수에 해당 URL을 할당

 

6. 파라미터 수정 (OPTIONAL) 및 전송할 로그를 생성하는 코드 위치에 함수 사용

 

 

참조

https://developers.google.com/chat/how-tos/webhooks#node.js