Telegram Bot API. I can't get the user's contacts. java

Question:

There are comments in the code. I need to get the user's phone number. The telegram api allows you to do this with keyboardButton.setText("Share your number >").setRequestContact(true); that is, a request appears and the user sends his contact with one click. Then I try to display his contact in the System.out.println(update.getMessage().getContact()); console System.out.println(update.getMessage().getContact()); but I get null

public void onUpdateReceived(Update update) {

    if (update.hasMessage() && update.getMessage().hasText()) {
        long chat_id = update.getMessage().getChatId();

        if (update.getMessage().getText().equals("/start")) {

            SendMessage sendMessage = new SendMessage()
                    .setChatId(chat_id)
                    .setText("You send /start");

            // Создаем клавиуатуру
            ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
            sendMessage.setReplyMarkup(replyKeyboardMarkup);
            replyKeyboardMarkup.setSelective(true);
            replyKeyboardMarkup.setResizeKeyboard(true);
            replyKeyboardMarkup.setOneTimeKeyboard(true);

            // Создаем список строк клавиатуры
            List<KeyboardRow> keyboard = new ArrayList<>();

            // Первая строчка клавиатуры
            KeyboardRow keyboardFirstRow = new KeyboardRow();
            // Добавляем кнопки в первую строчку клавиатуры
            KeyboardButton keyboardButton = new KeyboardButton();

            keyboardButton.setText("Share your number >").setRequestContact(true);
            keyboardFirstRow.add(keyboardButton);

            // Добавляем все строчки клавиатуры в список
            keyboard.add(keyboardFirstRow);
            // и устанваливаем этот список нашей клавиатуре
            replyKeyboardMarkup.setKeyboard(keyboard);

            try {
                sendMessage(sendMessage);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }

            System.out.println("#############");
            System.out.println(update.getMessage().getContact());
            System.out.println("#############");

        }
    }
}

Answer:

In general, through debugging, I noticed that the necessary data at a certain moment is nevertheless added. Therefore, by trial and error, I took out the code from the if in which there is a request for the user's phone and everything worked.

Scroll to Top