Is there a better way with NodeJs to get updates from a Telegram bot?

夙愿已清 提交于 2021-02-10 17:28:43

问题


I'm using simply like below:

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(); 

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


回答1:


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

Getting updates

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.

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

More info on: https://core.telegram.org/bots/api#getting-updates


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



来源:https://stackoverflow.com/questions/50275931/is-there-a-better-way-with-nodejs-to-get-updates-from-a-telegram-bot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!