TELEGRAM OSINT WITH PYTHON, Fetching Telegram Group Participants with Telethon: A Comprehensive Guide

D2

Администратор
Регистрация
19 Фев 2025
Сообщения
4,380
Реакции
0
Fetching Telegram Group Participants with Telethon: A Comprehensive Guide

Osint-XSS.is.png




Hello guys , its LC again
today we are here to create a script that can perform OSINT on telegram group chat users

Telegram, known for its robust security and rich features, has become a popular messaging platform worldwide. For developers, Telegram offers a comprehensive API that allows for extensive programmatic interaction. One powerful library for interfacing with the Telegram API is Telethon.

In this article, we will dive into a Python script that utilizes Telethon to retrieve participants from a Telegram group. We will break down the script, explain each component in detail, and ensure you gain thorough understanding of how it works. By the end of this guide, you'll be able to modify and use the script for your own projects.

Setting Up Your Environment

Before we dive into the script, you need to set up your environment by installing the Telethon library. You can do this using pip:


Python: Скопировать в буфер обмена
pip install telethon


Telethon is a Python library that provides a straightforward interface for interacting with the Telegram API, allowing you to automate tasks such as sending messages, downloading media, and managing groups.

Required Imports

To start, we import several components from the Telethon library:

Python: Скопировать в буфер обмена
Код:
from telethon import TelegramClient
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import ChannelParticipantsRecent



- TelegramClient: The main client class for interacting with the Telegram API.
- GetParticipantsRequest: A request type used to fetch the participants of a Telegram channel.
- ChannelParticipantsRecent: A filter type to specify that we want the recent participants of a channel.

API Credentials

To interact with the Telegram API, you need API credentials (API ID and API Hash), which can be obtained by creating an application on telegram api website .

here is the process you need to go through:

-1. first go to the website that i mentioned earlier


first.png


-2. fill the form and put your account number there.


second.png


-3. click on the api development tools

third.png



-4. fill the form and get your api id and api hash


Set up these credentials in your script as follows:

Python: Скопировать в буфер обмена
Код:
api_id = 'YOUR_API_ID'
api_hash = 'YOUR_API_HASH'
group_link = 'https://t.me/chat' # The link to the group

Replace 'YOUR_API_ID' and 'YOUR_API_HASH' with your actual credentials. The 'group_link' is the URL of the Telegram group you want to retrieve participants from.

Initializing the Telegram Client


Next, we initialize the Telegram client using the API credentials:

Python: Скопировать в буфер обмена
client = TelegramClient('session', api_id, api_hash)

The 'session' parameter is the name of the session file that will be created to store your session details. This file helps maintain your session state between script runs, avoiding the need to re-authenticate every time you run the script.

Defining the Async Function to Get Group Participants


We define an asynchronous function 'get_group_participants' that takes a group link as an argument and fetches the participants of the group:

Python: Скопировать в буфер обмена
Код:
async def get_group_participants(group_link):
    async with client:
        await client.start()
        entity = await client.get_entity(group_link)
        offset_user = 0 # Starting value of the user index
        limit_user = 200 # Number of users to retrieve in each request
        all_participants = [] # List to hold all the participant details
        while True:
            participants = await client(GetParticipantsRequest( entity, ChannelParticipantsRecent(), offset_user, limit_user, hash=0 ))
            if not participants.users:
                break
            for user in participants.users:
                user_data = { 'id': user.id, 'username': user.username, 'access_hash': user.access_hash, }
                all_participants.append(user_data)
            offset_user += len(participants.users)
        return all_participants


1.Explanation of get_group_participants

-1.1 Start the Client Session

Python: Скопировать в буфер обмена
Код:
async with client:
    await client.start()


This ensures that the client session is properly started and will be closed correctly when done. The 'async with' statement ensures that the client is properly initialized and that the session is managed correctly within the block.

-1.2 Convert Group Link to Entity
Python: Скопировать в буфер обмена
entity = await client.get_entity(group_link)

This line converts the group link into an entity that the Telegram API can understand. An entity is a fundamental object in Telegram's API representing users, chats, and channels.

