Telegram is one of the best communications apps around the world. People usually use Telegram for managing their communities and promotions.
Startup companies or ongoing projects use Telegram for bringing audience attention to their products and services. Telegram Members are engaging with the community! This is what we all want. Engaged members will help to grow the community.
In this tutorial, you will learn how to use Telegram API extract group members.
So why scraping members from Telegram Groups?
It’s a nice opportunity to get attentions from related Telegram groups. You may want to scrape members from other related groups and add them to yours. Also, you can send messages to them and start engaging (Without Spamming!)
Enough Talking. Let’s get our hands dirty with the code.
Create a Telegram App and Get Your Credentials
Go to my.telegram.org and log in.
Click on API development tools and fill the required fields.
You can choose any name for your app. After submitting, you will receive api_id and api_hash. Save them somewhere. You will use these credentials to login to Telegram API.
Install Telethon
Telethon is a great MTProto API Telegram client library written by LunamiWebs, you can check the Github page here. You can install telethon using pip:
1 2 |
python pip install telethon |
Note: If you are on Linux or Mac, you might need to use sudo before pip to avoid permissions issues.
Create Client Object and Login
Latest version of telethon has two sync and async modules. The async module is using asyncio which is out of the scope of this article. Although you can get the same functionality using both modules but for the sake of simplicity we will use the sync module in this tutorial.
So as the first step you need to import the sync module from Telethon library.
1 2 |
from telethon.sync import TelegramClient |
Then, instantiate your client object using the credentials you got before.
1 2 3 4 5 6 |
from telethon.sync import TelegramClient api_id = 123456 api_hash = 'YOUR_API_HASH' phone = '+111111111111' client = TelegramClient(phone, api_id, api_hash) |
Next step would be connecting to telegram and checking if you are already authorized. Otherwise send an OTP code request and ask user to enter the code they received on their telegram account.
1 2 3 4 5 |
client.connect() if not client.is_user_authorized(): client.send_code_request(phone) client.sign_in(phone, input('Enter the code: ')) |
After logging in, a .session file will be created. This is a database file which makes your session persistent.
Listing All Telegram Groups
Create an empty list for chats and populate with the results which you get from GetDialogsRequest. You need to import two more functions: GetDialogsRequest and InputPeerEmpty
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from telethon.tl.functions.messages import GetDialogsRequest from telethon.tl.types import InputPeerEmpty 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) |
Note: offset_date and offset_peer are used for filtering the chats. We are sending empty values to these parameters so API returns all chats. offset_id and limit are used for pagination. Here we are getting last 200 chats of the user.
In this tutorial, we assume that we are only interested in mega groups; so check if the megagroup attribute of the chat is True and add it to your list.
This is warped inside a try, except block avoid getting an error, because some chats do not have megagroup attribute at all. So basically we skip those using continue statement.
1 2 3 4 5 6 7 |
for chat in chats: try: if chat.megagroup== True: groups.append(chat) except: continue |
Ask User to Select a Group to Scrape Members
After listing the groups, prompt the user to input a number and select the group they want. When this code is executed it loops through every group that you stored in previous step and print it’s name starting with a number. This number is the index of that is your group list.
1 2 3 4 5 6 |
print('Choose a group to scrape members from:') i=0 for g in groups: print(str(i) + '- ' + g.title) i+=1 |
Ask user to enter a number associated with a group. Then use this number as index to get the target group.
1 2 3 |
g_index = input("Enter a Number: ") target_group=groups[int(g_index)] |
Get All Telegram Group Members
The last but not least step is to export all members (participants) of the Telegram group. Fortunately, there is a function for this in Telethon library which makes our job really simple.
Create an empty list of users and get members using the get_participants function and populate the list.
1 2 3 4 |
print('Fetching Members...') all_participants = [] all_participants = client.get_participants(target_group, aggressive=True) |
Important: Set the aggressive parameter to True otherwise you will not get more than 10k members. When aggressive is set to true, Telethon will perform an a-z search in the group’s participants and it usually extracts more than 90% of the members.
Store Scraped Telegram Members in a CSV File
Now use Python’s csv module to store the scraped data in a CSV file. First open a csv file in the write mode with an UTF-8 encoding. This is important because users might have non ASCII names which is very common in Telegram groups. Then create a CSV writer object and write the first row (header) in the CSV file. Finally, loop through every item in the all_participants list and write them to the CSV file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
print('Saving In file...') with open("members.csv","w",encoding='UTF-8') as f: writer = csv.writer(f,delimiter=",",lineterminator="\n") writer.writerow(['username','user id', 'access hash','name','group', 'group id']) 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,user.id,user.access_hash,name,target_group.title, target_group.id]) print('Members scraped successfully.') |
Note 1: Not every user has a username. If the user has no user name the API will return None. To avoid writing None and instead of writing an empty row, check if the user has a user name; otherwise, create an empty string as the username.
Note 2: Similar to the username, some user might don’t have a first name or last name, so we are doing the same thing for name as well.
For some large groups it might take a few minutes to get the members. But finally you should see this message Members scraped successfully. which shows that everything worked perfectly.
So we stored username, name, user id, user hash and the group details for every user in the CSV file. You can use user id and user hash to Add Scraped Telegram Members to Your Group or Send a Message to Telegram Group Members Using Telethon. More on that in next tutorials.
Complete Code of Telegram Group Members Extraction Tutorial
Here is the complete executable code for this tutorial.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
from telethon.sync import TelegramClient from telethon.tl.functions.messages import GetDialogsRequest from telethon.tl.types import InputPeerEmpty import csv api_id = 123456 api_hash = 'YOUR_API_HASH' phone = '+111111111111' client = TelegramClient(phone, api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) client.sign_in(phone, input('Enter the code: ')) 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('Choose a group to scrape members from:') i=0 for g in groups: print(str(i) + '- ' + g.title) i+=1 g_index = input("Enter a Number: ") target_group=groups[int(g_index)] print('Fetching Members...') all_participants = [] all_participants = client.get_participants(target_group, aggressive=True) print('Saving In file...') with open("members.csv","w",encoding='UTF-8') as f: writer = csv.writer(f,delimiter=",",lineterminator="\n") writer.writerow(['username','user id', 'access hash','name','group', 'group id']) 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,user.id,user.access_hash,name,target_group.title, target_group.id]) print('Members scraped successfully.') |
I speak Python!
Majid Alizadeh is a freelance developer specialized in web development, web scraping and automation. He provides high quality and sophisticated software for his clients. Beside Python he works with other languages like Ruby, PHP and JS as well.
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)
YOU DON’T NEED THESE LINE A SECOND TIME…
You are right; thanks! We have removed the repeated part.
I get the following error
File “a.py”, line 13, in
client.send_code_request(phone)
File “C:\Users\***\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\telethon\sync.py”, line 54, in syncified
return loop.run_until_complete(coro)
File “C:\Users\***\AppData\Local\Programs\Python\Python37-32\lib\asyncio\base
_events.py”, line 584, in run_until_complete
return future.result()
File “C:\Users\***\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\telethon\client\auth.py”, line 386, in send_code_request
phone, self.api_id, self.api_hash))
File “C:\Users\****\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\telethon\client\users.py”, line 59, in __call__
result = await future
telethon.errors.rpcerrorlist.FloodWaitError: A wait of 58593 seconds is required
(caused by SendCodeRequest)
Hi Karina! The FloodWaitError requires you to wait an extra time; so you have to avoid it in the first place. Please check our other tutorial on adding the scraped members to your group at: https://python.gotrained.com/adding-telegram-members-to-your-groups-telethon-python/
Hi please am a noob can you make a video on this .
It will be very help full
Cause am lost i have installed the telethon on my ubuntu server
I don know where to go to next
I really need this a video will do
Hi Solomon! We are working on a video, but it takes some time. In the meanwhile try to follow the tutorial step by step and let us know if you have questions.
I have fixed it thanks
Am also using the adding script but peer flood has been my major issue
After 20-40members
And I even increased the time for randomization to 130, 200
Still same thing
Also I a channel script to grow a channel will also be welcomed
i get this thing repeatedly
but there is nothing in the file just the headers usernames , user id etc
what should i do to fix it?
Hi Sadiq! I see you are commenting on the other tutorial of adding members. So have you fixed your issue with scraping them in the first place?
how can i add the users to channel , and filter their recent activity ?
thank you very much
Hello! Hopefully, this helps you:
https://github.com/LonamiWebs/Telethon/issues/781
Hey bro,
It works flawlessly, my question is:
what if i want to list channels instead of supergroups?
can you please explain how you do this? can you contact me on Emai i have one more question bigicxxl@hotmail.com
is here abybody who can give me some link where can have guide how to execute all this commands in python? because i never used python before and not understand how to do all this? is there any youtube guide… thanks
There are many resources that teach Python basics. Check for example the Coursera’s course “Python for Everyone”.
i replace only this :
api_id = 123456
api_hash = ‘YOUR_API_HASH’
phone = ‘+111111111111’
right?
Right.
so if everything is right why then this not working….. can anybody help me?
i have a error :
Traceback (most recent call last):
File “test.py”, line 18, in
result = client(GetDialogsRequest(
NameError: name ‘GetDialogsRequest’ is not defined
how to solve this error?
Hi Sinaaa! Have you imported GetDialogsRequest first?
from telethon.tl.functions.messages import GetDialogsRequest
If yes, check the name of your file; it cannot be “telethon”.
hey, when i try to add with usernames it works fine, but with user id it is showing error releted to apihash
Hello sir… I have a problem in this code… Please can you fix it..
Could you please elaborate on the problem, or you can check other comments.
client.get_participants(target_group, aggressive=True)
is generate WRONG access_hash….
the correct access_hash is from : client.get_input_entity(user[‘username’])
go try your self, the access_hash is different, and the one from “client.get_participants” cannot be used to add member to group because of wrong access_hash….
any clue about this one?
hello mate , i am getting this error , what is the index range ( i mean which number i should give here)
File “C:\python programs\mscraper.py”, line 45, in
target_group=groups[int(g_index)]
IndexError: list index out of range
For scrap the usernames and id from groups..admin only can sarap? Or just memnme of group is sufficient?
Because i am not admin just member of group.
Hello, do you need to be an admin to scrap the members usernames ?
How to fix it?
Traceback (most recent call last):
File “username.py”, line 1, in
from telethon.sync import TelegramClient
File “C:\Program Files (x86)\Python37-32\telethon\__init__.py”, line 1, in
from .client.telegramclient import TelegramClient
File “C:\Program Files (x86)\Python37-32\telethon\client\__init__.py”, line 12, in
from .telegrambaseclient import TelegramBaseClient
File “C:\Program Files (x86)\Python37-32\telethon\client\telegrambaseclient.py”, line 9, in
from ..crypto import rsa
File “C:\Program Files (x86)\Python37-32\telethon\crypto\__init__.py”, line 8, in
from .authkey import AuthKey
File “C:\Program Files (x86)\Python37-32\telethon\crypto\authkey.py”, line 7, in
from ..extensions import BinaryReader
File “C:\Program Files (x86)\Python37-32\telethon\extensions\__init__.py”, line 6, in
from .binaryreader import BinaryReader
File “C:\Program Files (x86)\Python37-32\telethon\extensions\binaryreader.py”, line 9, in
from ..errors import TypeNotFoundError
File “C:\Program Files (x86)\Python37-32\telethon\errors\__init__.py”, line 15, in
from .rpcerrorlist import *
ModuleNotFoundError: No module named ‘telethon.errors.rpcerrorlist’
Please make sure you update/install your Telethon library.
Hey How do i input my users.csv(scrapped from groups) to actually read it
I’m not sure where to put my file name . I get error input_file = sys.argv[1]
Index error : list index out of range.
I believe this question is about another tutorial; we answered it in the comments of the tutorial: Adding Telegram Group Members to Your Groups Using Telethon
I keep getting “NameError: name ‘client’ is not defined” I’m very new to this. Am I putting all the code in at once or one at a time? Im so confused…
which number i have to enter Please anyone tell me
Choose a group to scrape members from:
Enter a Number:
Hi Raj! Your Telegram number.
you have a list like that right?
1 – “telegram group name wow”
2 – “telegram group name lol”
3 – “telegram group name ok”
4 – “telegram group name please”
5 – “telegram group name thank”
6 – “telegram group name you”
so if you want to scrape from the third one “telegram group name ok” you should press 3
How do we get the information of recent activity of the users of that group?
Jamie, check this file and search for UserStatus
hi it works and thnx but what should i do if my groups name have Non-BMP character? TK does not support them.
Saman, do you use Python 3?
Hey GoTrained my man!!!
help me out please
what if i want to scrape a channel which im not an admin at? possible?
thanks in advance
1 more question
1 more question, how can i make the script show hebrew text? its all symbols and unreadable text if the group name is in hebrew…. THANKS AGAIN
For python 3.7 and telethon v1.8, change to “client.connect()” to “client.start()”
Hi. I get this error with target_group=groups[int(g_index)]
Traceback (most recent call last):
File “”, line 1, in
ValueError: invalid literal for int() with base 10: ”
How can I solve it?
I made a mistake and caused this error.
The code works like a charm!
Manoon Majid
nice working like a charm!Maybe a last online or only online members scrape will be nice !