如何从 Telegram API 获取 latest/new 消息

How to get the latest/new messages from Telegram API

我正在尝试从 Telegram API 获取最新消息(不是机器人 API)。我目前正在使用 messages.getHistory 但 returns 所有消息都从头开始。如果我收到新消息(自从我登录后),那也很好。

到目前为止,我最好的选择是读取所有消息,然后跟踪偏移量,这样我就不会再次读取相同的消息,但这太慢而且资源成本很高。

有一种更简单的方法可以从 Telegram 获取实时更新 API。

如果您将 TCP 连接设置为非轮询,那么只要您的电报帐户有更新,消息就会简单地推送给您。

这消除了您提到的成本,您根本不会得到任何重复项。

对于我的 Telegram 客户,我在启动时只需 运行 就成功地做到了这一点:

TL.invokewithlayer(layer, TL.initconnection(app_id, device_model, system_version, app_version, lang_code, TL.help_getconfig))

然后我只处理来自连接的 TCP 套接字的传入数据。

查尔斯的回答为我指明了正确的方向。对于那些对 node.js 版本感兴趣的人,我设法通过使用 telegram-link 模块并将连接类型设置为 TCP:

来让它工作
var telegramLink = require('telegram.link')();

// set the  environment
var app = {
    // NOTE: if you FORK the project you MUST use your APP ID.
    // Otherwise YOUR APPLICATION WILL BE BLOCKED BY TELEGRAM
    // You can obtain your own APP ID for your application here: https://my.telegram.org
    id: 12345,
    hash: 'somehashcode',
    version: require('../package.json').version,
    lang: 'en',
    deviceModel: os.type().replace('Darwin', 'OS_X'),
    systemVersion: os.platform() + '/' + os.release(),
    connectionType: 'TCP'
};

//var primaryDC = telegramLink.TEST_PRIMARY_DC;
var primaryDC = telegramLink.PROD_PRIMARY_DC;

...

telegramLink.createClient(app, dataCenter, function() {
...

简单的一点是,将其更改为 TCP 会给你想要的效果,你会在 registerOnUpdates 中收到推送给你的消息:

clientProxy.getClient().account.updateStatus(false).then(function() {
    clientProxy.getClient().registerOnUpdates(function(update) {
        console.log('update', update.toPrintable());

        clientProxy.getClient().messages.receivedMessages(update.id, function(err) { console.log(err); });
    });
...

注意 receivedMessages - 如果你不调用它,那么 Telegram 将不会向你发送任何新的更新。如果你的telegram中没有定义receivedMessages-link,在lib/api/messages.js中添加如下代码:

// ***
// messages.**receivedMessages(max_id, [callback])**

// Return a Promise to Confirms receipt of messages by a client, cancels PUSH-notification sending.

// [Click here for more details](https://core.telegram.org/method/messages.receivedMessages)
Messages.prototype.receivedMessages = function(max_id, callback) {
    return utility.callService(api.service.messages.receivedMessages, this.client, this.client._channel, callback, arguments);
};