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

如何在Python的Telethon/Pyrogram中调用GetMessagePublicForwards?

解决Telegram GetMessagePublicForwards调用的参数与权限问题

问题根源分析

你遇到的两个报错本质都和参数构造错误有关:

  • Telethon的权限提示是误导性的,并非真的需要管理员权限,而是频道实体参数不正确导致服务端返回错误权限提示
  • Pyrogram的CHANNEL_INVALID直接说明channel参数的channel_id或access_hash无效

针对你提到的两个核心问题,下面逐一给出解决方案:

1. 正确获取公开频道的access_hash

不需要手动查找或计算,直接用库内置方法获取频道实体,自动提取channel_id和access_hash:

  • Telethon:调用client.get_entity(),传入频道用户名(如@example_channel)或频道链接
  • Pyrogram:调用app.get_chat(),同样传入频道标识即可

2. GetMessagePublicForwards参数详解

该函数用于获取公开消息的转发记录,关键参数注意点:

  • channel:必须是包含有效channel_id和access_hash的InputChannel实体
  • offset_rate/offset_peer/offset_id:分页参数,首次调用全部设为0/InputPeerEmpty/0,后续根据返回结果更新
  • limit:单次获取的最大转发记录数,最大支持100条

3. 修正后的代码

Telethon版本

from telethon.sync import TelegramClient
from telethon import functions, types

api_id = MY_ID
api_hash = MY_HASH

async def get_message_forwards():
    async with TelegramClient('me', api_id, api_hash) as client:
        # 替换成目标公开频道的@用户名
        channel_entity = await client.get_entity("@public_channel_username")
        
        channel = types.InputChannel(
            channel_id=channel_entity.id,
            access_hash=channel_entity.access_hash
        )
        
        # 首次调用分页参数用空值初始化
        result = await client(functions.stats.GetMessagePublicForwardsRequest(
            channel=channel,
            msg_id=MESSAGE_ID,  # 目标消息ID
            offset_rate=0,
            offset_peer=types.InputPeerEmpty(),
            offset_id=0,
            limit=100
        ))
        
        print(result)

import asyncio
asyncio.run(get_message_forwards())

Pyrogram版本

from pyrogram import Client
from pyrogram.raw import functions, types

api_id = MY_ID
api_hash = MY_HASH

async def get_message_forwards():
    async with Client("my_account", api_id, api_hash) as app:
        # 替换成目标公开频道的@用户名
        chat = await app.get_chat("@public_channel_username")
        
        channel = types.InputChannel(
            channel_id=chat.id,
            access_hash=chat.access_hash
        )
        
        # 首次调用分页参数用空值初始化
        r = await app.invoke(
            functions.stats.GetMessagePublicForwards(
                channel=channel,
                msg_id=MESSAGE_ID,  # 目标消息ID
                offset_rate=0,
                offset_peer=types.InputPeerEmpty(),
                offset_id=0,
                limit=100
            )
        )
        
        print(r)

import asyncio
asyncio.run(get_message_forwards())

关键修正点说明

  • 替换手动指定access_hash的方式,通过库方法自动获取有效实体,避免手动输入错误
  • 首次调用时将offset_peer设为InputPeerEmpty(),而非原频道实体,符合分页逻辑
  • 修正offset_rate和offset_id的初始值为0,匹配服务端要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:37:21