1 Best way to add members to Telegram group(2021 using python)

This post for those who want to add members to thier telegram group, which could take forever if we do manually, hence we can automate this take. I'm using python for this automation. Using the python script called telethon we can add members to the group. The daliy limit is 200 members. The script adds members with 60-180 sec intervals to avoid bans.

you need the following installed in your computer :

1.python 3 (recent one would be better)

2.pip install of python installed(we can enable this option while install python choosing custom install)

3.telethon package installed using pip installer.

4.telegram group api registered in the telegram website.

5.good internet(mandatory)

1.Install python 3 CODE : 

visit python.org for downloading and installing the windows pacakge.

Note: 1.choose the custom installing to enable necessary installers in windows.

          2.if you are on the linux or mac python is defaultly installed. just update it. 

2. pip installer  

Note: in linux and mac python pip installer is defaultly installed.

3. 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. for windows open c

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.md using admin previllage type pip install in :

4.Get Telegram API Key

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.

The script for scrapping the people from the other groups :

Note :  in order to get list of people of any group you need to be one of member of the group in your account. otherwise it won't work.

the created file will be stored as Scrapped.csv file in same directory of script.

CODE
  
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import csv
api_id =   1234567                       #enter here api_id
api_hash = 'k564865366242fda6eab4892eada9d34e2' #Enter here api_hash id
phone = '+111111111111'   #enter here phone number with country code
client = TelegramClient(phone, api_id, api_hash)
async def main():
    # Now you can use all client methods listed below, like for example...
    await client.send_message('me', 'Hello !!!!')
with client:
    client.loop.run_until_complete(main())
client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter verification 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('From Which Group Yow Want To Scrap A Members:')
i=0
for g in groups:
    print(str(i) + '- ' + g.title)
    i+=1

g_index = input("Please! 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("Scrapped.csv","w",encoding='UTF-8') as f:#Enter your file name.
    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.......')
  

The script for adding the people from the other groups :

CODE : 

  
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.channels import InviteToChannelRequest
import sys
import csv
import traceback
import time
import random

api_id =   1234567                       #enter here api_id
api_hash = 'k564865366242fda6eab4892eada9d34e2' #Enter here api_hash id
phone = '+111111111111' client = TelegramClient(phone, api_id, api_hash)
async def main():
    # Now you can use all client methods listed below, like for example...
    await client.send_message('me', 'Hello !!!!!')


SLEEP_TIME_1 = 100
SLEEP_TIME_2 = 100
with client:
    client.loop.run_until_complete(main())
client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('40779'))

users = []
with open(r"Scrapped.csv", encoding='UTF-8') as f:  #Enter your file name
    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)

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 add members:')
i = 0
for group in groups:
    print(str(i) + '- ' + group.title)
    i += 1

g_index = input("Enter a Number: ")
target_group = groups[int(g_index)]

target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash)

mode = int(input("Enter 1 to add by username or 2 to add by ID: "))

n = 0

for user in users:
    n += 1
    if n % 80 == 0:
        sleep(60)
    try:
        print("Adding {}".format(user['id']))
        if mode == 1:
            if user['username'] == "":
                continue
            user_to_add = client.get_input_entity(user['username'])
        elif mode == 2:
            user_to_add = InputPeerUser(user['id'], user['access_hash'])
        else:
            sys.exit("Invalid Mode Selected. Please Try Again.")
        client(InviteToChannelRequest(target_group_entity, [user_to_add]))
        print("Waiting for 60-180 Seconds...")
        time.sleep(random.randrange(60, 90))
    except PeerFloodError:
        print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
        print("Waiting {} seconds".format(SLEEP_TIME_2))
        time.sleep(SLEEP_TIME_2)
    except UserPrivacyRestrictedError:
        print("The user's privacy settings do not allow you to do this. Skipping.")
        print("Waiting for 5 Seconds...")
        time.sleep(random.randrange(5, 0))
    except:
        traceback.print_exc()
        print("Unexpected Error")
        continue

  

Comments

Popular posts from this blog

"Kernel Panic” error After upgrading Parrot OS

HACK HC-05(BLUETOOTH MODULE) FRIMWARE INTO HID FRIMWARE