处理来自电报bot api的回复

时间:2015-07-07 16:03:53

标签: node.js promise telegram-bot

我正在使用此api:https://github.com/orzFly/node-telegram-bot

它应该像其他任何一样工作。

现在我希望我的Bot可以选择更新他保留的字符串。等等" / update"调用update函数,其中 msg 是一个Message对象(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
}

现在这个机器人要我提供一个新的字符串。由于force_reply,电报中的下一个答案已经是对机器人请求的回答。 我怎么会得到这个答案? '响应'这是一个承诺对象,我不知道如何处理它。

在阅读了Promises对象之后,我尝试了这样的事情:

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

但它没有用。绝不。

我只是不知道从哪里获得回复Message对象。 我希望我清楚我要问的是什么。否则请告诉我。

2 个答案:

答案 0 :(得分:1)

如果我理解正确,那么您正试图从用户那里获取下一条消息并将其视为新字符串; 问题是:响应将包含来自Telegram服务器的响应,说明您尝试发送的消息的结果;它与用户对您的消息的响应无关;

为了做到这一点,你需要控制机器人发送给用户的最后一条消息是什么,并根据它决定如何处理该用户的下一条消息;它可能看起来像这样:

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

答案 1 :(得分:0)

看来承诺的结果是Telegram的全部回复。因此,您的结果将显示在result.result.text

result变量如下所示:

{
    ok: true
    result: {
        message_id: x,
        from: { ... }
        chat: { ... }
        date: x,
        text: 'message'
    }
}

这很不幸,我建议作者只返回result键。

var api = require('telegram-bot');
api = new api(<TOKEN>);

api.sendMessage({ chat_id: 0, text: 'test' }).then(function (result) {
    console.log(result);
});

api.on('message', function (msg) {
    console.log(msg); // <- will contain the reply
    // msg.text
    // msg.chat.id 
    // msg.from.id
});

api.start();