所以我看了一个黑手党黑帮机器人的例子,我是他的粉丝,他们的自定义键盘让我感到惊讶:
我发现我必须为Telegram Bots jar添加这个Simple Java API才能实现它。我确实添加了jar,但我知道如何去做。我想用Java创建自定义键盘。这是源代码:
public class Pizza {
private static final Logger LOG = Logger.getLogger(Pizza.class.getName());
public static void main(String... args) throws Exception {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
telegramBotsApi.registerBot(new TelegramLongPollingBot() {
@Override
public void onUpdateReceived(Update update) {
Message message = update.getMessage();
Long chatId = message.getChatId();
String input = message.getText();
if ("/recommend".equals(input)) {
SendMessage request = new SendMessage();
request.setChatId(chatId.toString());
request.setText("Peperoni");
try {
sendMessage(request);
} catch (TelegramApiException e) {
LOG.log(Level.SEVERE, "Could not send message", e);
}
}
}
@Override
public String getBotUsername() {
return "USERNAME_BOT";
}
@Override
public String getBotToken() {
return "BOT_TOKEN";
}
});
}
}
答案 0 :(得分:2)
https://github.com/rubenlagus/TelegramBotsExample有一些此库的使用示例。更确切地说,您可以在https://github.com/rubenlagus/TelegramBotsExample/blob/master/src/main/java/org/telegram/updateshandlers/WeatherHandlers.java(@weatherbot)检查自定义键盘。
在该文件中,您可以看到,例如,使用以下方法生成设置键盘:
private static ReplyKeyboardMarkup getSettingsKeyboard(String language) {
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
replyKeyboardMarkup.setSelective(true);
replyKeyboardMarkup.setResizeKeyboard(true);
replyKeyboardMarkup.setOneTimeKeyboad(false);
List<KeyboardRow> keyboard = new ArrayList<>();
KeyboardRow keyboardFirstRow = new KeyboardRow();
keyboardFirstRow.add(getLanguagesCommand(language));
keyboardFirstRow.add(getUnitsCommand(language));
KeyboardRow keyboardSecondRow = new KeyboardRow();
keyboardSecondRow.add(getAlertsCommand(language));
keyboardSecondRow.add(getBackCommand(language));
keyboard.add(keyboardFirstRow);
keyboard.add(keyboardSecondRow);
replyKeyboardMarkup.setKeyboard(keyboard);
return replyKeyboardMarkup;
}
您可以在SendMessage
方法中使用ReplyKeyboardMarkup,例如:
SendMessage message = new SendMessage();
message.enableMarkdown(true);
message.setReplyMarkup(getSettingsKeyboard(language));
message.setReplyToMessageId(message.getMessageId());
message.setChatId(message.getChatId().toString());
message.setText(getSettingsMessage(language));