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

如何用Python获取Telegram群组/频道的所有用户ID?

问题:如何用Python获取Telegram群组/频道的全部用户ID?

我尝试使用Python获取Telegram群组或频道中所有用户的ID,曾尝试调用telebot库的get_chat_members()方法,但该方法无法使用。目前仅能通过以下代码获取管理员ID,现寻求获取全部用户ID的可行方法:

bot = telebot.TeleBot(bot_token)

administrators = bot.get_chat_administrators(chat_id)

print("List of Administrators:")
for admin in administrators:
    print(f"{admin.user.first_name} (ID: {admin.user.id})")

bot.stop_polling()

可行解决方案

核心说明

Telegram官方Bot API对成员获取有严格限制:普通机器人无法直接批量获取非公开群组/频道的所有成员,且get_chat_members()方法已被移除。以下是两种实用替代方案:

方法1:使用Telebot库(受限场景)

仅适用于超级群组,且机器人必须是该群组管理员。由于无批量接口,只能逐个查询成员,效率极低且易触发频率限制,仅适合小规模测试使用。

示例代码(局限性大,用户ID不连续,无法覆盖所有成员):

bot = telebot.TeleBot(bot_token)
chat_id = "-100xxxxxxxxx"

# 获取成员总数
member_count = bot.get_chat_members_count(chat_id)
print(f"Total members: {member_count}")

# 仅示例,实际需自行调整ID范围
for user_id in range(100000, 200000):
    try:
        member = bot.get_chat_member(chat_id, user_id)
        print(f"{member.user.first_name} (ID: {member.user.id})")
    except Exception as e:
        continue

bot.stop_polling()

方法2:使用Telethon库(推荐,支持多数场景)

Telethon是第三方Telegram客户端库,可模拟普通用户账号登录,能直接获取有权限查看的群组/频道成员列表,不受Bot API限制。

操作步骤:

  1. 安装Telethon:
pip install telethon
  1. 前往my.telegram.org注册账号,获取你的API ID和API Hash。
  2. 编写代码:
from telethon import TelegramClient

# 替换为你的个人信息
api_id = 你的API_ID
api_hash = '你的API_HASH'
phone_number = '+你的手机号'
chat_identifier = '@群组或频道用户名'  # 也可直接填写chat_id

# 初始化客户端,session_name会保存登录状态,下次无需重复验证
client = TelegramClient('telegram_session', api_id, api_hash)

async def fetch_all_members():
    await client.start(phone_number)
    # 获取对话实体
    chat = await client.get_entity(chat_identifier)
    # 获取所有成员(可通过limit参数控制单次获取数量,默认获取全部)
    all_members = await client.get_participants(chat)
    
    print("所有成员列表:")
    for member in all_members:
        # 处理无昵称的情况
        name = member.first_name if member.first_name else "无名称"
        print(f"{name} (ID: {member.id})")
    
    await client.disconnect()

# 运行异步函数
with client:
    client.loop.run_until_complete(fetch_all_members())

注意事项:

  • 使用普通用户账号登录,而非机器人账号
  • 确保你有权限查看目标群组/频道的成员(公开频道无限制,私有群组需先加入)
  • 避免短时间内频繁请求大量数据,防止被Telegram临时限制账号

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:22:41