image by mystical antiquity
Hello guys , its LC again
today we are here again with another article about osint on telegram platform -> part 2 of the telegram osint.
so lets don't waste the time and begin .
let's dive deeper into each section of the code, providing a clearer explanation of what each part does and how it contributes to the overall functionality of interacting with Telegram using the Telethon library.
Step-by-Step Explanation of the Python Script
1. Importing Necessary Libraries
Python:
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest, GetHistoryRequest
from telethon.tl.types import InputPeerEmpty
import csv
Explanation:
- TelegramClient: This is the main class from Telethon that facilitates communication with the Telegram API synchronously.
- GetDialogsRequest: Allows fetching of dialogs (chats and groups) from Telegram.
- GetHistoryRequest: Retrieves message history from a specific chat or group.
- InputPeerEmpty: Represents an empty input peer, used as a placeholder when fetching dialogs.
- csv: Python's built-in module for handling CSV files, essential for storing data fetched from Telegram
api_id = 'YOUR_API_ID'
api_hash = 'YOUR_API_HASH'
phone = 'YOUR_PHONE_NUMBER'
api_id and api_hash: These are required for authenticating your application with the Telegram API. You obtain them by creating a Telegram application at Telegram
phone: Your registered phone number associated with your Telegram account, used for connecting to Telegram through the API.
3. Creating and Connecting the Telegram Client
Python:
client = TelegramClient(phone, api_id, api_hash)
client.start()
Explanation:
- TelegramClient(phone, api_id, api_hash): Initializes a TelegramClient object with your phone number and API credentials.
- client.start(): Initiates the client session, establishing a connection with Telegram's servers. This step is crucial as it sets up the client to interact with Telegram API methods
Python:
chats = []
last_date = None
chunk_size = 200
groups = []
result = client(GetDialogsRequest(
offset_date=last_date,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=chunk_size,
hash=0
))
chats.extend(result.chats)
Explanation:
- GetDialogsRequest: This function fetches a list of chats and groups from Telegram.
- Parameters:
- offset_date, offset_id, offset_peer: These parameters control where to start fetching dialogs. InputPeerEmpty() indicates fetching from the beginning.
- limit: Specifies the maximum number of dialogs (chats/groups) to fetch per request.
- hash: An internal hash for verification purposes.
- After fetching, result.chats contains a list of dialogs (chats and groups) which are then added to the chats list.
Python:
for chat in chats:
try:
if chat.megagroup:
groups.append(chat)
except:
continue
Explanation:
- Iterates through the chats list to filter out groups (chat.megagroup == True).
- chat.megagroup checks if a chat is a mega group.
- Adds the identified mega groups to the groups list for further interaction.
Python:
print("Choose a group to scrape messages and members from:")
i = 0
for g in groups:
print(f"{i} - {g.title}")
i += 1
g_index = input("Enter the number of the group: ")
target_group = groups[int(g_index)]
Explanation:
- Displays a numbered list of available groups (groups) and prompts the user to choose a group by entering the corresponding number (g_index).
- Sets target_group to the group selected by the user based on g_index.
7. Scraping Group Members
Python:
print("Fetching members...")
all_participants = client.get_participants(target_group)
Explanation:
- client.get_participants(target_group): Fetches all participants (members) of the target_group.
- all_participants now holds information about each member fetched from the group.
8. Saving Members to CSV
Python:
print("Saving members to file...")
with open("members.csv", "w", encoding="UTF-8") as f:
writer = csv.writer(f, delimiter=",", lineterminator="\n")
writer.writerow(["username", "name", "group", "id"])
for user in all_participants:
username = user.username if user.username else ""
first_name = user.first_name if user.first_name else ""
last_name = user.last_name if user.last_name else ""
name = (first_name + ' ' + last_name).strip()
writer.writerow([username, name, target_group.title, user.id])
Explanation:
- Opens "members.csv" file in write mode ("w"), preparing to write member data to it.
- csv.writer is used to handle CSV writing with , as the delimiter and \n as the line terminator.
- Writes a header row (["username", "name", "group", "id"]) and iterates through all_participants.
- Extracts relevant details (username, name, target_group.title, user.id) for each member and writes them as a row in the CSV file.
9. Scraping Group Messages
Python:
offset_id = 0
limit = 100
all_messages = []
total_messages = 0
total_count_limit = 0
while True:
history = client(GetHistoryRequest(
peer=target_group,
offset_id=offset_id,
offset_date=None,
add_offset=0,
limit=limit,
max_id=0,
min_id=0,
hash=0
))
if not history.messages:
break
messages = history.messages
for message in messages:
all_messages.append(message.message)
offset_id = messages[len(messages) - 1].id
Explanation:
- Initializes variables (offset_id, limit, all_messages, total_messages, total_count_limit) for message fetching.
- Enters a while True loop to continuously fetch messages until no more messages are returned (if not history.messages: break).
- GetHistoryRequest fetches message history from target_group, specifying parameters like offset_id (starting message ID), limit (number of messages per fetch), and others for finer control over fetching messages.
- Appends each fetched message's content (message.message) to the all_messages list.
- Updates offset_id to continue fetching subsequent messages until the loop exits.
10. Saving Messages to CSV
Python:
print("Saving messages to file...")
with open("chats.csv", "w", encoding="UTF-8") as f:
writer = csv.writer(f, delimiter=",", lineterminator="\n")
for message in all_messages:
writer.writerow([message])
Explanation:
- Opens "chats.csv" file in write mode ("w"), preparing to write message data to it.
- Uses csv.writer to handle CSV writing with , as the delimiter and \n as the line terminator.
- Iterates through all_messages and writes each message (message) as a row in the CSV file.
at the end
summery:
with understanding the functionality of this script , you will understanding how Telethon interacts with the Telegram API to fetch group members and messages, and store them in CSV files.
be a telethon master.
gather information from telegram chats and groups .
hope you use it in a usefull way .
main file will be attached.
if you want to donate this writer{LC} you can use :
USDT -> 0x066c519333AeC9dd0623e33C5ea9f84785910E96
BTC -> bc1q0c2cc7gpsymsr8ey5pt2aujhq7cgcg4q76h9ru
Enjoy!


