In simple words about InlineKeyboard in Telegram bots on java

– receiving a request from the user by entering a specific command or typing a specific message into the message field.

For 4 months of independent life of my first bot, it became clear that users do not want to enter anything in the message field. What is much more convenient would be to simply click on the next button when choosing a document form. In other words, in order to simplify interaction with the bot, it is necessary to minimize the ability to use a regular smartphone or PC keyboard.

And there is such an opportunity if you use InlineKeyboard – a variant of buttons (behind which the necessary functionality is hidden) attached directly to the message from the bot.

I decided to use such a keyboard when developing another bot. However, I came across the fact that neither in the Telegram bot Api documentation, nor in articles / analyzes posted on the Internet, there is a transparent step-by-step explanation of the entire process chain. Having figured out for myself the relationship of calls in InlineKeyboard, I decided to share this with other developers.

How it works

To create an embedded keyboard, you need to work with the following classes:

– InlineKeyboardMarkup – an object representing an inline keyboard,

– InlineKeyboardButton – object of one button of the built-in keyboard. A button or set of buttons is located immediately below the message from the bot. The object accepts, among other things, such parameters as: text (displayed on the button, required parameter, supports text and emoji), url (the address to which the user will be redirected), callback_data (string 1-64 characters, which will be passed to the bot through the CallbackQuery object ).

In my project, the main functionality of which is to send the user pictures of the work of the artist that the user selects on the built-in keyboard, I implemented the InlineKeyboard as follows.

1. I created the built-in keyboards themselves in separate classes through methods that return an object of the SendMessage type:

