Adding Telegram Group Members to Your Groups Using Telethon

In the previous Telethon tutorial you learned how to send messages to Telegram group members. Now you are going to learn how to add new members to your own group. We will read the member list from the csv file which we extracted in the previous tutorial and add them to our group.

Make sure to check our previous Telethon tutorials to understand the basics of using Telethon and Telegram API.

The first steps are going to be very similar to the previous tutorials. Basically you need to get API keys from telegram and install Telethon using pip.

So let’s get started.

 

Disclaimer: Telegram does not allow adding more than 200 members to a group or channel by one account. Using this script, I am able to add around 150-200 members with 60 second sleep between each add; after that, you have to change to another Telegram account/number.

Get Telegram API Key

As stated in the previous tutorial you need to get your Telegram API credentials to be able to use the API. So do not hesitate and check the previous tutorial and use the guide to get your own Telegram API credentials, or simply follow these steps:

• Sign up for Telegram using any application.
• Log in to your Telegram core: https://my.telegram.org.
• Go to ‘API development tools’ and fill out the form.
• You will get basic addresses as well as the api_id and api_hash parameters required for user authorization.

 

Install Telethon 

Also you need to install Telethon using pip.

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

As usual we have to create  a Telegram client object and check if it is already authorized otherwise ask for an OTP password.

Create a client object.

Note: For the sake of simplicity we are importing  TelegramClient from telethon.sync module.

 

Next, you have to connect the client and check if it is already authorized, otherwise Telegram will send an OTP password to the client and we will ask the user to enter the code which they received.

 

Read Members from CSV File

We are passing the file name in the sys.argv parameters. sys.argv is a list in Python, which contains the command-line arguments passed to the script.

So if you run python sendMessage.py users.csv in the command line  sys.argv will return a list like this:

As you can see, the first item in the list is the name of the script and the second item is the name of our CSV file. So we can access the file name with  sys.argv[1] .

Now you have the name (or path) of our CSV file and you can use Python’s csv module to read the file and create a list of users.

 

Import the required modules

 

Create a dictionary for every user and append that to our user list.

Note: You need to cast the user id and access hash to integer type.

Note: We skip the first row in the CSV file (header) using the  next function.

 

Choose a Group to Add Members

In this step, you are going to ask the user to select a group which they want to add the members to it.

First get all groups using  GetDialogsRequest .

 

Add only super groups to  groups list.

 

Now print all of the groups on screen with their indexes and ask the user to enter the group index they want.

 

Ask for input and get the group using entered index.

 

Get the group entity.

 

Ask User to Enter the Adding Mode

For adding the user we need to get the user entity first. There is two options to do this.

First let’s ask the user which mode they want and then we will explain them one by one.

 

1- By username

Basically you can get any entity in Telethon including users, channels or groups using its username. But as I mentioned before not every user has a username.  So if this mode is selected by user we will skip the users which don’t have a user name while adding. Here is how you can get the user entity by its username.

 

2- By Id and access hash

Every entity in Telegram has an ID and an access hash. The ID is unique but the access hash is different for every telegram account. It means if you scrape the users with an account and you want to add them using another account then you can’t use this mode.

 

Add Members to the Selected Group

Now you have the users in  users  list and the selected group in  target_group . We will use  InviteToChannelRequest function to the add a user to the group. So let’s import it first.

 

