Search code examples
javapythontelegram-botpython-telegram-bot

Making a conversation whit a TelegramBOT on JAVA


I'm currently working on a Java TelegramBot, after programming it in Python. Right now i'm struggling on how to make a reply flow with the bot. Here's a part of the sourcecode:

public void reply (Update update) {

    String text = update.getMessage().getText();
    long chat_id = update.getMessage().getChatId();
    int message_id = update.getMessage().getMessageId();


    if (text.equals("/reply")) {

        SendMessage send = new SendMessage();

        send.setText("Reply to the message that you want to be responsed.")
                .setChatId(chat_id);

        try {
            execute(send);
        } catch (TelegramApiException e) {
            e.printStackTrace();
            System.out.println("Oops");
        }

        if (update.hasMessage() && update.getMessage().hasText() && message_id != update.getMessage().getMessageId()) {

            Message reply = new Message();

            if (reply.hasReplyMarkup()) {
                String response = reply.getText();
                send
                        .setText(response)
                        .setChatId(chat_id);
            }
            try {
                execute(send);
            } catch (TelegramApiException e) {
                e.printStackTrace();
                System.out.println("Oops");
            }
        }
    }
}

The question is, how do i register the next message on the chat? To create a conversation through simple messages. I have a json with words that matches with possible user inputs.

Here's an example of the same flow, but on python.

@bot.message_handler(commands=['conversor'])
def conversor(message):
    chat_id = message.chat.id

    text = ('Puedo convertir las siguientes unidades:\n'
            '1 - m --> cm\n'
            '2 - m --> mm\n'
            '3 - ft --> yardas\n'
            '4 - ft --> in\n'
            '5 - ft --> cm\n'
            '6 - ft --> m\n'

            'Solo respondeme al mensaje el numero de opción, separado del valor a convertir.\n')

    msg = bot.send_message(chat_id, text=text)
    bot.register_next_step_handler(msg, operacion)


def operacion(message):
    chat_id = message.chat.id
    msg = message.text

    answer = str.split(msg)

    option = int(answer[0])
    value = int(answer[1])

    result = functions.bot_conversor(option, value)

    bot.send_message(chat_id, result)

I'm using this api :

https://github.com/pengrad/java-telegram-bot-api

Thanks


Solution

  • Each message in the chat has its own numeric ID. For an easy way to work with "future" messages, you can use message.chat.id+1, but since the program will not receive it for some time - use the threads with the necessary flags (or if it is quite simple, then the usual sleep with the expected time to receive the message, but then the rest of the code will not work)