Skip to content

Command State Bot

Andrey Korsakov edited this page Jan 6, 2024 · 3 revisions

CommandBot

This section of the tutorial will present a barebone example on creating your first CommandBot!

Bot Implementation

Bot token are passed via the constructor and don't require an override.

CommandStateUpdateProcessor commandProcessor = new CommandStateUpdateProcessor(null, null, null);
commandProcessor.getCommandRegistry().register(new SumCommand()); // We create it in a moment

TelegramBot bot = TelegramBotBuilder.init("TEST", System.getenv("BOT_TOKEN")).build();
bot.registerUpdateProcessor(commandProcessor, 1);
bot.init();

That's it to have a valid, compilable and ready to be deployed bot. However, your bot doesn't have a single command to use. Let's declare one!

Sum Command

To add a feature to your bot, you need to implementCommand. Let's create a command to sum two numbers in two different messages.

public class SumCommand implements Command {
@Override
    public String getIdentifier() {
        return "sum";
    }
}

So, we need something to save a state of the command between messages.

public class SumCommand implements Command<SumCommand.State> {

    // Identifier getter

    /**
     * @param stage       Current stage of the command (first or second number entering)
     * @param firstNumber Saved first number
     */
    public record State(int stage, Double firstNumber) {
    }
}

Finally, let's describe command logic.

public class SumCommand implements Command<SumCommand.State> {

    // Identifier getter

    @Override
    public CommandState<SumCommand.State> processCommand(MethodSender methodSender, Message message, String[] arguments, CommandState<?> currentState) {
        State state = (State) currentState.state();
        if (state == null) {
            sendMessage(methodSender, message, "Enter first number");
            return new CommandState<>(getIdentifier(), new State(1, null));
        } else if (state.stage == 1) {
            double i;
            try {
                i = Double.parseDouble(message.getText());
            } catch (Exception e) {
                sendMessage(methodSender, message, "Incorrect format, enter again");
                return new CommandState<>(getIdentifier(), state);
            }
            sendMessage(methodSender, message, "Enter second number");
            return new CommandState<>(getIdentifier(), new State(2, i));
        } else if (state.stage == 2) {
            double i;
            try {
                i = Double.parseDouble(message.getText());
            } catch (Exception e) {
                sendMessage(methodSender, message, "Incorrect format, enter again");
                return new CommandState<>(getIdentifier(), state);
            }
            double result = state.firstNumber + i;
            sendMessage(methodSender, message, "Result: " + result);
            return new CommandState<>(getIdentifier(), null);
        } else {
            return null; // Returning null always mean command execution error!
        }
    }

    private void sendMessage(MethodSender methodSender, Message message, String text) {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(message.getChat().getId().toString());
        sendMessage.setText(text);
        methodSender.send(sendMessage);
    }

    // Nested State record
}

Testing Your Bot

Go ahead and run, then "/sum" to your bot. It should respond back with "Enter first number".

Conclusion

Congratulation on creating your first CommandBot. What's next? So far we've only considered the case of commands, but what about inline replies? CommandBots can also handle that!

Clone this wiki locally