InlineKeyboard em telegram bots

InlineKeyboard - um teclado anexado a uma mensagem usando um retorno de chamada (CallbackQuery), em vez de enviar uma mensagem de um teclado comum.

Exemplo





Criando um wireframe de bot


Primeiro, crie um projeto no Maven e adicione o repositório " Telegram Bots ":

<dependency> <groupId>org.telegram</groupId> <artifactId>telegrambots</artifactId> <version>4.0.0</version> </dependency> 

Usando o BotFather, registre o bot e obtenha o token:

Ecrã



Em seguida, crie a classe Bot, herda de TelegramLongPollingBot e substitua os métodos:

Código fonte
 import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.objects.Update; public class Bot extends TelegramLongPollingBot { @Override public void onUpdateReceived(Update update) { } @Override public String getBotUsername() { return null; } @Override public String getBotToken() { return null; } } 


Criamos variáveis ​​finais com o nome e o token do bot, adicionamos ao método getBotUsername () - botUserName, ao getBotToken () - token. No método principal, registre o bot:

Código fonte
 import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; public class Bot extends TelegramLongPollingBot { private static final String botUserName = "Habr_Inlinebot"; private static final String token = "632072575:AAG5YNl9tM9MJbnP5HwLB22rVzNCmY05MQI"; public static void main(String[] args) { ApiContextInitializer.init(); TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); try { telegramBotsApi.registerBot(new Bot()); } catch (TelegramApiRequestException e) { e.printStackTrace(); } } @Override public void onUpdateReceived(Update update) { } @Override public String getBotUsername() { return botUserName; } @Override public String getBotToken() { return token; } } 


O quadro do bot está pronto! Agora vamos escrever um método com o InlineKeyboard.

Trabalhar com o InlineKeyboard


Crie um objeto de layout do teclado:

  InlineKeyboardMarkup inlineKeyboardMarkup =new InlineKeyboardMarkup(); 

Agora criamos a posição dos botões.

Criamos um objeto InlineKeyboardButton que possui 2 parâmetros: Texto (O que será escrito no próprio botão) e CallBackData (O que será enviado ao servidor quando o botão for pressionado).

  InlineKeyboardButton inlineKeyboardButton = new InlineKeyboardButton(); inlineKeyboardButton.setText(""); inlineKeyboardButton.setCallbackData("Button \"\" has been pressed"); 

Adicione-o à lista, criando assim uma série.

  List<InlineKeyboardButton> keyboardButtonsRow1 = new ArrayList<>(); keyboardButtons.add(inlineKeyboardButton); 

Se você deseja criar outra linha, basta fazer outra lista e adicionar novos botões a ela.

  List<InlineKeyboardButton> keyboardButtonsRow2 = new ArrayList<>(); keyboardButtons.add(inlineKeyboardButton2); 

Depois disso, precisamos unir as linhas, para criar uma lista de linhas.

 List<List<InlineKeyboardButton>> rowList= new ArrayList<>(); rowList.add(keyboardButtonsRow1); rowList.add(keyboardButtonsRow2); 

Recurso
O desenvolvedor cuidou de nós e podemos escrever imediatamente botões na lista sem criar uma variável.

 keyboardButtonsRow1.add(new InlineKeyboardButton().setText("Fi4a") .setCallbackData("CallFi4a")); 

Agora podemos definir os botões no objeto de layout do teclado.

  inlineKeyboardMarkup.setKeyboard(rowList); 

Se a descrição de como criar um teclado é um pouco confusa, aqui está um diagrama:


Isso é tudo! Agora adicione a marcação à mensagem:

  SendMessage message = new SendMessage().setChatId(chatId).setText("") .setReplyMarkup(inlineKeyboardMarkup); 

Agora podemos enviar, aqui está um método pronto para você:

Código fonte
 public static SendMessage sendInlineKeyBoardMessage(long chatId) { InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup(); InlineKeyboardButton inlineKeyboardButton1 = new InlineKeyboardButton(); InlineKeyboardButton inlineKeyboardButton2 = new InlineKeyboardButton(); inlineKeyboardButton1.setText(""); inlineKeyboardButton1.setCallbackData("Button \"\" has been pressed"); inlineKeyboardButton2.setText("2"); inlineKeyboardButton2.setCallbackData("Button \"2\" has been pressed"); List<InlineKeyboardButton> keyboardButtonsRow1 = new ArrayList<>(); List<InlineKeyboardButton> keyboardButtonsRow2 = new ArrayList<>(); keyboardButtonsRow1.add(inlineKeyboardButton1); keyboardButtonsRow1.add(new InlineKeyboardButton().setText("Fi4a").setCallbackData("CallFi4a")); keyboardButtonsRow2.add(inlineKeyboardButton2); List<List<InlineKeyboardButton>> rowList = new ArrayList<>(); rowList.add(keyboardButtonsRow1); rowList.add(keyboardButtonsRow2); inlineKeyboardMarkup.setKeyboard(rowList); return new SendMessage().setChatId(chatId).setText("").setReplyMarkup(inlineKeyboardMarkup); } 


