├── README.md └── auto-add.py /README.md: -------------------------------------------------------------------------------- 1 | # A simple script to export members from Telegram Groups and Channels to a CSV file and to automatically add members to Telegram Groups. 2 | 3 | > Exporting and adding members to channels requires the user from which the script is launched to be a Channel admin. 4 | 5 | ### Watch this YouTube Video To Know How To Use This Script: 6 | [Auto Add Members In Telegram Group](https://youtu.be/WThZuzpswsw) 7 | 8 | ### Read More Blogs About Termux And CyberWorld: 9 | [amanbytes.com](https://amanbytes.com/) 10 | 11 | ### Install dependencies 12 | 13 | ### **python3** and **pip3** must be installed and available in your PATH. 14 | 15 | ### install telethon module by executing command 16 | pip3 install telethon 17 | 18 | ### Telegram Configuration 19 | 20 | 1. To run it you need to generate API credentials for your Telegram user, you can do it [here](https://core.telegram.org/api/obtaining_api_id), and access your already created ones [here](https://my.telegram.org/apps) 21 | 2. Replace your credentials in the python script 22 | 23 | ``` 24 | api_id = 12345 # Your API ID 25 | 26 | api_hash = 'XXXXXXXXXXXXXXX' # Your API Hash 27 | 28 | phone = '+11234567890' # Your Phone Number With Country Code. 29 | ``` 30 | 31 | ### Exporting users 32 | 33 | Just follow the instructions in the script after running it from your shell. 34 | 35 | ### Adding users to groups 36 | 37 | Users can be added using: 38 | 39 | - **Username**: Gets temporarily banned with less requests. 40 | 41 | - **User ID**: Gets temporarily banned with more requests. 42 | 43 | > *Temporarily bans lasts for up to a day* 44 | 45 | Adding users by Username expects a CSV file with one username per line. 46 | Adding users by User ID expects a CSV file such as: `username,user_id,user_access_hash` 47 | -------------------------------------------------------------------------------- /auto-add.py: -------------------------------------------------------------------------------- 1 | from telethon.sync import TelegramClient 2 | from telethon.tl.functions.messages import GetDialogsRequest 3 | from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser 4 | from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError 5 | from telethon.tl.functions.channels import InviteToChannelRequest 6 | from telethon.errors import SessionPasswordNeededError 7 | import getpass 8 | import sys 9 | import csv 10 | import traceback 11 | import time 12 | import random 13 | import re 14 | 15 | 16 | api_id = 12345 #Your Api ID 17 | api_hash = 'XXXXXXXXXXXXXXX' #Your Api Hash 18 | phone = '+11234567890' # Your Phone Number With Country Code. 19 | client = TelegramClient(phone, api_id, api_hash) 20 | 21 | client.connect() 22 | if not client.is_user_authorized(): 23 | client.send_code_request(phone) 24 | client.sign_in(phone) 25 | try: 26 | client.sign_in(code=input('Enter code: ')) 27 | except SessionPasswordNeededError: 28 | client.sign_in(password=getpass.getpass()) 29 | 30 | def add_users_to_group(): 31 | input_file = sys.argv[1] 32 | users = [] 33 | with open(input_file, encoding='UTF-8') as f: 34 | rows = csv.reader(f,delimiter=",",lineterminator="\n") 35 | next(rows, None) 36 | for row in rows: 37 | user = {} 38 | user['username'] = row[0] 39 | try: 40 | user['id'] = int(row[1]) 41 | user['access_hash'] = int(row[2]) 42 | except IndexError: 43 | print ('users without id or access_hash') 44 | users.append(user) 45 | 46 | random.shuffle(users) 47 | chats = [] 48 | last_date = None 49 | chunk_size = 10 50 | groups=[] 51 | 52 | result = client(GetDialogsRequest( 53 | offset_date=last_date, 54 | offset_id=0, 55 | offset_peer=InputPeerEmpty(), 56 | limit=chunk_size, 57 | hash = 0 58 | )) 59 | chats.extend(result.chats) 60 | 61 | for chat in chats: 62 | try: 63 | if chat.megagroup== True: #Condition To Only List Megagroups 64 | groups.append(chat) 65 | except: 66 | continue 67 | 68 | print('Choose a group to add members:') 69 | i=0 70 | for group in groups: 71 | print(str(i) + '- ' + group.title) 72 | i+=1 73 | 74 | g_index = input("Enter a Number: ") 75 | target_group=groups[int(g_index)] 76 | print('\n\nChosen Group:\t' + groups[int(g_index)].title) 77 | 78 | target_group_entity = InputPeerChannel(target_group.id,target_group.access_hash) 79 | 80 | mode = int(input("Enter 1 to add by username or 2 to add by ID: ")) 81 | 82 | error_count = 0 83 | 84 | for user in users: 85 | try: 86 | print ("Adding {}".format(user['username'])) 87 | if mode == 1: 88 | if user['username'] == "": 89 | continue 90 | user_to_add = client.get_input_entity(user['username']) 91 | elif mode == 2: 92 | user_to_add = InputPeerUser(user['id'], user['access_hash']) 93 | else: 94 | sys.exit("Invalid Mode Selected. Please Try Again.") 95 | client(InviteToChannelRequest(target_group_entity,[user_to_add])) 96 | print("Waiting 60 Seconds...") 97 | time.sleep(60) 98 | except PeerFloodError: 99 | print("Getting Flood Error from Telegram. You should stop script now.Please try again after some time.") 100 | except UserPrivacyRestrictedError: 101 | print("The user's privacy settings do not allow you to do this. Skipping.") 102 | except: 103 | traceback.print_exc() 104 | print("Unexpected Error") 105 | error_count += 1 106 | if error_count > 10: 107 | sys.exit('too many errors') 108 | continue 109 | 110 | def list_users_in_group(): 111 | chats = [] 112 | last_date = None 113 | chunk_size = 200 114 | groups=[] 115 | 116 | result = client(GetDialogsRequest( 117 | offset_date=last_date, 118 | offset_id=0, 119 | offset_peer=InputPeerEmpty(), 120 | limit=chunk_size, 121 | hash = 0 122 | )) 123 | chats.extend(result.chats) 124 | 125 | for chat in chats: 126 | try: 127 | print(chat) 128 | groups.append(chat) 129 | # if chat.megagroup== True: 130 | except: 131 | continue 132 | 133 | print('Choose a group to scrape members from:') 134 | i=0 135 | for g in groups: 136 | print(str(i) + '- ' + g.title) 137 | i+=1 138 | 139 | g_index = input("Enter a Number: ") 140 | target_group=groups[int(g_index)] 141 | 142 | print('\n\nGrupo elegido:\t' + groups[int(g_index)].title) 143 | 144 | print('Fetching Members...') 145 | all_participants = [] 146 | all_participants = client.get_participants(target_group, aggressive=True) 147 | 148 | print('Saving In file...') 149 | with open("members-" + re.sub("-+","-",re.sub("[^a-zA-Z]","-",str.lower(target_group.title))) + ".csv","w",encoding='UTF-8') as f: 150 | writer = csv.writer(f,delimiter=",",lineterminator="\n") 151 | writer.writerow(['username','user id', 'access hash','name','group', 'group id']) 152 | for user in all_participants: 153 | if user.username: 154 | username= user.username 155 | else: 156 | username= "" 157 | if user.first_name: 158 | first_name= user.first_name 159 | else: 160 | first_name= "" 161 | if user.last_name: 162 | last_name= user.last_name 163 | else: 164 | last_name= "" 165 | name= (first_name + ' ' + last_name).strip() 166 | writer.writerow([username,user.id,user.access_hash,name,target_group.title, target_group.id]) 167 | print('Members scraped successfully.') 168 | 169 | def printCSV(): 170 | input_file = sys.argv[1] 171 | users = [] 172 | with open(input_file, encoding='UTF-8') as f: 173 | rows = csv.reader(f,delimiter=",",lineterminator="\n") 174 | next(rows, None) 175 | for row in rows: 176 | user = {} 177 | user['username'] = row[0] 178 | user['id'] = int(row[1]) 179 | user['access_hash'] = int(row[2]) 180 | users.append(user) 181 | print(row) 182 | print(user) 183 | sys.exit('FINITO') 184 | 185 | # print('Fetching Members...') 186 | # all_participants = [] 187 | # all_participants = client.get_participants(target_group, aggressive=True) 188 | print('Sucessfully Connected! ') 189 | print('What do you want to do:') 190 | mode = int(input("Enter \n1 - List users in a group\n2 - Add users from CSV to Group (CSV must be passed as a parameter to the script)\n3 - Show CSV\n\nYour option: ")) 191 | 192 | if mode == 1: 193 | list_users_in_group() 194 | elif mode == 2: 195 | add_users_to_group() 196 | elif mode == 3: 197 | printCSV() 198 | --------------------------------------------------------------------------------