Then you need to get the user based on the entered mode (i.e by ID or by user name.

 

Handle Exceptions

Now you can start adding the users but you have to consider some error scenarios.

 

1- PeerFloodError

If you put too much requests on Telegram API or commit tasks very fast, you will get  PeerFloodError . So you need to put a waiting time between each add to prevent this error. We will use 60 seconds in this tutorial to stay safe. But you can play with this number and find the optimum value.

You can also use the random library’s randrange() method giving a random sleep time, say between 60 and 180 seconds. For the sake for clarification, the code below users “print”, but you can of course delete it.

 

2- UserPrivacyRestrictedError

You might get this error for some users depending on their privacy settings.

Finally, let’s add our new members.

 

3. FloodWaitError

If you get this error, you should either wait for the stated time or use another Telegram number.

telethon.errors.rpcerrorlist.FloodWaitError: A wait of 58593 seconds is required
(caused by SendCodeRequest)

So you must avoid this error in the first place. To do so, it is recommended to give an extra sleep time (15 minutes or more) after adding every 50 users. If this will take much time, you can use a cloud server to run your code.

To get a general idea about how this works, run this simple code. Here, you have a list of names; the code loops over names, sleep for 5 seconds after each 10 names, and print the name.

 

As I mentioned earlier, Telegram does not allow adding more than 200 members to a group or channel by one account. Using this script, I am able to add around 150-200 members with 60 second sleep between each add; after that, you have to change to another Telegram account/number.

 

Project Source Code for Adding Members to Telegram Groups Tutorial

Here is the completed code for this tutorial.

 

Full Code with random and extra sleep after 50 users

 

 

You may also like: Scrapy, Powerful Web Scraping with Python

 

 

Rating: 4.4/5. From 43 votes.
Please wait...

55 Replies to “Adding Telegram Group Members to Your Groups Using Telethon”

  1. Amazing! Very Nice Dude!

    Rating: 3.3/5. From 3 votes.
    Please wait...
    1. Thanks, Daniel!

      Rating: 4.1/5. From 11 votes.
      Please wait...
  2. Hello, Thank you for this superb article.
    I’m new to python can you please help me with this error

    Traceback (most recent call last):
    File “C:\Users\AffleTech\test.py”, line 22, in
    input_file = sys.argv[1]
    IndexError: list index out of range

    Rating: 4.4/5. From 27 votes.
    Please wait...
    1. Hi Sadiq! Have you added your file name to your CMD command?

      Check the part of the tutorial under “Read Members from CSV File”. So you have to pass the file name (and path) to the Terminal/CMD command.

      Otherwise, you can replace “input_file” with your CSV file path directly, line #24 of the code. In this case, delete the line “sys.argv[1]” from you code.

      Rating: 3.3/5. From 13 votes.
      Please wait...
      1. Good day Sir,

        Please kindly give me a detailed explanation on how to Add my file name to my CMD command

        I Successfully Created my CSV file . My Issues now is how to read the CSV file then after that I will continue with adding them to Group.

        Thanks for your tutorials …

        Rating: 4.6/5. From 8 votes.
        Please wait...
        1. Afeexzy, please refer to the section “Read Members from CSV File”. You should have something like this in your CMD:
          python sendMessage.py users.csv 

          Rating: 3.3/5. From 4 votes.
          Please wait...
    2. you need to write the argument i.e., members.csv

      so this is the command – add.py members.csv

      Rating: 3.8/5. From 5 votes.
      Please wait...
  3. Hi everyone! Where should i add my .csv file in the code?

    Rating: 3.5/5. From 2 votes.
    Please wait...
    1. Hi Manna! Check the part of the tutorial under “Read Members from CSV File”. So you have to pass the file name (and path) to the Terminal/CMD command.

      Otherwise, you can replace “input_file” with your CSV file path directly, line #24 of the code. In this case, delete the line “sys.argv[1]” from you code.

      Rating: 2.3/5. From 6 votes.
      Please wait...
  4. Getting this error

    Traceback (most recent call last):
    File “C:\Users\AffleTech\updated_script – Copy.py”, line 85, in
    client(InviteToChannelRequest(target_group_entity,[user_to_add]))
    File “C:\Users\AffleTech\AppData\Local\Programs\Python\Python38\lib\site-packages\telethon\sync.py”, line 54, in syncified
    return loop.run_until_complete(coro)
    File “C:\Users\AffleTech\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py”, line 589, in run_until_complete
    return future.result()
    File “C:\Users\AffleTech\AppData\Local\Programs\Python\Python38\lib\site-packages\telethon\client\users.py”, line 59, in __call__
    result = await future
    telethon.errors.rpcerrorlist.UserIdInvalidError: Invalid object ID for a user. Make sure to pass the right types, for instance making sure that the request is designed for users or otherwise look for a different one more suited (caused by InviteToChannelRequest)
    Unexpected Error

    Rating: 4.5/5. From 15 votes.
    Please wait...
    1. Hi Sadiq! How does your CSV file look like?

      Rating: 3.5/5. From 4 votes.
      Please wait...
  5. sendMessage.py = sys.argv[1]
    members.csv = [] i dont get it ,, how do i state the location . can yall please help me with details, thank you

    Rating: 4.0/5. From 2 votes.
    Please wait...
    1. Hello! You have to add your file name and path to your Terminal/CMD command. Check the part of the tutorial under “Read Members from CSV File”.

      Otherwise, you can replace “input_file” with your CSV file path directly, line #24 of the code. In this case, delete the line “sys.argv[1]” from you code.

      Rating: 2.2/5. From 5 votes.
      Please wait...
      1. i saw that comment all ready, i havent understood.

        can you give me an example how does those three lines of script should look like

        Rating: 3.5/5. From 2 votes.
        Please wait...
        1. If you will use the Command Prompt to run your Python file, do not change the code at all, just type:
          python sendMessage.py users.csv

          This will work if your files are in the current folder; otherwise, change the path, for example:
          python C:\Users\BijoRino\Desktop\sendMessage.py C:\Users\BijoRino\Desktop\users.csv

          Please check this article also:
          https://www.wikihow.com/Use-Windows-Command-Prompt-to-Run-a-Python-File

          Rating: 4.3/5. From 3 votes.
          Please wait...
  6. client.connect()
    if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input(‘Enter the code: ‘))

    users = []
    with open(C:\Users\BijoRino\Desktop, encoding=’UTF-8’) as f:
    rows = csv.reader(f,delimiter=”,”,lineterminator=”\n”)
    next(rows, None)
    for row in rows:
    user = {}

    dosent work

    Rating: 3.0/5. From 3 votes.
    Please wait...
    1. Yes, this will not work. You should add the path between quotes. Also, the path here is missing the file name. What can work for example:

      with open("C:\Users\BijoRino\Desktop\users.csv", encoding='UTF-8') as f:

      So here, I have added the CSV file name to the path and made the path enclosed by “quotes”.

      I hope this helps. Please let me know.

      Rating: 4.7/5. From 3 votes.
      Please wait...
      1. Perfect,
        Both comments helped me thank you very much

        i actually used ‘ to quote

        THANK YOU

        Rating: 4.7/5. From 3 votes.
        Please wait...
  7. InviteToChannelRequest doesn’t work
    Can you add event handler and update?

    Rating: 4.0/5. From 4 votes.
    Please wait...
    1. The tutorial worked for other people. Unless you are blocked, it should work.
      What is the error message you get?

      Rating: 4.0/5. From 2 votes.
      Please wait...
  8. is there a way to make the script skip members that are already in the group?

    Rating: 4.4/5. From 5 votes.
    Please wait...
  9. what is this error and how to fix it. i am nooB.
    Traceback (most recent call last):
    File “C:\Users\siddu\Desktop\tg scrapper and adder\adder.py”, line 84, in
    client(InviteToChannelRequest(target_group_entity,[user_to_add]))
    File “C:\Users\siddu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\telethon\sync.py”, line 35, in syncified
    return loop.run_until_complete(coro)
    File “C:\Users\siddu\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py”, line 468, in run_until_complete
    return future.result()
    File “C:\Users\siddu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\telethon\client\users.py”, line 60, in __call__
    result = await future
    telethon.errors.rpcerrorlist.UserIdInvalidError: Invalid object ID for a user. Make sure to pass the right types, for instance making sure that the request is designed for users or otherwise look for a different one more suited (caused by InviteToChannelRequest)

    Rating: 4.3/5. From 4 votes.
    Please wait...
    1. Hello! Try to run it with username instead and see if it works for you.

      Rating: 3.7/5. From 3 votes.
      Please wait...
      1. yeah. it is working with username. but people are not being added to the group even after it is showing as
        adding 843785782
        adding 238840254
        but nobody is being added. . when i tried manually i got error #400 peer_flood

        Rating: 4.8/5. From 4 votes.
        Please wait...
        1. Same problem, Any soloution?

          Rating: 4.3/5. From 3 votes.
          Please wait...
      2. user[‘name’] = row[3]
        users.append(user)

        chats = []
        last_date = None
        chunk_size = 200
        groups=[]

        result = client(GetDialogsRequest(
        offset_date=last_date,
        offset_id=0,

        I’m trying to configure the last_date

        How am i suppose to define it?

        Let’s say i want it to add users only seen in the last 7 days or less.

        Thanks.

        Rating: 3.8/5. From 4 votes.
        Please wait...
    2. i have the same problem

      Rating: 4.0/5. From 2 votes.
      Please wait...
  10. ey bro have a problem with line 74

    Rating: 4.3/5. From 4 votes.
    Please wait...
  11. hello
    i have a problem :
    ————————————
    C:\Users\iMaN\Desktop\py>py add.py members.csv
    Traceback (most recent call last):
    File “add.py”, line 31, in
    user[‘name’] = row[3]
    IndexError: list index out of range
    ————————————-
    example rows if members.csv(This file was created in the first application (scraping…)) :
    ,255631757,8575228332541770229
    mily221,299132080,7406021434165398607
    ******

    plz help me!
    TnX

    Rating: 4.5/5. From 2 votes.
    Please wait...
  12. Good day Sir , my main issue lies on the send Message.py users.csv command

    I tried that on my IDLE and Command prompt it Underlined the sendMessage.py .

    Please help with detailed explanation at that specific part of the code.

    Am running Windows 10 Python 3.7.3 with the latest Telethon.

    Thanks …

    Rating: 4.0/5. From 2 votes.
    Please wait...
    1. You can instead set the file name explicitly in the code. So, instead of:
      input_file = sys.argv[1]
      You can have the file path between quotes like:
      input_file = “c://foldername/users.csv”

      Rating: 4.8/5. From 6 votes.
      Please wait...
  13. Hello Sir, I Read the csv file but when i press 1 to add by Username it stop debugging am using Visual Studio code Please Help me with it

    Rating: 3.8/5. From 4 votes.
    Please wait...
    1. @afeezoo try using CMD or Terminal instead.

      Rating: 5.0/5. From 4 votes.
      Please wait...
  14. Hello Sir I’m done With All I Have a Issue now

    To Skip Existing Users while Adding …

    Rating: 4.0/5. From 2 votes.
    Please wait...
    1. Afeexzy, apparently, you need to find out what usernames/IDs in your group and write a condition not to add existing users.

      Rating: 5.0/5. From 2 votes.
      Please wait...
  15. Great write up. Thanks for creating this resource.

    I found that I need to use time for the sleep(900) call between every 50 users, ie: time.sleep(900)

    Also, I found that I needed to wait longer than 900 seconds, have had positive results with 1800 seconds

    Rating: 4.8/5. From 4 votes.
    Please wait...
    1. Many thanks for your feedback, Camslice!

      Rating: 3.5/5. From 2 votes.
      Please wait...
      1. actually I spoke too soon, it seems Telegram keep changing their time limits for peer flood errors. seems to be somewhere between 12-24 hours now. requires a bit of trial and error

        also i ended up adding sys.exit(1) for the peer flood exception to avoid the script continuing to attempt to add the next user

        Rating: 3.5/5. From 2 votes.
        Please wait...
        1. yes I ve experienced the same the limits time for flood error really varies. I had like 300 seconds after that I could send every 15 seconds (for a other tutorial) for about 20 messages then 400 seconds after that again 15 messages then like 80 seconds flood etc.. needs some trial and error 🙂

          Rating: 4.0/5. From 2 votes.
          Please wait...
  16. How can make anti-flood? every time i use that method i will be banned for 2/3 day, just after 5 action. why ?

    Rating: 3.0/5. From 1 vote.
    Please wait...
    1. Maybe you need another account. Use the script only reasonably and avoid spamming.

      Rating: 3.5/5. From 4 votes.
      Please wait...
  17. How to not get banned after using this script ?

    Rating: 2.8/5. From 4 votes.
    Please wait...
  18. people are not being added to the group even after it is showing as
    adding 843785782
    adding 238840254
    but nobody is being added

    got this error, but I can add through the telegram app.
    Need help.

    Rating: 4.3/5. From 3 votes.
    Please wait...
    1. Maybe you have been banned.

      Rating: 3.5/5. From 2 votes.
      Please wait...
  19. Hi I’m a totally noob (: and have no idea what im doing wrong ,
    I’ve installed pip,telethon
    Now the script you gave us i replaced the correct ID,API,and phone number.
    Now when i run the script > CMD > python.exe scriptname.py

    It gives me an error Line 58 else:
    IndentationError : unident does not match any outer identitaion level
    ):

    Rating: 4.0/5. From 4 votes.
    Please wait...
    1. Please try to study a Python introductory first.

      Rating: 3.8/5. From 5 votes.
      Please wait...
  20. I just finished extracting users from a group

    I am now following the steps to add members to my group

    I changed the csv file name to users.csv

    When I write this code I get the following error

    input_file = sys.argv[1]
    users = []
    with open(input_file, encoding=’UTF-8′) as f:
    rows = csv.reader(f,delimiter=”,”,lineterminator=”n”)
    next(rows, None)
    for row in rows:
    user = {}
    user[‘username’] = row[0]
    user[‘id’] = int(row[1])
    user[‘access_hash’] = int(row[2])
    user[‘name’] = row[3]
    users.append(user)

    this is the error i get

    Traceback (most recent call last):
    File “”, line 3, in
    FileNotFoundError: [Errno 2] No such file or directory: ‘–mode=client’

    Even if i add the csv location it still gives the same error.

    Rating: 3.5/5. From 2 votes.
    Please wait...
    1. Mitchel, apparently you are adding the file path in the wrong order. The error states you are giving a file named “–mode=client”; so make sure you add the argument correctly in your CMD/Terminal.

      Rating: 3.0/5. From 4 votes.
      Please wait...
  21. chats = []
    last_date = None
    chunk_size = 200
    groups=[] My question is how to define”last_date” so i can retrieve only people connected last week per se? thanks in advance

    Rating: 4.3/5. From 4 votes.
    Please wait...
  22. BTW i avoid peerflood by adding every800-900 seconds, no stop breaks no nothing.
    95\100 bots finished a 200 people list each, in 2 days without being spam..

    just some info for yall. Peace

    Rating: 4.6/5. From 5 votes.
    Please wait...
  23. I could add only 50 users per day per phone number . Is there any steps where we can add proxy or giving multiple phone number and api key?

    Rating: 4.3/5. From 12 votes.
    Please wait...
  24. how can I ask the programme to skip members already in the group ?

    Rating: 3.6/5. From 5 votes.
    Please wait...
    1. @Ifeoluwa – one way is to extract the members in the old group to a list and add the new member only if not in the group.

      Rating: 4.5/5. From 2 votes.
      Please wait...
  25. after i put my hash and api and run it it return error “expected an indented block” any thoughts ?thx

    Rating: 4.0/5. From 3 votes.
    Please wait...
    1. @Limbo – you need to revise the code indentation.

      Rating: 4.7/5. From 3 votes.
      Please wait...

Comments are closed.