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

Telegram API技术问询:如何导出群组联系人及获取成员用户ID

How to Export Group Contacts & Fetch User IDs via Telegram API

Hey there! To answer your core question first: yes, the Telegram API fully supports retrieving group member user IDs and contact information—though using a client library like Telethon or Pyrogram will make this way more straightforward than dealing with raw API requests. Let’s break this down step by step.

1. Fetching Group Member User IDs

Here’s a practical example using Telethon (a popular Python library for interacting with the Telegram API):

Prerequisites

  • First, get your api_id and api_hash: Log into your Telegram account on the official Telegram developer portal, create a new application, and copy the credentials provided.
  • Install Telethon via pip:
    pip install telethon
    

Code Example

from telethon import TelegramClient
import asyncio

# Replace with your actual credentials and group identifier
api_id = YOUR_API_ID
api_hash = 'YOUR_API_HASH'
group_identifier = 'your_group_username'  # Can also use the group's numeric ID

async def get_group_user_ids():
    async with TelegramClient('session_file', api_id, api_hash) as client:
        # Resolve the group entity (works with usernames, links, or numeric IDs)
        group = await client.get_entity(group_identifier)
        
        # Fetch all group members (handles pagination automatically with aggressive=True)
        participants = await client.get_participants(group, aggressive=True)
        
        # Extract user IDs from the participant list
        user_ids = [user.id for user in participants]
        print("Group Member User IDs:", user_ids)
        
        # Optional: Save IDs to a text file for later use
        with open('group_user_ids.txt', 'w') as f:
            for user_id in user_ids:
                f.write(f"{user_id}\n")

# Execute the function
asyncio.run(get_group_user_ids())

Important Notes

  • You need to be a member of the group (or have admin access for private/restricted groups) to fetch member data.
  • Respect Telegram’s rate limits—avoid running this too frequently for large groups to prevent being temporarily restricted.

2. Exporting Group Contacts

Exporting contact info follows a similar workflow, but keep this critical detail in mind: you can only access contact details that the member has made public (like phone number, username, or full name). Private information (e.g., hidden phone numbers) won’t be available via the API.

Code Example (Extending the Above)

Modify the previous function to extract and export contact details:

async def export_group_contacts():
    async with TelegramClient('session_file', api_id, api_hash) as client:
        group = await client.get_entity(group_identifier)
        participants = await client.get_participants(group, aggressive=True)
        
        # Compile contact data into a structured format
        contact_list = []
        for user in participants:
            contact = {
                'user_id': user.id,
                'first_name': user.first_name or 'N/A',
                'last_name': user.last_name or 'N/A',
                'username': user.username or 'N/A',
                'phone': user.phone or 'N/A'  # Only available if the member made it public
            }
            contact_list.append(contact)
        
        # Export to CSV for easy access in spreadsheets
        import csv
        with open('group_contacts.csv', 'w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=['user_id', 'first_name', 'last_name', 'username', 'phone'])
            writer.writeheader()
            writer.writerows(contact_list)
        
        print(f"Successfully exported {len(contact_list)} contacts to group_contacts.csv")

asyncio.run(export_group_contacts())

Key Considerations

  • Always comply with Telegram’s Terms of Service and local privacy laws—never use this data for spam, harassment, or unauthorized purposes.
  • For extremely large groups, add small delays between requests to avoid triggering rate limits.
  • If you prefer using Pyrogram instead of Telethon, the core logic is identical—you’ll just need to adjust the syntax to match that library’s methods.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:49:05