GCP/Apps Script

Apps Script로 카카오톡 메세지 보내기 (나한테)

whistory 2023. 6. 1. 15:09
반응형

 

Apps Script를 이용해 나에게 카카오톡 메세지를 보내본다.

 

0. 사전준비

일단 kakao developers 사이트에 회원 가입을 진행한다.

 

Kakao Developers

카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.

developers.kakao.com

진행하고 애플리케이션을 등록해준다.

(예시)

애플리케이션을 생성하면 앱 키를 확인할 수 있다.

여기서 REST API 키가 필요하다.

 

 

 

1. 카카오 로그인 활성화

[내 애플리케이션] > [제품 설정] > [카카오 로그인] 페이지로 이동해

활성화상태를 ON 으로 변경한다.

 

 

 

Redirect URI 설정

하단으로 내려 Redirect URI를 입력한다.

구글을 해도, 네이버를 해도 상관없다.

 

 

2. 동의항목 설정

[내 애플리케이션] > [제품 설정] > [동의항목] 으로 이동해,

동의항목들을 아래와 같이 설정해준다.

 

3. 카카오 계정 인증

크롬의 시크릿 모드로 새창을 연 뒤

 

https://kauth.kakao.com/oauth/authorize?client_id={REST API 키}&redirect_uri={REDIRECT_URI}&response_type=code&scope=talk_message

 

로 이동한다.

 

 

메세지 접근 권한을 동의하고 다음으로 이동한다.

위에서 입력한 REDIRECT URI로 페이지가 이동 되고,

URI 뒤에 아래와 같이 code가 return 된다.

https://whiseung.tistory.com/?code={코드}

 

 

4. Access token 얻기

function getAuth() {
    
  const url = "https://kauth.kakao.com/oauth/token";
  const REST_API_KEY = "REST API 키";    // REST API 키
  const API_CODE = "위에서 받은 API 키"; // API 키

  data = {
    "grant_type"   : "authorization_code",
    "client_id"    : REST_API_KEY ,
    "redirect_uri" : "https://whiseung.tistory.com/",
    "code"         : API_CODE 
   }

  const options = {
    contentType: "application/x-www-form-urlencoded;charset=utf-8",
    headers: { 
                Authorization: "Bearer " + REST_API_KEY 
            },
    payload: data
  };
  const res = UrlFetchApp.fetch(url, options).getContentText();
  console.log(res);
}
{
	"access_token":"메세지 전송에 사용될 KEY"
	, "token_type":"bearer"
	, "refresh_token":"리프레시 토큰"
	, "expires_in":9999
	, "scope":"talk_message"
	, "refresh_token_expires_in":9999
}

json 으로 리턴받은 access_token 을 이용해 메세지를 보낸다.

 

Kakao Developers

카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.

developers.kakao.com

 

 

 

5. 메세지 전송

https://developers.kakao.com/docs/latest/ko/message/rest-api#default-template-msg-me

function sendMessage() {
    
  const url = "https://kapi.kakao.com/v2/api/talk/memo/default/send";

  const ACCESS_TOKEN = "위에서 발급받은 access_token";

  var dataString = `template_object={
      "object_type": "text",
      "text": "Hello KAKAO!",
      "link": {
          "web_url": "<https://developers.kakao.com>",
          "mobile_web_url": "<https://developers.kakao.com>"
      },
      "button_title": "바로 확인"
  }`;

  const options = {
    method: "POST",
    headers: { 
                Authorization: "Bearer " + ACCESS_TOKEN
                , contentType: "application/x-www-form-urlencoded;charset=utf-8"
            },
    payload: dataString
  };
  const res = UrlFetchApp.fetch(url, options).getContentText();
  console.log(res);
  
}

 

 

반응형