본문 바로가기
토이프로젝트/텔레그램 리마인더 봇

[JAVA/텔레그램봇] 3. 리마인더 봇 개발하기 - 명령어(Command) 사용하기

by 상후 2022. 10. 3.
728x90
반응형

 

 

 

토이프로젝트 - 텔레그램 리마인더 봇 만들기 - 명령어(Command) 사용하기


1. 명령어 등록하기

  - BotFather에서 사용할 명령어를 등록해주면 된다.

  - /setcommands 

  - @봇 이름 선택

  - 사용할 명령어 - 설명

 

명령어(Command) 등록 예시

 

채팅방에서 등록 화인

 

이렇게 필요한 명령어들을 등록해두면 된다.

이제 해당 명령어를 호출했을 때 처리하는 로직을 작성하면 된다.


0. 명령어 관리 클래스 생성

 

package com.shmoon.telegramreminderbot.bot;

public class Commands {

    // help command
    public static final String help = "/help";

}

 

1. 명령어 별로 처리하기 위해 명령어 핸들링 메서드 작성

 

@Override
public void onUpdateReceived(Update update) {
    try {
        handleCommands(update);
    } catch (TelegramApiException e) {
        logger.info("onUpdateReceived()", e);
    }

}

/**
 * 명령어 핸들링 메서드
 *
 * @param update
 * @throws TelegramApiException
 */
private void handleCommands(Update update) throws TelegramApiException {
    if (hasCommand(update)) {
        String chatId = String.valueOf(update.getMessage().getChatId());
        String messageText = update.getMessage().getText();

        if (messageText.startsWith(Commands.help)) {
            sendHelpMessage(chatId);
        }
    }
}

 

2. 명령어인지 확인하는 메서드 작성

 

/**
 * 명령어(command)인지 확인하는 메서드
 *
 * @param update
 */
private boolean hasCommand(Update update) {
    return update.getMessage().getEntities() != null && "bot_command".equals(update.getMessage().getEntities().get(0).getType());
}

 

@Test
void 명령어_확인_테스트() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    // case
    Method method = ReminderBot.class.getDeclaredMethod("hasCommand", Update.class);
    method.setAccessible(true);
    Update update = new Update();
    update.setMessage(new Message());

    ArrayList<MessageEntity> messageEntities = new ArrayList<>();
    MessageEntity messageEntity = new MessageEntity();
    messageEntity.setType("bot_command");
    messageEntities.add(messageEntity);
    update.getMessage().setEntities(messageEntities);

    // when
    boolean isCommand = (boolean) method.invoke(reminderBot, update);

    // then
    assertTrue(isCommand);
}

@Test
void 일반메시지_확인_테스트() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    // case
    Method method = ReminderBot.class.getDeclaredMethod("hasCommand", Update.class);
    method.setAccessible(true);
    Update update = new Update();
    update.setMessage(new Message());

    // when
    boolean isCommand = (boolean) method.invoke(reminderBot, update);

    // then
    assertFalse(isCommand);
}

 

 

3. 명령어 처리 메서드 작성(/help)

 

/**
 * /help 처리 메서드
 *
 * @param chatId
 * @throws TelegramApiException
 */
private void sendHelpMessage(String chatId) throws TelegramApiException {
    execute(SendMessage.builder().chatId(chatId).text("도움말입니다.").build());
}

 

/help 테스트

 

- 명령어 확인 메서드는 불필요해 보인다.

- /help 명령어인지 확인을 들어온 메시지의 접두어를 검사하므로 크게 의미가 없어 보인다.

 

 

 

 

https://github.com/SanghooMoon/telegram-reminder-bot/pull/1/commits/924949081dc7df6c4220be16dae06bf079ff85a3

 

/help 명령어 추가 by SanghooMoon · Pull Request #1 · SanghooMoon/telegram-reminder-bot

/help 명령어 추가 및 기본 세팅 테스트 코드 작성 시 private 메서드 이슈 - https://www.crocus.co.kr/1665

github.com

 

 

 

728x90
반응형

댓글