Optamos por uma opção quando o método será chamado no manipulador de solicitação onUpdateReceived:

Código fonte
  @Override public void onUpdateReceived(Update update) { if(update.hasMessage()){ if(update.getMessage().hasText()){ if(update.getMessage().getText().equals("Hello")){ try { execute(sendInlineKeyBoardMessage(update.getMessage().getChatId())); } catch (TelegramApiException e) { e.printStackTrace(); } } } } } 


Nós tentamos!



Agora precisamos processá-lo, criar uma nova ramificação em if e processar CallbackQuery:

Código fonte
  @Override public void onUpdateReceived(Update update) { if(update.hasMessage()){ if(update.getMessage().hasText()){ if(update.getMessage().getText().equals("Hello")){ try { execute(sendInlineKeyBoardMessage(update.getMessage().getChatId())); } catch (TelegramApiException e) { e.printStackTrace(); } } } }else if(update.hasCallbackQuery()){ try { execute(new SendMessage().setText( update.getCallbackQuery().getData()) .setChatId(update.getCallbackQuery().getMessage().getChatId())); } catch (TelegramApiException e) { e.printStackTrace(); } } } 


Verifique!



Provavelmente é tudo, obrigado pela atenção!


Todo o código fonte:

Código inteiro
 import org.telegram.telegrambots.ApiContextInitializer; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.ApiContext; import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardButton; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import java.util.ArrayList; import java.util.List; public class Bot extends TelegramLongPollingBot { private static final String botUserName = "Habr_Inlinebot"; private static final String token = "632072575:AAG5YNl9tM9MJbnP5HwLB22rVzNCmY05MQI"; public static void main(String[] args) { ApiContextInitializer.init(); TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); try { telegramBotsApi.registerBot(new Bot()); } catch (TelegramApiRequestException e) { e.printStackTrace(); } } @Override public void onUpdateReceived(Update update) { if(update.hasMessage()){ if(update.getMessage().hasText()){ if(update.getMessage().getText().equals("Hello")){ try { execute(sendInlineKeyBoardMessage(update.getMessage().getChatId())); } catch (TelegramApiException e) { e.printStackTrace(); } } } }else if(update.hasCallbackQuery()){ try { execute(new SendMessage().setText( update.getCallbackQuery().getData()) .setChatId(update.getCallbackQuery().getMessage().getChatId())); } catch (TelegramApiException e) { e.printStackTrace(); } } } @Override public String getBotUsername() { return botUserName; } @Override public String getBotToken() { return token; } public static SendMessage sendInlineKeyBoardMessage(long chatId) { InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup(); InlineKeyboardButton inlineKeyboardButton1 = new InlineKeyboardButton(); InlineKeyboardButton inlineKeyboardButton2 = new InlineKeyboardButton(); inlineKeyboardButton1.setText(""); inlineKeyboardButton1.setCallbackData("Button \"\" has been pressed"); inlineKeyboardButton2.setText("2"); inlineKeyboardButton2.setCallbackData("Button \"2\" has been pressed"); List<InlineKeyboardButton> keyboardButtonsRow1 = new ArrayList<>(); List<InlineKeyboardButton> keyboardButtonsRow2 = new ArrayList<>(); keyboardButtonsRow1.add(inlineKeyboardButton1); keyboardButtonsRow1.add(new InlineKeyboardButton().setText("Fi4a").setCallbackData("CallFi4a")); keyboardButtonsRow2.add(inlineKeyboardButton2); List<List<InlineKeyboardButton>> rowList = new ArrayList<>(); rowList.add(keyboardButtonsRow1); rowList.add(keyboardButtonsRow2); inlineKeyboardMarkup.setKeyboard(rowList); return new SendMessage().setChatId(chatId).setText("").setReplyMarkup(inlineKeyboardMarkup); } } 


Source: https://habr.com/ru/post/pt418905/


All Articles