skip to Main Content

I am trying to have a Telegram Bot respond to a user’s input and convert C to F (and vice versa). At the simplest level this is a breakdown of what I would like to achieve:

  1. User says "Convert"
  2. Bot says "What would you like to convert?"
  3. User says either "Celsius" or "Fahrenheit"
  4. If "Celsius", the bot responds, "Please enter value to convert."

I have tried an approach using a boolean that toggles from ‘false’ to ‘true’ whenever a command of interest was captured (in this case ‘Convert’). Once the bot responds, it toggles back to ‘false’. This is pretty limiting however and I’m not sure is accurate all:

public class Bot extends TelegramLongPollingBot {

    private static Boolean example = false;

    public void onUpdateReceived(Update update) {

        System.out.println(update.getMessage().getText());
        String command = update.getMessage().getText();
        SendMessage message = new SendMessage();

        // Conversation example

        if (command.contains("Convert")) {
            example = true;
            String ask = "What would you like to convert?";
            message.setText(String.valueOf(ask));
        }

        if (example == true && command.contains("Celsius")) {
            example = false;
            String answer = "Please enter value to convert.";
            message.setText(String.valueOf(answer));
        }
}

This is where I am stuck… I am not sure if this method is efficient, and also I am not sure how to capture a Double entered by the user and perform a calculation with it.

2

Answers


  1. I suggest you to do an event based architecture. You can create a abstract class Method including a method which will be called if the method as itself gets called.
    After you did this, register all methods you need (eq. Convert, Celsius …) and execute the code you want to.
    This will reduce the amount of code you need and makes your application much more expandable.

    Login or Signup to reply.
  2. Once you get both commands Convert and Celcius you obviously end up in example == false state:

        if (command.contains("Convert")) {
            example = true;
            ...
        }
    
        if (example == true && command.contains("Celsius")) {
            example = false;
            ...
        } 
    

    The problem here is not only in incomplete state – it is not possible to hold the state in boolean, you need a data type holding at least 3 states: requesting "convert", requesting "celcius/fahhrenheit", requesting value.

    Another problem here is that you have to map current state to current user – your bot will respond with irrelevant messages if two or more users will use your bot in the same time

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search