如何通过Telethon获取频道或群组订阅人数且避免ChatAdminRequiredError
使用Telethon获取频道/群组订阅人数并避免ChatAdminRequiredError
核心逻辑
Telegram的权限规则明确:公开频道、超级群组的成员数可直接获取;私有聊天(群组/频道)仅当你是成员或管理员时才能查看人数,否则必然触发ChatAdminRequiredError。我们分场景处理即可:
1. 直接获取公开聊天的成员数
对于公开频道、超级群组,无需管理员权限,调用client.get_chat()就能拿到官方统计的成员数:
from telethon import TelegramClient # 替换为你的API信息 client = TelegramClient('session_name', api_id=你的API_ID, api_hash='你的API_HASH') async def get_public_chat_member_count(chat_identifier): chat = await client.get_chat(chat_identifier) # participants_count 即为订阅/成员人数 return chat.participants_count async def main(): await client.start() # 支持用户名(@xxx)、聊天ID两种格式 count = await get_public_chat_member_count('@telegram') print(f"公开频道成员数:{count}") if __name__ == '__main__': client.loop.run_until_complete(main())
2. 捕获异常处理无权限场景
针对私有聊天,必须用try-except捕获ChatAdminRequiredError,避免程序崩溃,同时给出明确提示:
from telethon import TelegramClient from telethon.errors import ChatAdminRequiredError client = TelegramClient('session_name', api_id=你的API_ID, api_hash='你的API_HASH') async def get_chat_member_count(chat_identifier): try: chat = await client.get_chat(chat_identifier) return chat.participants_count except ChatAdminRequiredError: # 无权限时的自定义处理:返回None、打印提示或跳过该聊天 print(f"无法获取聊天 {chat_identifier} 的成员数:需要管理员权限") return None async def main(): await client.start() # 测试私有群组(假设你不是管理员) private_group_count = await get_chat_member_count(-1001234567890) print(f"私有群组成员数:{private_group_count}") if __name__ == '__main__': client.loop.run_until_complete(main())
重要提示
- 不存在"绕过"权限的方法:Telegram API严格限制非管理员/成员查看私有聊天的成员数,任何声称能绕过的方案都是违规或无效的。
- 大型公开群组的
participants_count是官方提供的近似统计值,无需遍历成员(遍历成员才需要管理员权限)。
内容的提问来源于stack exchange,提问作者theprogrammer451
相关产品推荐
相关产品推荐

