node.js - 有没有更好的方法使用 NodeJs 从 Telegram 机器人获取更新?

标签 node.js telegram 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 调用

最佳答案

Telegram 支持轮询或 Webhook,因此您可以使用后者来避免轮询 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 序列化的 Update 对象。

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

<小时/>

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

关于node.js - 有没有更好的方法使用 NodeJs 从 Telegram 机器人获取更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50275931/

相关文章:

javascript - 使用 Node.js 遍历目录

javascript - 如何检查某人是否通过邀请链接吸引了更多人订阅我的 telegram channel ?

php - Telegram REST API,在消息文本中发送换行符?

javascript - NodeJs HTTP Post 调用,如何将其用作使用 $http 的 AngularJs 的 API

javascript - 在不修改的情况下扩展对象(功能扩展)

javascript - Nodejs 变量无法传递给事件监听器

android - Telegram 上的构建命令失败

android - Telegram API release.keystore 错误

php - 如何从 Telegram bot API 下载大文件

android - 从我的 Android 应用中获取用户的 Telegram ID