public static SendMessage hermitageInlineKeyboardAb (long chat_id) {

// создаем объект сообщения
        SendMessage message = new SendMessage();
        message.setChatId(chat_id);
        message.setText(«Чтобы увидеть картины, нажми на фамилию художника или перейди в полную коллекцию на сайте музея»);

// создаем объект встроенной клавиатуры
        InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();

// создаем список списков кнопок, который впоследствии объединит ряды кнопок
        List<List<InlineKeyboardButton>> rowsInline = new ArrayList<>();

// создаем список с кнопками для первого ряда
        List<InlineKeyboardButton> rowInline1 = new ArrayList<>();

// создаем первую кнопку для в ряду
        InlineKeyboardButton inlineKeyboardButton1 = new InlineKeyboardButton(); 

// устанавливаем параметр текста на кнопке 
        inlineKeyboardButton1.setText(«Аврезе»); 
        
// устанавливаем параметр callback_data 
        inlineKeyboardButton1.setCallbackData(«АВРЕЗЕ»); 

// создаем по аналогии вторую кнопку в ряду        
        InlineKeyboardButton inlineKeyboardButton2 = new InlineKeyboardButton();
        inlineKeyboardButton2.setText(«Аликс»);
        inlineKeyboardButton2.setCallbackData(«АЛИКС»);

// добавляем кнопки в первый ряд в том порядке, 
// какой нам необходим. В рассматриваемом случае ряд будет содержать 2 кнопки, 
// размер которых будет одинаково пропорционально растянут по ширине сообщения, 
// под которым клавиатура располагается
        rowInline1.add(inlineKeyboardButton1);
        rowInline1.add(inlineKeyboardButton2);

// если необходимо в кнопку запрограммировать переход на адрес 
// Интернет страницы, такой параметр устанавливается через setUrl(String s). 
// При этом в приведенном примере ряд кнопок будет состоять всего из одной кнопки
        InlineKeyboardButton inlineKeyboardButton21 = new InlineKeyboardButton();
        inlineKeyboardButton21.setText(«Переход на внешний сайт»);            
        inlineKeyboardButton21.setUrl(«https://collections.hermitagemuseum.org»); 

// устанавливаем url, указывая строковый параметр с адресом страницы
        inlineKeyboardButton21.setCallbackData(«ПЕРЕХОД НА ВНЕШНИЙ САЙТ»);

        rowInline11.add(inlineKeyboardButton21);

// настраиваем разметку всей клавиатуры
        rowsInline.add(rowInline1);
        rowsInline.add(rowInline2);
…
        rowsInline.add(rowInline11);

// добавляем встроенную клавиатуру в сообщение
        markupInline.setKeyboard(rowsInline);
        message.setReplyMarkup(markupInline);

Separately, it is necessary to dwell on such a parameter as CallbackData. This is a required identifier that allows the bot to understand which button was clicked. Each button has its own individual identifier (in fact, the button id). When a user clicks on a button, such an id is passed to the bot, and the bot, in turn, understands which button was pressed and subsequently performs certain actions for the user (in my case, it sends a picture).

We get the final code of the method:

public static SendMessage hermitageInlineKeyboardAb (long chat_id) {

        SendMessage message = new SendMessage();
        message.setChatId(chat_id);
        message.setText(«Чтобы увидеть картины, нажми на фамилию художника или перейди в полную коллекцию на сайте музея»);

        InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();

        List<List<InlineKeyboardButton>> rowsInline = new ArrayList<>();

        List<InlineKeyboardButton> rowInline1 = new ArrayList<>();
        InlineKeyboardButton inlineKeyboardButton1 = new InlineKeyboardButton();
        inlineKeyboardButton1.setText(«Аврезе»);
        inlineKeyboardButton1.setCallbackData(«АВРЕЗЕ»);
        InlineKeyboardButton inlineKeyboardButton2 = new InlineKeyboardButton();
        inlineKeyboardButton2.setText(«Аликс Ив»);
        inlineKeyboardButton2.setCallbackData(«АЛИКС»);
        rowInline1.add(inlineKeyboardButton1);
        rowInline1.add(inlineKeyboardButton2);

        List<InlineKeyboardButton> rowInline2 = new ArrayList<>();
        InlineKeyboardButton inlineKeyboardButton3 = new InlineKeyboardButton();
        inlineKeyboardButton3.setText(«Амелин»);
        inlineKeyboardButton3.setCallbackData(«АМЕЛИН»);
        InlineKeyboardButton inlineKeyboardButton4 = new InlineKeyboardButton();
        inlineKeyboardButton4.setText(«Арстер»);
        inlineKeyboardButton4.setCallbackData(«АРСТЕР»);
        rowInline2.add(inlineKeyboardButton3);
        rowInline2.add(inlineKeyboardButton4);

        … // иные необходимые ряды кнопок по вышеуказанной аналогии

        List<InlineKeyboardButton> rowInline11 = new ArrayList<>();
        InlineKeyboardButton inlineKeyboardButton21 = new InlineKeyboardButton();
        inlineKeyboardButton21.setText(«Переход на внешний сайт»);
        inlineKeyboardButton21.setUrl(«https://collections.hermitagemuseum.org»);
        inlineKeyboardButton21.setCallbackData(«ПЕРЕХОД НА ВНЕШНИЙ САЙТ»);
        rowInline11.add(inlineKeyboardButton21);

        rowsInline.add(rowInline1);
        rowsInline.add(rowInline2);
     	… 
        rowsInline.add(rowInline11);

        markupInline.setKeyboard(rowsInline);
        message.setReplyMarkup(markupInline);

        return message;

    }

In the bot, this is visualized as follows:

Some developers write that they experimentally found out the restrictions on the number of buttons on the built-in keyboard: no more than eight in a row and no more than a hundred in total. At the same time, although the number of rows is not limited, in total more than a hundred buttons do not work.

2. Processing user actions when pressing the buttons of the built-in keyboard:

In the class where the onUpdateReceived() method is overridden, we write the handling of events related to the built-in keyboards. In such processing, we necessarily carry out at least 2 checks of what came from the user – text or CallbackData (the same button id that we set when creating keyboards). Without the specified checks, response actions from the built-in keyboard will not follow:

@SneakyThrows
@Override
    public void onUpdateReceived(Update update) {

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

// если получен соответствующий текст, 
            if (message_text.equals(«А-Б»)) { 

//то отправляем пользователю нужную встроенную клавиатуру
                execute(HermitageInlineKeyboardAb.hermitageInlineKeyboardAb(chat_id));
            } 

// если же пользователь передал не текст, 
// а некое значение - id кнопки (CallbackData) 

        } else if (update.hasCallbackQuery()) {

// то бот совершает определенные действия
// (в моем случае – отправляет пользователю картинки 
// или перенаправляет его на страницу в Интернете)

            String call_data = update.getCallbackQuery().getData();
            long chat_id = update.getCallbackQuery().getMessage().getChatId();
	String path = «D:\\testBot\\testing\\src\\main\\resources\\page.jpg»;

            if (call_data.equals(«АВРЕЗЕ»)) {
                execute(Sender.sendPhoto(chat_id, path));
            } else if (call_data.equals(«ПЕРЕХОД НА ВНЕШНИЙ САЙТ»)) {                
                execute(Sender.sendMessage(chat_id, ""));
            }

Total

On the one hand, there are plenty of articles and explanatory materials about the built-in keyboards of telegram bots, but there are not so many examples specifically for java. I hope this analysis and implementation of InlineKeyboard in the project, the code of which is posted on GitHubwill help someone in the development of their telegram bots.

If you are interested in how my last telegram bot works, then you are welcome: My own gallery owner.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *