Line Notify 로 메시지 보내기

알파로그·2023년 4월 30일
0

✏️ 토큰 발급받기

📍 Line Notify 로그인

🔗 Line Notify

  • 로그인은 라인에서 등록한 이메일로 할 수 있다.
  • 로그인 후 My page 로 들어가면 토큰 발급 버튼을 볼수 있다.

📍 그룹 톡방 만들기

  • my page 에서 generate Tocken 을 누르면 자기 자신과 1:1 로 메시지를 보내는 기능만 활성화 되어있다.
  • 일단 특정 사람에게 메시지를 보내려면 그룹톡방을 만들어 그 사람을 톡방에 초대해야 되는 것같다.
    • 라인에 접속해 그룹톡방을 생성해서 다시 generate Tocken 를 누르면 새로만튼 톡방이 활성화된다.

⚠️ 그룹톡방에서 메시지 기능을 사용하려면 Line Notify 를 그룹에 초대해야 된다.


📍 토큰 생성

  • 원하는 톡방을 선택한 뒤 임의의 토근 명을 입력한다.
    • 여기서 입력한 토큰명은 line 메시지 앞에 표시된다.
    • 토큰 값을 카피한다.
    • ⚠️ 토큰값을 분실하면 다시 찾을 방법이 없다. 분실했다면 삭제 후 다시 토큰을 생성해야 한다.

✏️ Srping boot 코드 구현하기

  • 이 기능을 지금까지 구현한 다양한 Controller 메서드에 바로 적용시키기 위해서 Service 계층에 구현하기로 했다.

📍 LineNotifyService

  • Field
    • url 끝점과 Http header 에 입력할 정보들을 선언해준다.
    • token 의 Bearer 은 공급측에서 정한 양식이기 때문에 토큰 값 앞에 필수로 입력해줘야 한다.
  • 나에게 보낼 메시지와 그룹에 보낼 메시지를 별도의 method 로 나누고,
    공통 로직을 처리하는 method 를 별도로 생성했다.
package com.baeker.baeker.base.messge;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

@Service
@Transactional(readOnly = true)
public class LineNotifyService {

    private final String group_token = "Bearer {token}";
    private final String my_token = "Bearer {token}";

    private final static String url = "https://notify-api.line.me/api/notify?message=";
    private final static String HEADER_AUTH = "Authorization";

		//-- 나에게 line 메시지 발송 --//
    public void alarmToMe(String msg) {
        alarm(my_token, msg);
    }

		//-- 그룹에 메시지 발송 --//
    public void alarmToGroup(String msg) {
        alarm(group_token, msg);
    }

		//-- 공통 처리 로직 --//
    private void alarm(String groupToken, String msg) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set(HEADER_AUTH, groupToken);
        String apiContext = url + msg;

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<?> httpEntity = new HttpEntity<>(httpHeaders);
        restTemplate.exchange(apiContext, HttpMethod.POST, httpEntity, String.class);
    }

}

📍 LineNotifyController

  • servcie 로직을 DI 하고 원하는 라인에 메서드를 호출해 원하는 메시지를 전송할 수 있다.
@Controller
@RequestMapping("/line")
@RequiredArgsConstructor
public class LineNotifyController {

    private final LineNotifyService service;

    @GetMapping("/test")
    public String callMsg() {
        service.alarmToMe("나에게 전송한 메시지");
//        service.alarmToGroup("그룹에게 전송한 메시지");

        return "redirect:/";
    }
}

⚠️ 메시지 전송이 실패한 경우

📍 401 에러

  • 인증에 실패할경우 발생하는 에러
    • 인증 자격이 잘못되었거나, 제공되지 않았기 때문에 발생하는 에러
    • http header 입력 양식이 잘못됬거나 토큰값이 잘못된게 아닌지 확인해본다.
로그 메시지 : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception 
		[Request processing failed: org.springframework.web.client.HttpClientErrorException$Unauthorized: 
		401 : [no body]] with root cause

📍 400 에러

  • 메시지를 전송하려는 대상이 존재하지 않을 때 발생하는 에러
    • 이 에러를 봤다면 그룹 메시지 작업중 일거라 생각된다.
    • 그룹 톡방에 메시지를 보내려면 메시지를 보내는 봇을 초대해줘야 하는데 초대없이 메시지를 보낼 때 이 에러가 발생한다.
    • Line Notify 를 톡방에 초대하면 해결된다.
status":400,"message":
		"LINE Notify account doesn't join group which you want to send.

This account has not yet been added to BAEKER bot's connected group chat. 
		Invite this account to "토큰이름" to receive notifications.
profile
잘못된 내용 PR 환영

0개의 댓글