Ошибка adder.py при запуске telegram добавить пользовательский код Python на Windows 10
!/ USR / бен /python3
из настроек импортировать ПОЛЬЗОВАТЕЛИ из telethon импортировать TelegramClient из telethon.tl.types import ChannelParticipantsSearch, PeerChannel, InputUser, User, Chat, InputChannel из telethon.tl.functions.channels import GetParticipantsRequest, InviteToChannelRequest, JoinChannelRequest from importthonunsslv. импорт ос импорт время импорта системный импорт JSON
def telegram_connect (пользователь): client = TelegramClient ('сессий /' + пользователь ['телефон'], пользователь ['api_id'], пользователь ['api_hash']) client.connect (), если не client.is_user_authorized (): try: print ('Генерация кода для' + '(' + user ['phone'] + '), пожалуйста, подождите...') client.send_code_request (user ['phone']) client.sign_in (user ['phone' ], ввод ('Введите код:'))
while not client.is_user_authorized():
print('Bad passcode. Press "s" to skip this user.')
code = input('Enter the code: ')
if code == 's':
print('Skipping authorization of user ' + user['phone'])
break
time.sleep(2)
client.sign_in(user['phone'], code)
if client.is_user_authorized():
print(user['phone'] + ' successfully authorized.')
time.sleep(5)
pass
except Exception as e:
print(e)
print('Skipping this user...')
time.sleep(5)
pass
else:
print(user['phone'] + ' already authorized.')
time.sleep(5)
return client
def scrape (клиент): диалоги, сущности = client.get_dialogs (100)
avail_channels = {}
channel_id = None
for i, entity in enumerate(entities):
if not isinstance(entity, User) and not isinstance(entity, Chat):
avail_channels[str(i)] = [entity.title, entity.id]
for k, v in avail_channels.items():
print(k, v[0])
if len(avail_channels) < 1:
print('No super groups to scrape from.')
sys.exit()
channel_index = input("Please select number of super group you want to scrape> ")
channel = client.get_entity(PeerChannel(avail_channels[channel_index][1]))
# dialogs=client.get_dialogs(500)
# entity=None
# for dialog in self.dialogs:
# if not isinstance(dialog.input_entity, InputPeerUser) and not isinstance(dialog.input_entity,InputPeerSelf):
# avail_channels.append(dialog.name)
# if isinstance(dialog.input_entity, InputPeerChannel) and dialog.name==target_group:
# entity=dialog.input_entity
offset = 0
limit = 200
all_participants = []
users = []
while True:
try:
participants = client.invoke(GetParticipantsRequest(channel, ChannelParticipantsSearch(''), offset,limit))
if not participants.users:
break
all_participants.extend(participants.users)
offset += len(participants.users)
except Exception as e:
print(e)
sys.exit()
for item in all_participants:
users.append(
{'username': item.username, 'id': item.id, 'access_hash': item.access_hash})
with open('saksham.json', 'w') as f:
json.dump(users, f, indent=4)
print("All users of the channel " + avail_channels[channel_index][
0] + " has been stored into " + "saksham.json file.")
def add_users (client, file_name): диалоги, лица = client.get_dialogs (100)
avail_channels = {}
channel = None
channel_id = None
channel_access_hash = None
for i, entity in enumerate(entities):
if not isinstance(entity, User) and not isinstance(entity, Chat):
avail_channels[str(i)] = [entity, entity.id, entity.access_hash, entity.title]
for k,v in avail_channels.items():
print(k, v[3])
channel_index = input("Please select number of supergroup where you want to add users> ")
#participants = client.invoke(GetParticipantsRequest(avail_channels[channel_index][0], ChannelParticipantsSearch(''), 0, 0))
#count_of_members_before_adding = len(participants.users)
users = None
try:
with open(file_name, 'r') as f:
users = json.load(f)
except Exception:
print('Invalid file name, make sure you have added extension or if file even exists, if not, run scrape_channel_users.py to create one!')
sys.exit()
count = int(input('Do you want to add only subset of users('+ str(len(users)) +')? if so, enter the number of users to be added: '))
users_to_save_back = users[count:] # only users, which didnt be used, will be saved to file again
print(str(len(users_to_save_back)) + ' users to be saved back to json file!')
users = users[:count] # users to be added
print(str(len(users)) + ' users to be removed from list!')
print()
with open(file_name, 'w') as f:
json.dump(users_to_save_back, f, indent=4)
input_users = []
for item in users:
input_users.append(InputUser(item['id'], item['access_hash']))
user_chunks = list(chunks(input_users, 60))
for item in user_chunks:
try:
client(InviteToChannelRequest(InputChannel(avail_channels[channel_index][1], avail_channels[channel_index][2]), item))
print('Adding chunk of '+ str(len(item)) +' users...')
time.sleep(2)
except Exception as e:
print(str(e))
print('some error occurred, skipping to next chunk.')
time.sleep(2)
print('There was attempt to add ' + str(len(input_users)) + ' users in total.')
#participants = client.invoke(GetParticipantsRequest(avail_channels[channel_index][0], ChannelParticipantsSearch(''), 0, 0))
#count_of_members_after_adding = len(participants.users)
#print('Count of members before adding: ' + str(count_of_members_before_adding))
#print('Count of members after adding: ' + str(count_of_members_after_adding))
print()
#print('True number of added users: ' + str(count_of_members_after_adding - count_of_members_before_adding))
print('added')
def chunks (l, n): # Для элемента i в диапазоне, равном длине l, для i в диапазоне (0, len (l), n): yield l [i: i + n]
def remove (x): users = None с открытым (file_name, 'r') как f: users = json.load (f) value1 = x
# value1 = int (input ("В файле есть" + str (len (users)) + ". Введите, сколько вы хотите удалить:")) print ("Удалить" + str (value1) + "users") users_to_save_back = users [value1:] # только пользователи, которые не были использованы, будут сохранены в файл снова. print (str (len (users_to_save_back)) + 'пользователи будут сохранены обратно в файл json!') с открытым (file_name, 'w ') как f: try: json.dump (users_to_save_back, f, indent = 4) за исключением исключения как e: print (e)
опции def (client, file_name): client1 = client file_name1 = file_name, в то время как True: value = input ("Нажмите 1 для добавления, если не 50, 2 для удаления из json, еще до конца:"), если значение == "1": add_users (client1, file_name1) elif value == "2": value2 = input ("Сколько?") удалить (value2)
еще: перерыв
if name == 'main': для пользователя в USERS:
#user = check_arguments ()
client = telegram_connect (пользователь) entity1 = client.get_entity ('lokchain_official') клиент (JoinChannelRequest(entity1))
entity4=client.get_entity('binance_chat') клиент (JoinChannelRequest(entity4))
# entity2=client.get_entity('mpcoins')
# client(JoinChannelRequest(entity2))
# entity3=client.get_entity('krmkorea')
# client(JoinChannelRequest(entity3))
# try:
# updates = client(ImportChatInviteRequest('GTYgykQDpwkxGdZFWKI2lg')) обновлений 'IDoS7As-UypXFtuwxT841g'))
# за исключением исключения как e:
# pass
scrape (клиент)
file_name= "saksham.json"
# удалить (1500) опции add_users (клиент, имя_файла) (клиент, имя_файла) client.disconnect ()