NodeJs 有没有更好的方法来从 Telegram bot 获取更新? [英] Is there a better way with NodeJs to get updates from a Telegram bot?

查看:46
本文介绍了NodeJs 有没有更好的方法来从 Telegram bot 获取更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用如下:

class Bot {
   constructor(token) {
     let _baseApiURL = `https://api.telegram.org`;
     //code here
   }

   getAPI(apiName) {
    return axios.get(`${this.getApiURL()}/${apiName}`);
   }

   getApiURL() {
     return `${this.getBaseApiUrl()}/bot${this.getToken()}`;
   }

   getUpdates(fn) {
        this.getAPI('getUpdates')
            .then(res => {
                this.storeUpdates(res.data);
                fn(res.data);
                setTimeout(() => {
                    this.getUpdates(fn);
                }, 1000);
            })
            .catch(err => {
                console.log('::: ERROR :::', err);
            });
    }
}
const bot = new Bot('mytoken');
bot.start(); 

我想知道是否有更好的方法来监听 Telegram 的更新,而不是使用超时并重做对getUpdates"API 的 Ajax 调用

I'd like to know whether there is a better way to listen for Telegram's updates, instead of using a timeout and redo an Ajax call to 'getUpdates' API

推荐答案

Telegram 支持轮询或 webhooks,因此您可以使用后者来避免轮询 getUpdates API

Telegram supports polling or webhooks, so you can use the latter to avoid polling the getUpdates API

有两种相互排斥的方式来接收您的更新bot — 一方面是 getUpdates 方法,另一方面是 Webhooks.传入的更新存储在服务器上,直到机器人收到它们无论哪种方式,但它们的保存时间不会超过 24 小时.

There are two mutually exclusive ways of receiving updates for your bot — the getUpdates method on one hand and Webhooks on the other. Incoming updates are stored on the server until the bot receives them either way, but they will not be kept longer than 24 hours.

无论您选择哪个选项,您都会收到 JSON 序列化的更新对象.

Regardless of which option you choose, you will receive JSON-serialized Update objects as a result.

更多信息:https://core.telegram.org/bots/api#getting-updates

您可以使用 telegraf 轻松设置 webhook 或使用出色的 API 为您处理轮询

You can use telegraf to easily setup a webhook or to handle the polling for you with a great API

这篇关于NodeJs 有没有更好的方法来从 Telegram bot 获取更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