【问题标题】:How to receive data from Telegram channel to webhook?如何从 Telegram 频道接收数据到 webhook?
【发布时间】:2016-05-19 01:22:48
【问题描述】:

我已经使用 node.js/express 将 Telegram webhook 设置为 mybot:

app.get('/hook', function (req, res) {    

        url='https://api.telegram.org/bot17xxxxx/setwebhook?url=https://example.com/hook'
            request(url, function (error, response, body) {
                    if (!error && response.statusCode == 200) {
                console.log(body)
              }
            response.emit('close');
            });        
    });

当我 GET https://example.com/hook 时,我可以收到我的机器人控制台:

{"ok":true,"result":true,"description":"Webhook was set"}

现在我想从机器人接收数据,这样当用户访问https://telegram.me/mybot?start=xyz 并按/start 时,机器人应该在/hook 的帖子中收到xyz(至少这是我对程序的理解)

这是我收到帖子的路线:

app.post("/hook", function(req, res) {
            console.log(body);

});

但是当用户在她的浏览器中访问https://telegram.me/mybot?start=xyz 并按下/start 时,我发现机器人没有任何反应。

这里可能出了什么问题,如何解决?

【问题讨论】:

标签: node.js telegram telegram-bot


【解决方案1】:

数据来自https://example.com/hook 上的req.body。所以你需要使用 (req.body)

app.post("/hook", function(req, res) {
        console.log(req.body);

});

会有类似的东西

{"update_id":1111111111,"message":{"message_id":2222,"from":{"id":333333333333,"is_bot":false,"first_name":"Username","last_name":"Lastname","username":"username","language_code":"en},"chat":{"id":1111111111,"first_name":"Username","last_name":"Lastname","username":"username","type":"private"},"date":1518592199,"text":"xyz"}}

如果你不使用像 bodyParser bodyParser middleware 这样的东西,你可以解析它

看简单的例子。 body 中的所有信息和 text

中的文本
body=JSON.parse(req.body)
text=body.message.text
console.log(body)
console.log(text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2017-11-28
    • 1970-01-01
    • 2015-08-27
    • 2018-08-18
    • 2016-04-04
    相关资源
    最近更新 更多