简体   繁体   English

使用节点 js 从 webhook 电报机器人获取数据

[英]get data from webhook telegram bot with node js

I set the server address for the bot with /setwebhook , now how can I get the data with only node js and https package to access {message:{...} }?我使用/setwebhook设置了机器人的服务器地址,现在如何仅使用节点 js 和 https package 获取数据以访问 {message:{...} }? (like /getupdates method) but by webhook, probably I mean like the php code but in node js: file_get_contents("php://input") . (如/getupdates方法)但通过 webhook,可能我的意思是像 php 代码但在节点 js 中: file_get_contents("php://input") Should I use async or https.createServer ?我应该使用async还是https.createServer If yes, how and please explain a little如果是,如何,请解释一下

You have to create a server that will handle receiving the data.您必须创建一个服务器来处理接收数据。 You can do this by using http.createServer or, more conveniently, using a library such as Express .您可以使用http.createServer或更方便地使用Express等库来完成此操作。 Simple implementation using Express would look like this:使用 Express 的简单实现如下所示:

const app = express();

app.post(`/api/telegram${process.env.TELEGRAM_BOT_TOKEN}`, async (req, res) => {
    
    const message = req.body.message || req.body.edited_message;
    ...
});

In this example, I use bot token in the webhook url (since I and Telegram are the only entities that know the bot token, I can be sure that the requests to the url come from Telegram).在这个例子中,我在 webhook url 中使用了机器人令牌(因为我和 Telegram 是唯一知道机器人令牌的实体,所以我可以确定对 url 的请求来自 Telegram)。 There are better ways to make the webhook secure, such as using secret_token as specified in the docs for setWebhook method.有更好的方法可以使 webhook 安全,例如使用setWebhook方法的文档中指定的secret_token

For development purposes, you can use a service like ngrok to redirect requests from the bot webhook to localhost.出于开发目的,您可以使用ngrok 之类的服务将请求从 bot webhook 重定向到 localhost。

To get an idea of a fully functioning example of implementing webhook with node.js and Express, you can check my open-source project on Github.要了解使用 node.js 和 Express 实现 webhook 的完整功能示例,您可以查看我在 Github 上的开源项目

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

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