简体   繁体   English

如何从Telegram频道接收数据到webhook?

[英]How to receive data from Telegram channel to webhook?

I have set a Telegram webhook to mybot using node.js/express: 我使用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');
            });        
    });

and when I GET https://example.com/hook I could received into my bot console: 当我获得https://example.com/hook我可以收到我的机器人控制台:

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

Now I want to receive data from the bot so that when a users visits https://telegram.me/mybot?start=xyz and press /start , the bot should receive xyz in a post to /hook (at least that's my understaning of the procedure) 现在我想从机器人接收数据,以便当用户访问https://telegram.me/mybot?start=xyz并按/start ,机器人应该在帖子中接收xyz/hook (至少这是我的不足)的程序)

Here is the route that I have to receive the post: 这是我必须收到帖子的路线:

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

});

But I see nothing happen in the bot when user visits https://telegram.me/mybot?start=xyz in her browser and presses /start . 但是当用户在浏览器中访问https://telegram.me/mybot?start=xyz并按下/start时,我发现机器人中没有任何反应。

What can be wrong here, and how to fix it? 这里有什么问题,以及如何解决它?

Data comes in req.body on https://example.com/hook . 数据来自https://example.com/hook上的req.body So you need to work with (req.body) 所以你需要使用(req.body)

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

});

There will be something like that 会有类似的东西

{"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"}}

You can if you don't use something like bodyParser bodyParser middleware you should parse it 如果您不使用bodyParser bodyParser中间件之类的东西,您可以解析它

See simple example. 看简单的例子。 All info in body and text in text 身体的所有信息和文字文本

body=JSON.parse(req.body)
text=body.message.text
console.log(body)
console.log(text)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM