InlineKeyboard en Telegram Bots

InlineKeyboard : un teclado conectado a un mensaje mediante una devolución de llamada (CallbackQuery), en lugar de enviar un mensaje desde un teclado normal.

Ejemplo





Crear una estructura metálica de bot


Primero, cree un proyecto en Maven y agregue el repositorio " Telegram Bots ":

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

Usando BotFather, registre el bot y obtenga el token:

Pantalla



A continuación, cree la clase Bot, herede de TelegramLongPollingBot y anule los métodos:

Código fuente
 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; } } 


Creamos variables finales con el nombre del bot y el token, agregamos botUserName al método getBotUsername (), token en getBotToken (). En el método principal, registre el bot:

Código fuente
 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; } } 


¡El marco del bot está listo! Ahora escribamos un método con InlineKeyboard.

Trabajar con InlineKeyboard


Crear un objeto de diseño de teclado:

  InlineKeyboardMarkup inlineKeyboardMarkup =new InlineKeyboardMarkup(); 

Ahora construimos la posición de los botones.

Creamos un objeto InlineKeyboardButton que tiene 2 parámetros: Texto (lo que se escribirá en el botón) y CallBackData (Lo que se enviará al servidor cuando se haga clic en el botón).

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

Agréguelo a la lista, creando así una serie.

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

Si desea crear otra fila, simplemente haga otra lista y agréguele nuevos botones.

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

Después de eso, necesitamos unir las filas, así que cree una lista de filas.

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

Característica
El desarrollador se ocupó de nosotros y podemos escribir botones de inmediato en la lista sin crear una variable.

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

Ahora podemos configurar los botones en el objeto de diseño del teclado.

  inlineKeyboardMarkup.setKeyboard(rowList); 

Si la descripción de cómo crear un teclado es un poco confusa, aquí hay un diagrama:


Eso es todo! Ahora agregue el marcado al mensaje:

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

Ahora podemos enviar, aquí hay un método listo para usted:

Código fuente
 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); } 


Hacemos una opción cuando se llamará al método en el controlador de solicitud onUpdateReceived:

Código fuente
  @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(); } } } } } 


Lo intentamos!



Ahora tenemos que procesarlo, crear una nueva rama en if y procesar CallbackQuery:

Código fuente
  @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(); } } } 


Cheque!



Eso es probablemente todo, ¡gracias por su atención!


Todo el código fuente:

Código completo
 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/es418905/


All Articles