Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handle response from telegram bot api

I am using this api: https://github.com/orzFly/node-telegram-bot

It should work like any other.

Now I want my Bot to have an option to update a string he keeps for some reason. so on "/update" the update function is called, where msg is a Message object (https://core.telegram.org/bots/api#message):

link = "something";
function update(msg) {

    response = tg.sendMessage({
        text: "Send a new URL, please",
        chat_id: msg.chat.id,
        reply_to_message_id: msg.message_id,
        reply_markup: {
            force_reply: true,
            selective: true
        }
    });
    console.log("response: " + response);
    // on reply I want to update link
}

Now this bot asks me to provide a new string. The next answer in telegram is already an answer to the bots request, because of the force_reply. How would I get this answer? 'response' here is a promise object and I don't know what to do with it.

After reading about Promises objects, I tried something like this:

response.then(function successHandler(result) {
    tg.sendMessage({
        text: "new URL is: I don't know",
        chat_id: msg.chat.id
    });
}, function failureHandler(error) {
    colsole.log("error: " + error);
});

But it didn't work. In no way.

I just don't know where to get the reply Message object from. I hope it's clear what I am asking. Otherwise let me know.

like image 462
Sadik Avatar asked Aug 09 '26 02:08

Sadik


1 Answers

If I understood right, you're trying to get the next message from the user and treat it as the new string; Problem is: response will contain the response from Telegram servers stating the result of the message you tried to send; it has nothing to do with the user's response to your message;

In order to do this, you need to control what was the last message your bot sent to a user and, based on that, decide how to handle that user's next message; it could look something like this:

link = "something";
states = {}
function update(msg) {
    if (!states[msg.chat.id] || states[msg.chat.id] == 1) {
        tg.sendMessage({
            text: "Send a new URL, please",
            chat_id: msg.chat.id,
            reply_to_message_id: msg.message_id,
            reply_markup: {
                force_reply: true,
                selective: true
            }
        }).then(() => {
            states[msg.chat.id] = 2
            console.log(`Asked a question to ${msg.chat.id}`);
        });
    } else {
        link = msg.text;
        tg.sendMessage({
            text: `New URL is: ${link}`,
            chat_id: msg.chat.id,
            reply_to_message_id: msg.message_id
        })
    }
}
like image 87
Rogério Munhoz Avatar answered Aug 10 '26 15:08

Rogério Munhoz