JavaRush /Java Blog /Random EN /Telegram Ability Bot: a bot that can conduct a dialogue: ...
Chundrik
Level 35
Санкт-Петербург

Telegram Ability Bot: a bot that can conduct a dialogue: Part 2

Published in the Random EN group
PART 1 In order not to get confused later in parts of the program, I try to divide all the logic into separate classes. The actual phrases with which the bot will respond will be stored in the interface Constants. Let's create a line there:
String START_DESCRIPTION = "Hello";
Then let's go to the class TelegramBotand insert the following code:
public Ability replyToStart() {
    return Ability
        .builder()
        .name("start")
        .info(Constants.START_DESCRIPTION)
        .locality(ALL)
        .privacy(PUBLIC)
        .action(ctx ->  silent.send("Hello!", ctx.chatId()))
        .build();
}
Telegram Ability Bot: a bot that can conduct a dialogue: Part 2 - 1Now the bot can greet its clients in response to a standard command /start. Try running it: the bot is already a little alive! But, like any Frankenstein monster, he is missing a couple of limbs.Telegram Ability Bot: a bot that can conduct a dialogue: Part 2 - 2

Using the built-in keyboard

In order for the bot to build a dialogue with us, we need two more classes: MessageFactoryand KeyboardFactory. The first one will read people's answers and generate messages, and the second one will create buttons with answers.
public class KeyboardFactory {
    public static ReplyKeyboard startButtons() {
        InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup();
        List<list<inlinekeyboardbutton>> rowsInline = new ArrayList<>();
        List<inlinekeyboardbutton> rowInline = new ArrayList<>();

       rowInline.add(new InlineKeyboardButton().setText("DISCUSSION").setCallbackData(Constants.DISCUSSION));
        rowInline.add(new InlineKeyboardButton().setText("SMALL TALK").setCallbackData(Constants.SMALL_TALK));

        rowsInline.add(rowInline);
        inlineKeyboard.setKeyboard(rowsInline);
        return inlineKeyboard;
    }
}
</inlinekeyboardbutton></list<inlinekeyboardbutton>
Along the way we will add to Constants:
String START_REPLY = "Start using the telegram bot if you are lonely or bored";
String CHOOSE_OPTION = "Make a choice";
String DISCUSSION = "Let's discuss!";
String SMALL_TALK = "Let's talk!";
Now we can simply call our factory's static method to use the built-in keyboard. The most important part of the code is the setCallbackData(). It recognizes which button was pressed by the user. Let's go to MessageFactory:
public class MessageFactory {
    private final MessageSender sender; //используется для отправки сообщений обратно пользователю

    public MessageFactory(MessageSender sender) {
        this.sender = sender;
    }

    public void start (long chatId) {
        try {
            sender.execute(new SendMessage()
                    .setText(Constants.START_REPLY)
                    .setChatId(chatId));

            sender.execute(new SendMessage()
                    .setText(Constants.CHOOSE_OPTION)
                    .setChatId(chatId)
                    .setReplyMarkup(KeyboardFactory.startButtons()));


        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}
Let's replace the code in the method Telegrambot.replyToStart():
public Ability replyToStart() {
        return Ability
                .builder()
                .name("start")
                .info(Constants.START_DESCRIPTION)
                .locality(ALL)
                .privacy(PUBLIC)
                .action(ctx ->  messageFactory.start(ctx.chatId()))
                .build();
    }
And one more amendment in the same class - replacing the constructor:
private TelegramBot(String botToken, String botUsername) {
        super(botToken, botUsername);
        messageFactory = new MessageFactory(sender);
    }
Try restarting your bot. It will now offer the built-in keyboard in response to your actions. Telegram Ability Bot: a bot that can conduct a dialogue: Part 2 - 3Useful life hacks for beginners: If you are using Idea and want to see the documentation for a class, then select the class or method and press Ctrl+J on Mac or Ctrl+Q on Windows. You can also do right click->Go to->Declaration of usages. Thus, for example, you can find out that our AbilityBot actually inherits from the standard TelegramLongPollingBot. Only it uses lambdas, which significantly reduces the code. The next (final) part will develop the dialogue and deployment on Heroku.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION