how to create data scraper for telegram group

Solutions on MaxInterview for how to create data scraper for telegram group by the best coders in the world

showing results for - "how to create data scraper for telegram group"
Marco
16 May 2019
1from telethon.sync import TelegramClient
2from telethon.tl.functions.messages import GetDialogsRequest
3from telethon.tl.types import InputPeerEmpty
4import csv
5 
6api_id = 123456
7api_hash = 'YOUR_API_HASH'
8phone = '+111111111111'
9client = TelegramClient(phone, api_id, api_hash)
10 
11client.connect()
12if not client.is_user_authorized():
13    client.send_code_request(phone)
14    client.sign_in(phone, input('Enter the code: '))
15 
16 
17chats = []
18last_date = None
19chunk_size = 200
20groups=[]
21 
22result = client(GetDialogsRequest(
23             offset_date=last_date,
24             offset_id=0,
25             offset_peer=InputPeerEmpty(),
26             limit=chunk_size,
27             hash = 0
28         ))
29chats.extend(result.chats)
30 
31for chat in chats:
32    try:
33        if chat.megagroup== True:
34            groups.append(chat)
35    except:
36        continue
37 
38print('Choose a group to scrape members from:')
39i=0
40for g in groups:
41    print(str(i) + '- ' + g.title)
42    i+=1
43 
44g_index = input("Enter a Number: ")
45target_group=groups[int(g_index)]
46 
47print('Fetching Members...')
48all_participants = []
49all_participants = client.get_participants(target_group, aggressive=True)
50 
51print('Saving In file...')
52with open("members.csv","w",encoding='UTF-8') as f:
53    writer = csv.writer(f,delimiter=",",lineterminator="\n")
54    writer.writerow(['username','user id', 'access hash','name','group', 'group id'])
55    for user in all_participants:
56        if user.username:
57            username= user.username
58        else:
59            username= ""
60        if user.first_name:
61            first_name= user.first_name
62        else:
63            first_name= ""
64        if user.last_name:
65            last_name= user.last_name
66        else:
67            last_name= ""
68        name= (first_name + ' ' + last_name).strip()
69        writer.writerow([username,user.id,user.access_hash,name,target_group.title, target_group.id])      
70print('Members scraped successfully.')
71 
72