-1.3 Initialize Pagination Variables
Python: Скопировать в буфер обмена
Код:
offset_user = 0
limit_user = 200


These variables help paginate through the list of participants. 'offset_user' is the starting index for the participants, and 'limit_user' is the number of users to fetch in each request. Setting these up allows us to handle groups with a large number of participants.

-1.4 Initialize Participant List


Python: Скопировать в буфер обмена
all_participants = []

This list will store the details of all participants fetched from the group. We will append each participant's data to this list as we retrieve them.

-1.5 Fetch Participants in a Loop

Python: Скопировать в буфер обмена
Код:
while True:
    participants = await client(GetParticipantsRequest( entity, ChannelParticipantsRecent(), offset_user, limit_user, hash=0 ))
    if not participants.users:
        break
    for user in participants.users:
        user_data = { 'id': user.id, 'username': user.username, 'access_hash': user.access_hash, }
        all_participants.append(user_data)
    offset_user += len(participants.users)

This loop continues fetching participants until there are no more users to fetch:

- Request Participants: Sends a request to fetch participants using the 'GetParticipantsRequest'. We specify the 'entity', 'ChannelParticipantsRecent()' filter, 'offset_user', 'limit_user', and a hash of '0'.
- Check for More Users: If no users are returned ('if not participants.users:'), the loop breaks, indicating all users have been fetched.
- Process Each User: Iterates through the list of users returned, extracts their 'id', 'username', and 'access_hash', and appends this data to 'all_participants'.
- Update Offset: Updates 'offset_user' to ensure the next batch of users is fetched correctly.

then at the end we return 'all_participants'

Running the Function

To execute the function and print the results, we define another asynchronous function 'main' and run it:

Python: Скопировать в буфер обмена
Код:
async def main():
    participants = await get_group_participants(group_link)
    for participant in participants:
        print(participant)
    client.loop.run_until_complete(main())

- Main Function: Calls 'get_group_participants' and prints each participant’s details.
- Execute Main: 'client.loop.run_until_complete(main())' runs the 'main' function until it completes, ensuring the async code is executed properly.

Handling Errors and Edge Cases

one of the important parts of any script is to handle error.
To make the script more robust, consider adding error handling and logging. Here’s an example of how you could modify the script to handle potential issues:

Python: Скопировать в буфер обмена
Код:
import logging
from telethon.errors import FloodWaitError, SessionPasswordNeededError
logging.basicConfig(level=logging.INFO)
async def get_group_participants(group_link):
    async with client:
        try:
            await client.start()
        except SessionPasswordNeededError:
            logging.error("Two-factor authentication is enabled, please provide the password.")
            return
        try:
            entity = await client.get_entity(group_link)
        except Exception as e:
            logging.error(f"Failed to get entity for {group_link}: {e}")
            return

        offset_user = 0
        limit_user = 200
        all_participants = []
        
        while True:
            try:
                participants = await client(GetParticipantsRequest(entity, ChannelParticipantsRecent(), offset_user, limit_user, hash=0))
            except FloodWaitError as e:
                logging.warning(f"Rate limit exceeded, waiting for {e.seconds} seconds.")
                await asyncio.sleep(e.seconds)
                continue
            except Exception as e:
                logging.error(f"Failed to fetch participants: {e}")
                break
            if not participants.users:
                break
            for user in participants.users:
                user_data = {'id': user.id,'username': user.username,'access_hash': user.access_hash}
                all_participants.append(user_data)
            offset_user += len(participants.users)
        return all_participants
async def main():
    participants = await get_group_participants(group_link)
    if participants:
        for participant in participants:
            print(participant)client.loop.run_until_complete(main())


at the end, output will be something like this:
output.jpg



Summary:


This script demonstrates how to use the Telethon library to fetch participants from a Telegram group. By following this guide, you should now understand how to:

- Set up the Telethon library and obtain your API credentials.
- Initialize the Telegram client.
- Define and run an asynchronous function to fetch group participants.
- Handle potential errors and implement logging for better debugging and monitoring.


FULL SCRIPT WILL BE ATTACHED
Enjoy.
 
Сверху Снизу