NodeJs 是否有更好的方法从 Telegram 机器人获取更新?

Is there a better way with NodeJs to get updates from a 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 的更新,而不是使用超时并重做 Ajax 调用 'getUpdates' API

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

获取更新

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-序列化更新对象作为结果。

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


您可以使用 telegraf to easily setup a webhook 或以出色的方式为您处理投票 API