Как получить предыдущее сообщение (Telegram Bot, использующий JAVA) - PullRequest
1 голос
/ 23 апреля 2020

Я пытаюсь получить предыдущее сообщение. Сначала пользователь отправляет сообщение: «Поиск ученика». Затем Бот отвечает на это сообщение: «Введите имя ученика». Затем пользователь должен что-то написать, и после этого я хотел бы вызвать конкретную c функцию.

Вот мой код:

switch (message.getText()){
      case "Search Student":
            sendMsg(message, "Enter the name of Stunde: ");
            //And somewhere here i would like to call a function that is searching for a student (I have
            //already created the function)
            break;

}

Ответы [ 2 ]

3 голосов
/ 24 апреля 2020

Я также недавно столкнулся с такой проблемой, и я воссоздал этот метод. Но я не уверен, что это хорошее решение! Я также считаю, что нет очень конкретного c ответа на этот вопрос.

Идея состоит в том, чтобы записать последнее действие пользователя / студента / профиля в базу данных, открыв одну таблицу с именем telegram_action table включая следующие столбцы:

telegram action {
  actionName: String; // your case, the action is "Search Student"
  messageId: Integer; // message Id that you want to as previous one
} 

Ваш измененный код:

switch (message.getText()){
      case "Search Student":
            sendMsg(message, "Enter the name of Stunde: ");
            //And somewhere here i would like to call a function that is searching for a student (I have
            //already created the function)
            createTelegramUserAction("Search Student", message.getMessageId());
            break;
      default:
              //I didn't implement this method, idea is simply choose from TelegramAction database
             //that ACTIVE STATUS or not deleted one(there will be only one) with action name "Search Student";
             // Then you will have previous **mesageId** and you will know this message is action of Searching student
             // every time you create new action, `createTelegramAction function` will delete you previous actions, don't worry!
              actionCheck(message);

}

Итак, я создал один createTelegramUserAction() метод для сохранения последнего действия следующим образом:

 public void createTelegramAction(String actionName, Integer messageId, Long chatId) {

            // Disable or Delete all previous actions from database before creating new one!!!
            disableAllActions("Search Students");

            // create action that Student wants search, in your case actionName = "Search Student";
            // save this action to telegram_action table, **didn't implemented**
            create(actionName, messageId);
}



public void disableAllActions(String actionName) {
    // Note that I have chosen to disable the status in here, however you can simply delete all actions
    // In my case, it was necessary to save last action
    // In Deleting case you don't need ActionStatus enum

    // ActionStatus is enum with values {ACTIVE and INACTIVE}
        List<TelegramAction> telegramActions = telegramActionRepository
            .findAllByActionNameAndUserActionStatus(actionName, ActionStatus.ACTIVE);

        for (TelegramAction telegramAction : telegramActions) {
            // here you can either delete the actions or make INACTIVE.
            telegramAction.setActionStatus(ActionStatus.INACTIVE);
            telegramActionRepository.save(telegramAction);
        }
}

Обратите внимание, что этот createTelegramAction метод может использоваться для других методов как обобщенный c метод. Но всегда есть место для улучшения идеи, чтобы сделать ее более обобщенной c функции

1 голос
/ 25 апреля 2020
if(message.getReplyToMessage().getText().contains("Enter the name of Schueler:")){
        List<Schueler> foundSchueler = search.searchSchueler(message.getText(), schueler);
        String foundSchuelerStr = "Found Schueler: \n\n";
        for (Schueler s: foundSchueler) {
            foundSchuelerStr += s.toString();
        }
        sendMsg(message, foundSchuelerStr);
    }

Это мое решение, и оно работает fantasti c! Вы просто должны проверить, ответил ли пользователь на сообщение с указанием c text

...