You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Telegram频道帖子历史?解决messages.getHistory调用报错问题

解决Telegram频道历史消息获取问题

错误分析

你遇到的问题核心出在两个关键点:

  • API凭证混淆:你把Bot Token拆分成了api_id和api_hash,这是错误的。api_id和api_hash需要在官方平台注册独立应用获取,和Bot Token完全是两回事。
  • peer参数格式错误:messages.getHistory要求的peer必须是符合Telegram TL类型的结构化对象,频道对应的类型是inputPeerChannel,需要频道的channel_id和access_hash两个关键参数,不能随意填写字符串或数字。

解决步骤

1. 获取正确的API凭证

前往官方平台注册一个新应用(名称、描述可随意填写),即可拿到专属的api_id(纯数字)和api_hash(字符串)。

2. 获取频道的peer信息

先通过contacts.resolveUsername方法传入频道用户名(如example_channel,去掉前面的@),获取频道的ID和access_hash:

3. 修改代码调用getHistory

将获取到的channel_id和access_hash填入inputPeerChannel对象,作为peer参数传入:

const { Telegram } = require('telegram-mtproto');

// 替换为你从官方平台拿到的真实凭证
const telegram = Telegram({
  api_id: 123456, // 纯数字格式
  api_hash: 'your_real_api_hash_string',
});

export default async (req, res) => {
  try {
    // 解析频道用户名,获取peer所需参数
    const channelInfo = await telegram('contacts.resolveUsername', {
      username: 'example_channel'
    });
    const { channel_id, access_hash } = channelInfo.chats[0];

    // 调用getHistory获取频道历史消息
    const channelHistory = await telegram('messages.getHistory', {
      peer: {
        _: 'inputPeerChannel',
        channel_id,
        access_hash
      },
      limit: 100,
    });

    res.end(JSON.stringify(channelHistory))
  } catch(error) {
    console.log(error)
    res.end("error")
  }
}

补充说明

  • 如果目标是私有频道,必须确保你的账号已经加入该频道,否则无法获取历史消息。
  • 若需要获取超过100条消息,可以循环调用messages.getHistory,每次传入offset_id参数(用上一次返回的最后一条消息ID作为偏移值),直到返回的消息列表为空。

内容的提问来源于stack exchange,提问作者Eugeny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 01:27:59