在JAVA上与TelegramBOT进行对话

2024-09-28 13:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

在用Python编程之后,我目前正在开发一个Java TelegramBot。 现在,我正在努力研究如何使用bot实现回复流。 以下是源代码的一部分:

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");
            }
        }
    }
}

问题是,如何在聊天室中注册下一条消息?通过简单的消息创建对话。我有一个json,其中的单词与可能的用户输入匹配

下面是一个相同流的示例,但在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)

我正在使用这个api:

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

谢谢


Tags: textanswersendidmessageifbotchat
1条回答
网友
1楼 · 发布于 2024-09-28 13:33:29

聊天中的每条消息都有自己的数字ID。为了方便处理“未来”消息,您可以使用message.chat.id+1,但由于程序在一段时间内不会接收到它,请使用带有必要标志的线程(或者如果它很简单,则使用通常的sleep预期接收消息的时间,但代码的其余部分将无法工作)

相关问题 更多 >

    热门问题