Skip to content

Instantly share code, notes, and snippets.

@hoai97nam
Created June 22, 2020 07:55
Show Gist options
  • Save hoai97nam/c0a9b0e5fea2ba62142eff500a785be9 to your computer and use it in GitHub Desktop.
Save hoai97nam/c0a9b0e5fea2ba62142eff500a785be9 to your computer and use it in GitHub Desktop.
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 = <your_API_id>
api_hash = '<your_API_hash>'
phone = '<your_phone_number>'
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(float(row[2])) # changing something in data type
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: "))
i = 1 #testing numbering
for user in users:
try:
print ("{}. Adding {}".format(i, user['id'])) # this location "i"
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 60 Seconds...")
time.sleep(20) #sleep 900 instead 60
i = i + 1 # this location increases counting unit
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment