Showing posts with label telegram import. Show all posts
Showing posts with label telegram import. Show all posts

Friday, April 15, 2022

Telegram - Import Members into a Public Group

 

There are two conditions to import group members of a telegram public group.

    1) It should be a Public group but you do not need to be an administrator or owner of the group, You can import / export members of any public group, just you should be a member of the group.

    2) If a member has selected ‘My Contacts’ option in ‘who can add you to groups and channels’ then you should be added in his/her contact list, only then you can import him/her into a group.

To import group members, First Generate api id and api hash in your telegram account. To do this open my.telegram.org
Login using your registered phone number.
Now Open Link Development Tools and copy your api id and hash
We will use the api id and hash in the Python Script

 Create virtual environment with python 3 and install Telethon using pip.

virtualenv telegram -p /usr/bin/python3
source telegram/bin/activate
pip install Telethon==1.23.0

Update API ID, API hash and telegram registered phone number in the following python script import.py.

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

api_id = 9999999
api_hash = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'
phone = '+919999999999'
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: '))

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)

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)
print('======')
mode = int(input("Enter 1 to add by username or 2 to add by ID: "))

for user in users:
    try:
        print ("Adding {}".format(user['id']))
        if mode == 1:
            if user['username'] == "":
                continue
            user_to_add = client.get_input_entity(user['username'])
            print(user['username'])
        elif mode == 2:
            user_to_add = InputPeerUser(user['id'], user['access_hash'])
            print(user_to_add)
        else:
            sys.exit("Invalid Mode Selected. Please Try Again.")
        print(target_group_entity)
        client(InviteToChannelRequest(target_group_entity,[user_to_add]))
        print("Waiting 60 Seconds...")
        time.sleep(60)
    except PeerFloodError:
        print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
    except UserPrivacyRestrictedError:
        print("The user's privacy settings do not allow you to do this. Skipping.")
    except:
        traceback.print_exc()
        print("Unexpected Error")
        continue
Run the Python script in the same virtual env.

python import.py members.csv

Pass members.csv as an argument. It has all the exported group members. members.csv should be in same directory where you are running the script.

It will list all your public groups. Choose number of the channel into you want to import members. Members will be imported in the group. 

To see the steps :

 



If you want to export telegram group members, check other post of the blog.

https://linuxamination.blogspot.com/2022/04/telegram-export-members-of-public-group.html