调用Telegram API获取频道统计数据触发ChatAdminRequiredError报错求助
问题排查与修复方案
错误根因说明
你触发的telethon.errors.rpcerrorlist.ChatAdminRequiredError虽然字面含义为需要聊天管理员权限,但你作为频道所有者仍触发报错,核心原因是参数构造错误、接口字段使用不当或权限配置不符合接口要求,和Telegram官方接口的隐藏校验规则有关。
排查步骤
- 确认当前登录账号权限
你代码中登录的账号,必须是该频道的所有者,或者被分配了查看统计权限的管理员。你可以手动打开Telegram客户端,进入频道「管理」-「管理员列表」,确认登录账号的权限项中「查看统计」为开启状态。 - 校验InputChannel参数正确性
你硬编码的id_channel和access_hash可能存在过期、错误问题,Telegram的access_hash会随账号、频道状态变更,手动填写很容易触发校验失败,导致接口误判为权限不足。 - 检查接口字段合法性
GetBroadcastStatsRequest的dark参数为Telegram内部测试专用字段,普通开发者调用无需传入,携带该字段反而会触发额外权限校验,导致报错。
修复后可运行代码
import configparser from telethon import TelegramClient, functions, types from telethon.errors import SessionPasswordNeededError from telethon.tl.types import InputChannel config = configparser.ConfigParser() config.read("config.ini") api_id = config['Telegram']['api_id'] api_hash = config['Telegram']['api_hash'] phone = config['Telegram']['phone'] username = config['Telegram']['username'] # 直接用频道链接获取实体,无需硬编码id和access_hash channel_link = 'https://t.me/testapi2607' client = TelegramClient(username, api_id, api_hash) async def main(): await client.start() print("Client Created") # 鉴权逻辑 if not await client.is_user_authorized(): await client.send_code_request(phone) try: await client.sign_in(phone, input('Enter the code: ')) except SessionPasswordNeededError: await client.sign_in(password=input('Password: ')) # 动态获取频道实体 channel_entity = await client.get_entity(channel_link) my_channel = InputChannel(channel_entity.id, channel_entity.access_hash) # 调用统计接口,移除无用的dark参数 result = await client(functions.stats.GetBroadcastStatsRequest(channel=my_channel)) print(result.stringify()) with client: client.loop.run_until_complete(main())
额外注意事项
- 新创建的频道需要至少有1个订阅者才会开放统计功能,你可以先手动打开Telegram频道的统计页面,确认页面可以正常加载后再运行代码。
- 统计接口的调用频率限制较严格,短时间内多次调用会触发临时权限限制,建议两次调用间隔至少1分钟。
内容的提问来源于stack exchange,提问作者Nam Nghi
相关产品推荐
相关产品推荐

