• XSS.stack #1 – первый литературный журнал от юзеров форума

Статья Fetching Telegram Group Participants with Telethon --> P2

looonely_creature

HDD-drive
Пользователь
Регистрация
16.10.2023
Сообщения
40
Реакции
6
photo_2024-06-18_15-21-39.jpg

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
2. Setting Up API Credentials
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
4. Fetching Chats and Groups
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.
5. Filtering and Selecting a Target Group
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.
6. Selecting a Group to Work With
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!
 

Вложения

  • main_script.zip
    1.1 КБ · Просмотры: 33
Пожалуйста, обратите внимание, что пользователь заблокирован
looks like i read a documentation of telethon.
client = TelegramClient(phone, api_id, api_hash) client.start()
if u use this connect to tg account, u account will die
 
will this also get members from groups that hides their member list ?
I didn't zoom on this particular thing , but i guess yes cause it collects all the info from the group and its a good script for gathering and making a big db from users data
 
Пожалуйста, обратите внимание, что пользователь заблокирован
looks like i read a documentation of telethon.

if u use this connect to tg account, u account will die
Делаю так (Акки пока что все живы):
Python:
client = TelegramClient('name_session', api_id, api_hash, device_model="AMD B550", system_version="Windows 10")

3. Creating and Connecting the Telegram Client
Python:
client = TelegramClient(phone, api_id, api_hash)
client.start()

При выставленном 2FA на аккаунте сессия не поднимется, желательно добавить:
Python:
from telethon.errors import SessionPasswordNeededError

client = TelegramClient('name_session', api_id, api_hash, device_model="AMD B550", system_version="Windows 10")
client.connect()
phone = input("Enter phone: ")
client.send_code_request(phone, force_sms=False)
value = input("Enter login code: ")
try:
    me = client.sign_in(phone, code=value)
#Если на акке выставленно 2FA, будет запрос на авторизацию
except SessionPasswordNeededError:
    password = input("Enter password: ")
    me = client.sign_in(password=password)
 
Последнее редактирование:
Пожалуйста, обратите внимание, что пользователь заблокирован
воо, это совсем другое дело, таким образом, при каких нибудь хотяб настройках аккаунт не будет вылетать
client = TelegramClient('name_session', api_id, api_hash, device_model="AMD B550", system_version="Windows 10")
 
I do this (Akki is still alive):
Python:
client = TelegramClient('name_session', api_id, api_hash, device_model="AMD B550", system_version="Windows 10")



If 2FA is set on the account, the session will not go up, it is advisable to add:
Python:
from telethon.errors import SessionPasswordNeededError

client = TelegramClient('name_session', api_id, api_hash, device_model="AMD B550", system_version="Windows 10")
client.connect()
phone = input("Enter phone: ")
client.send_code_request(phone, force_sms=False)
value = input("Enter login code: ")
try:
    me = client.sign_in(phone, code=value)
#If 2FA is set on your account, there will be a request for authorization
except SessionPasswordNeededError:
    password = input("Enter password: ")
    me = client.sign_in(password=password)
Thanks for your advice buddy. Good material 👏
 
Did you test it, is it show the hidden members of group
Я думаю что не будет работать. Он же снимает используя клиентские функции. А если список участников закрыт сервером ТГ. Как он их вытянет? Это специально и было сделано чтобы не парсили участников чата.
 
Я думаю что не будет работать. Он же снимает используя клиентские функции. А если список участников закрыт сервером ТГ. Как он их вытянет? Это специально и было сделано чтобы не парсили участников чата.
Oh that's meant the OSINT on telegram is not going successful
 
Автор нас обманул, статья не его, взято отсюда:
А авторы этой статьи взяли код с:
А я на основе этого сделал свой файловый парсер, вот такой замкнутый круг.
 
Последнее редактирование:
Hello again . As u can see these articles that you send is more than a year ago

and ofc a code for a library in python is unique. For example for connecting we used a function called client.connect()
Can u create another program with the same library that uses another function but does as it had ?

i gathered information in web
Edited by myself , tried its functionality and finally got a script running that was useful
And shared it in here

I Will not accept that this is not my code and its anothers
We might have some variables name the same but that not means that i copied from another one.

With all respect _LC
 
So there are two options.
First u have a fight with me that it might be true cause im a new person in writing articles

Second you haven't coded in python urself cause everyone knows there might be websites like W3S and SOF that programmers help each other
Ты за дураков то нас не держи. Таких совпадений не бывает. Сравни свой код с этим и найди 10 отличий:
Python:
from xmlrpc.client import DateTime
from telethon.sync import TelegramClient
 
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.tl.types import PeerChannel
 
import csv
 
api_id = 18377495
api_hash = "a0c785ad0fd3e92e7c131f0a70987987"
phone = "+79991669331"
 
client = TelegramClient(phone, api_id, api_hash)
 
client.start()
 
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)
for chat in chats:
   try:
       if chat.megagroup== True:
           groups.append(chat)
   except:
       continue
print("Выберите группу для парсинга сообщений и членов группы:")
i=0
for g in groups:
   print(str(i) + "- " + g.title)
   i+=1
g_index = input("Введите нужную цифру: ")
target_group=groups[int(g_index)]
print("Узнаём пользователей...")
all_participants = []
all_participants = client.get_participants(target_group)
print("Сохраняем данные в файл...")
with open("members.csv", "w", encoding="UTF-8") as f:
   writer = csv.writer(f,delimiter=",",lineterminator="\n")
   writer.writerow(["username", "name","group"])
   for user in all_participants:
       if user.username:
           username= user.username
       else:
           username= ""
       if user.first_name:
           first_name= user.first_name
       else:
           first_name= ""
       if user.last_name:
           last_name= user.last_name
       else:
           last_name= ""
       name= (first_name + ' ' + last_name).strip()
       writer.writerow([username,name,target_group.title])
print("Парсинг участников группы успешно выполнен.")
 
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
   if total_count_limit != 0 and total_messages >= total_count_limit:
       break
 
print("Сохраняем данные в файл...")
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])
print('Парсинг сообщений группы успешно выполнен.')

For example for connecting we used a function called client.connect()
Путаешься в своем коде, ты использовал не функцию client.connect(), а функцию client.start():
client = TelegramClient(phone, api_id, api_hash)
client.start()

P.S. Тебе бы слова никто не сказал если бы ты не пытался получить деньги за этот плагиат, вводя администрацию в заблуждение.
 
Последнее редактирование:


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх